ASP.NET Core日志在生产环境中无法工作

3
原来问题与NLog或ASP.NET Logging系统无关。日志记录已正确配置,但由于配置错误,构建服务器将Debug构建发布到生产环境中。
我正在尝试在ASP.NET Core 2.0(SDK 2.1.401)项目中设置第三方日志记录器。到目前为止,我已经尝试了Serilog和NLog,但两者都遇到了相同的问题。总结一下问题:
  • 当我像dotnet run这样运行应用程序时(即在Development环境中),它按预期工作
  • 但是当我在二进制文件dotnet MyApplication.dll中运行它时(即在Production环境中),它不起作用。
  • 在appsettings.Development.json文件中,我没有为Development环境定义Logging部分中的任何内容。
下面描述的问题是针对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>

当以开发模式运行时,我看到的日志与我预期的完全一致。

$ 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

然而,当我在生产环境中运行应用程序时,控制台输出看起来好像我没有安装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提供者。感谢任何帮助。
1个回答

8
我能重现你的问题并解决它。请查看我的配置如下。
appsettings.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>

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

在.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

是的,我已经做了,并且我已经可以在发布的文件夹中看到该文件了。 :) - undefined
太棒了,我会尝试添加“AllowedHost”属性。谢谢。 - undefined
感谢你的努力,伙计。然而,这实际上是由于一个完全无关的问题(如上所述),我现在已经解决了。对此造成的麻烦,我很抱歉。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接