在您的MyCustomDB上下文中.
通过构造函数输入以下内容:
Microsoft.Extensions.Logging.ILoggerFactory
(这是为了向接口编码,而不是具体的,Serilog是具体的)
然后使用您注入的ILoggerFactory.将"作为生成的SQL陈述的目标".如下所示:
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Microsoft.EntityFrameworkCore;
public class MyCustomDbContext : DbContext
{
public const string ErrorMessageILoggerFactoryWrapperIsNull = "ILoggerFactory is null";
private readonly Microsoft.Extensions.Logging.ILoggerFactory loggerFactory;
public MyCustomDbContext(
ILoggerFactoryWrapper loggerFactory,
DbContextOptions<MyCustomDbContext> options)
: base(options)
{
this.loggerFactory = loggerFactory ?? throw new ArgumentNullException(
ErrorMessageILoggerFactoryWrapperIsNull,
(Exception)null);
/* note, the base-class checks for null for the DbContextOptions-"options" */
}
// your "DbSet's" HERE, now shown.
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
base.OnConfiguring(optionsBuilder);
// null is possible if you are using an IDesignTimeDbContextFactory
// below, you should also consider the use of IHostEnvironment values .. to avoid putting sql-statements in production. see : https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.hosting.hostenvironmentenvextensions.isdevelopment?view=dotnet-plat-ext-8.0
if (null != this.loggerFactory)
{
//// NOT SHOWN ::: Probably should not log sql statements in production, so use hostEnvironment "flags" to only do it when a developer is involved.
///but below..is the primary "magic" to get Sql statements to show up.
optionsBuilder.UseLoggerFactory(this.loggerFactory);
// other non-related options shown above
//optionsBuilder.EnableSensitiveDataLogging();
//optionsBuilder.EnableDetailedErrors();
}
}
当然..在你知道后(通过这个回答)..神奇的方法名称..很容易在互联网上搜索并找到这样的文章:
https://www.infoworld.com/article/3679528/how-to-work-with-logging-in-entity-framework-core-7.html
而且..在微软.
https://learn.microsoft.com/en-us/ef/core/logging-events-diagnostics/extensions-logging?tabs=v3#other-application-types
恕我直言,不要落入"简单"的诱惑.(在微软文章中). 花几分钟时间连接您的"真正"ILoggerFactory / ILogger.
写入"控制台".是短视的.