简体   繁体   English

ASP.NET Core日志记录不适用于生产环境

[英]ASP.NET Core Logging does not work on Production

Turns out the issue was not anyway related to NLog or ASP.NET Logging system. 事实证明,该问题与NLog或ASP.NET日志记录系统无关。 Logging was configured correctly but the build server was publishing a Debug build to the Production due to a configuration error. 日志配置正确,但是由于配置错误,生成服务器将Debug发布到生产中。

I am trying to setup a third party logger in my ASP.NET Core 2.0 (SDK 2.1.401 ) project. 我正在尝试在ASP.NET Core 2.0(SDK 2.1.401 )项目中设置第三方记录器。 So far I have tried Serilog and NLog . 到目前为止,我已经尝试了SerilogNLog However I am having same issue for both. 但是我对两个都有同样的问题。 To summarise the issue, 总结一下问题,

  • It works as intended when I run the app like dotnet run (ie. In Development environment) 当我像dotnet run一样dotnet run应用程序时,它可以按预期工作(即在Development环境中)
  • But it does not when I run the binary dotnet MyApplication.dll (ie. In Production environment). 但是当我运行二进制dotnet MyApplication.dll (即在Production环境中)时却没有。
  • I do not have anything defined in "Logging" section for Development environment in my appsettings.Development.json file. 我的appsettings.Development.json文件中的Development环境的"Logging"部分没有定义任何内容。

The issue described below is for NLog . 下面描述的问题是针对NLog I have tried SeriLog and hit the same issue. 我已经尝试过SeriLog并遇到了同样的问题。

Here is the relevant part from Program.cs 这是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();

Note I have cleared all providers and added NLog also the nlog.config file is defined: 注意我已经清除了所有提供程序,并添加了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>

When running in Development mode, I see the logs exactly as I expected 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

However, when I run the app in Production envoronment, the console output looks as if I do not have NLog installed and I haven't cleared the default providers. 但是,当我在Production envoronment中运行该应用程序时,控制台输出看起来好像我没有安装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

Notice those lines begins with info: ? 请注意,这些行以info:开头info: those are standard console logging format you get when you use the default logging setup defined in Microsoft.Extensions.Logging . 这些是使用Microsoft.Extensions.Logging定义的默认日志记录设置时获得的标准控制台日志记录格式。 But I definitely cleared Console provider by calling logging.ClearProviders(); 但是我肯定通过调用logging.ClearProviders();清除Console提供程序logging.ClearProviders(); in the Program.cs file. Program.cs文件中。

Thanks for any help. 谢谢你的帮助。

I was able to reproduce your problem and fix it. 我能够重现您的问题并解决它。 Please find my configuration here. 请在这里找到我的配置。

appsettings.json appsettings.json

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

nlog.config 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>

Program.cs Program.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();
}

added the following entry to .csproj file 在.csproj文件中添加了以下条目

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

Reference: 参考:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM