NLog 不记录(Asp.net core with .net 4.6.2)

NLog not logging (Asp.net core with .net 4.6.2)

我正在使用 asp.net 核心项目和完整的 .net 框架 4.6.2,使用 NLog.Web.AspNetCore (4.3.1) nuget 包。以下是我的配置。

nlog.config

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  autoReload="true"
  internalLogLevel="Warn"
  internalLogFile="c:\Logs\internal-nlog.txt">
  <!-- define various log targets -->
<targets>
  <!-- write logs to file -->
    <target xsi:type="File" name="allfile" fileName="c:\Logs\nlog-all-${shortdate}.log"
        layout="${longdate}|${logger}|${uppercase:${level}}|${message} ${exception:format=stacktrace}"
        maxArchiveFiles="100"
        archiveFileName="c:\LogsBackup\nlog-all-${shortdate}.{##}.log"
        archiveNumbering="DateAndSequence"
        archiveAboveSize="10000000"
        archiveDateFormat="yyyyMMdd" />
    <target xsi:type="File" name="ownFile-web" fileName="c:\Logs\nlog-own-${shortdate}.log"
         layout="${longdate}|${logger}|${uppercase:${level}}|  ${message} ${exception:format=stacktrace}" />
    <target xsi:type="Null" name="blackhole" />
</targets>
<rules>
  <!--All logs, including from Microsoft-->
  <logger name="*" minlevel="Trace" writeTo="allfile" />
  <!--Skip Microsoft logs and so log only own logs-->
  <!--<logger name="Microsoft.*" minlevel="Trace" writeTo="blackhole" final="true" />-->
  <!--<logger name="*" minlevel="Trace" writeTo="ownFile-web" />-->
</rules>
</nlog>

Startup.cs

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
  {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();

        //add nlog
        //env.ConfigureNLog("nlog.config");
        //loggerFactory.ConfigureNLog("nlog.config");
        //loggerFactory.AddNLog();
        app.AddNLogWeb();

        //add identity server authentication
        //app.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions
        //{
        //    Authority = "http://localhost:5000",
        //    RequireHttpsMetadata = false,
        //    ApiName = "prismapi"
        //});

        app.UseMvcWithDefaultRoute();

        app.UseSwagger();
        app.UseSwaggerUI(options =>
        {
            options.SwaggerEndpoint("/swagger/v1.0/swagger.json", "Prism api version 1");
        });
  }

出于某种原因,它没有发出日志。 Nlog 甚至没有创建其内部日志文件。有趣的是,如果我取消注释 env.ConfigureNLog("nlog.config");,它至少会开始创建其内部日志文件,但实际日志文件仍然没有成功。

可能您需要在 Configure 方法中的 app.AddNLogWeb(); 之前取消注释 loggerFactory.AddNLog();

根据文档中的示例,

env.ConfigureNLog("nlog.config"); 应该在构造函数中。

请同时查看 https://github.com/NLog/NLog.Extensions.Logging

中的 How to use 部分

我还想建议从与示例中相同的代码行开始。如果可行,请根据您的需要进行更改。

希望这对您有所帮助。