如何通过 NLog 记录 Entity Framework Core 操作

Fla*_*ght 4 nlog entity-framework-core .net-core entity-framework-core-2.1

我想使用 NLog 以类似于 WebApi Core 的方式记录来自 Entity Framework Core 的 SQL 查询。我该如何设置?

Jul*_*ian 7

对于实体框架核心日志有一些文档在这里

你需要这个:(见文档)

public static readonly LoggerFactory MyLoggerFactory
    = new LoggerFactory(new[] {new ConsoleLoggerProvider((_, __) => true, true)});
Run Code Online (Sandbox Code Playgroud)

并使用这个包NLogLoggerProvider中的ConsoleLoggerProvider,而不是 : https://www.nuget.org/packages/NLog.Extensions.Logging

和这样的事情:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    => optionsBuilder
        .UseLoggerFactory(MyLoggerFactory) // Warning: Do not create a new ILoggerFactory instance each time
        .UseSqlServer(
            @"Server=(localdb)\mssqllocaldb;Database=EFLogging;Trusted_Connection=True;ConnectRetryCount=0");
Run Code Online (Sandbox Code Playgroud)

您还需要加载您的 NLog 配置文件:

NLog.LogManager.LoadConfiguration("nlog.config");
Run Code Online (Sandbox Code Playgroud)

当然,您需要一个 nlog 配置(nlog.config 或可以在 C# 中),请检查https://github.com/NLog/NLog/wiki/Configuration-file

更新:根据评论效果很好:)