c# - ASP.NET Core 日志记录不适用于生产

标签 c# logging nlog serilog asp.net-core-logging

Turns out the issue was not anyway related to NLog or ASP.NET Logging system. Logging was configured correctly but the build server was publishing a Debug build to the Production due to a configuration error.

我正在尝试在我的 ASP.NET Core 2.0 (SDK 2.1.401) 项目中设置第三方记录器。到目前为止,我已经尝试过 SerilogNLog。但是我对两者都有同样的问题。总结这个问题,

  • 当我像 dotnet run 一样运行应用程序时(即在 Development 环境中),它按预期工作
  • 但当我运行二进制 dotnet MyApplication.dll 时(即在 Production 环境中),它不会。
  • 我的 appsettings.Development.json 文件中的 “Logging” 部分没有为 Development 环境定义任何内容。

下面描述的问题是针对 NLog 的。我已经尝试过 SeriLog 并遇到了同样的问题。

这是来自 Program.cs

的相关部分
public static IWebHost BuildWebHost(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .UseApplicationInsights()
        .UseStartup<Startup>()
        .ConfigureLogging((env, logging) =>
        {
            logging.ClearProviders();
            logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
        })
        .UseNLog()
        .Build();

注意 我已经清除了所有提供程序并添加了 NLog 还定义了 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="error"
  internalLogFile="./internal-nlog.txt">

  <extensions>
    <add assembly="NLog.Web.AspNetCore"/>
  </extensions>

  <targets>
    <target name="Console" 
      xsi:type="Console" 
      layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}" />
  </targets>

  <rules>
    <logger name="*" minlevel="Trace" writeTo="Console" />
  </rules>
</nlog>

Development 模式下运行时,我看到的日志完全符合我的预期

$ dotnet run
Using launch settings from .. /Properties/launchSettings.json...
2018-09-16 19:04:39.7585||DEBUG|My.WebApp.Program|init main |url: |action:
Hosting environment: Development
Content root path: /Users/ ...
Now listening on: http://localhost:61638
Application started. Press Ctrl+C to shut down.
2018-09-16 19:04:46.5405|1|INFO|Microsoft.AspNetCore.Hosting.Internal.WebHost|Request starting HTTP/1.1 GET http://localhost:61638/api/_doc   |url: http://localhost/api/_doc|action:
2018-09-16 19:04:46.7381|1|INFO|Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker|Executing action method My.WebApp.RestApi.Doc (My.WebApp) with arguments ((null)) - ModelState is Valid |url: http://localhost/api/_doc|action: Doc

但是,当我在 Production 环境中运行该应用程序时,控制台输出看起来好像我没有安装 NLog 并且我没有清除默认提供程序。

dotnet .\My.WebApp.dll
Hosting environment: Production
Content root path: C:\inetpub\wwwroot\myapp\wwwroot
Now listening on: http://localhost:5000
Application started. Press Ctrl+C to shut down.
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
      Request starting HTTP/1.1 GET http://localhost:5000/
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[1]
      Executing action method My.WebApp.Controllers.HomeController.Index (My.WebApp) with arguments ((null)) - ModelState is Valid

注意那些以 info: 开头的行了吗?这些是您在使用 Microsoft.Extensions.Logging 中定义的默认日志记录设置时获得的标准控制台日志记录格式。但我确实通过调用 Program.cs 文件中的 logging.ClearProviders(); 清除了 Console 提供程序。

感谢您的帮助。

最佳答案

我能够重现您的问题并修复它。请在此处找到我的配置。

应用设置.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Trace",
      "Microsoft": "Information"
    }
  },
  "AllowedHosts": "*"
}

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="error"
      internalLogFile="./internal-nlog.txt">

  <extensions>
    <add assembly="NLog.Web.AspNetCore"/>
  </extensions>

  <targets>
    <target name="Console"
            xsi:type="Console"
            layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}" />
  </targets>

  <rules>
    <logger name="*" minlevel="Trace" writeTo="Console" />

    <!--Skip non-critical Microsoft logs and so log only own logs-->
    <logger name="Microsoft.*" maxLevel="Info" final="true" />
    <!-- BlackHole without writeTo -->
    <logger name="*" minlevel="Trace" writeTo="Console" />
  </rules>
</nlog>

程序.cs

public class Program
{
    public static void Main(string[] args)
    {
        var logger = NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();

        try
        {
            logger.Debug("init main");
            CreateWebHostBuilder(args).Build().Run();
        }
        catch (Exception ex)
        {
            //NLog: catch setup errors
            logger.Error(ex, "Stopped program because of exception");
            throw;
        }
        finally
        {
            // Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux)
            NLog.LogManager.Shutdown();
        }
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .ConfigureLogging((env, logging) =>
            {
                logging.ClearProviders();
                logging.SetMinimumLevel(LogLevel.Trace);
            })
            .UseNLog();
}

将以下条目添加到 .csproj 文件

<ItemGroup>
    <Content Update="nlog.config">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </Content>
</ItemGroup>

引用:

  1. https://github.com/NLog/NLog.Web/wiki/Getting-started-with-ASP.NET-Core-2

关于c# - ASP.NET Core 日志记录不适用于生产,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52357374/

相关文章:

javascript - 如何访问文件处理程序以使用 Typescript 在 deno 日志模块中运行 flush 方法

c# - 为什么 NuGet 包 NLog 不适用于 .NET Core?

azure - 使用 nlog.config 在 Azure Function Log Streams 中进行 NLog

c# - 用户控件 - 自定义属性

C# 正则表达式 - 替换为自身

c# - 使用 Entity Framework 重构代码

tomcat - 从 run-app 配置 Grails 访问日志记录

ios - iOS 的日志记录框架?

c# - 使用 nlog 记录多个线程

c# - 如何格式化 ListView 列以显示货币符号