在 asp.net 核心 2.0 Web 应用程序中使用 NLog

Using NLog in asp.net core 2.0 web application

在 asp.net 核心 2.0 Web 应用程序中使用 Nlog 的最佳方式

我发现了很多不同的解决方案如何配置。这是其中的两个。还有其他更好的方法吗?

A) 在启动服务器之前创建记录器:

 public class Program
{
    public static void Main(string[] args)
    {    
        // NLog: setup the logger first to catch all errors
        var logger = NLogBuilder.ConfigureNLog("NLog.config").GetCurrentClassLogger();    
        try
        {
            logger.Debug("init main");
            BuildWebHost(args).Run();
        }
        catch (Exception e)
        {
            //NLog: catch setup errors
            logger.Error(e, "Stopped program because of exception");
            throw;
        }    
    }

    public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>().UseNLog() // use NLog for DI Logger
            .Build();
}

B) 在启动时配置

public class Startup
    {
        public Startup(IHostingEnvironment env, IConfiguration configuration)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                .AddEnvironmentVariables();
            Configuration = builder.Build();            
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {            
            services.AddMvc();                            
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddNLog();
            loggerFactory.ConfigureNLog("nlog.config");

            LogManager.Configuration.Variables["connectionString"] = Configuration.GetConnectionString("myDb");

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseMvc();
        }
    }

有一个关于此的 wiki 文档:

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

要注入连接字符串等自定义数据,只需创建并注册自定义布局渲染器即可:

https://github.com/NLog/NLog/wiki/How-to-write-a-custom-layout-renderer

或者在启动时将连接字符串放入 NLog-Global-Diagnostic-Context 中:

https://github.com/NLog/NLog/wiki/Var-Layout-Renderer

也许像这样 NLog.config 使用 ${gdc:connectionString}:

var myConnectionString = Configuration.GetConnectionString("myDb");
NLog.GlobalDiagnosticsContext.Set("connectionString", myConnectionString);
var logFactory = NLogBuilder.ConfigureNLog("NLog.config"); // Uses ${gdc:connectionString}
var logger = logFactory.GetCurrentClassLogger();
logger.Info("Hello World");

另见 https://github.com/NLog/NLog/wiki/Gdc-Layout-Renderer

更新 - ${configsetting}

NLog.Extension.Logging 版本。 1.4 现在支持 ${configsetting} 因此 NLog 可以直接从 appsettings.json 读取设置而不需要使用 NLog 变量。参见 https://github.com/NLog/NLog/wiki/ConfigSetting-Layout-Renderer

所以这是我在我的项目中尝试并一直在使用的在控制台上显示日志的方法。

  • 使用 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">

 <extensions>
    <add assembly="NLog.Web.AspNetCore"/>
  </extensions>
  <!-- the targets to write to -->
  <targets>
    <!-- write logs to file  -->
    <target name="file" xsi:type="File"
            fileName="${basedir}/App_Data/Logs/${shortdate}.txt" encoding="utf-8" layout="[${longdate}][${machinename}][${level}] ${message} ${exception}" />
  </targets>

  <!-- rules to map from logger name to target -->
  <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>

  • 现在请确保您的 appsettings.json 具有这些最低配置,以便在控制台上查看日志。

{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default":"Trace",
      "Microsoft": "Warning"
    }
  }

  • 配置 Program.cs 以使用此第 3 方 NLog 作为您的记录器。

    using NLog;
using  NLog.Extensions.Logging;     

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
                WebHost.CreateDefaultBuilder(args)
                .UseKestrel(options =>
                {
                    // options.Listen(IPAddress.Loopback, 5000); //HTTP port
                })
                    .UseContentRoot(Directory.GetCurrentDirectory())
                    .UseIISIntegration()
                    .ConfigureLogging((hostingContext, logging) =>
                                {
                                    logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
                                    logging.AddConsole();
                                    logging.AddDebug();
                                    logging.AddEventSourceLogger();
                                    // Enable NLog as one of the Logging Provider
                                    logging.AddNLog();
                                })
                    .UseStartup<Startup>();

注意:我使用代码片段插入代码,因为我无法在当前编辑器中正确格式化代码。