繁体   English   中英

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

[英]Using NLog in asp.net core 2.0 web application

哪个是在asp.net core 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();
        }
    }

有关于此的维基文档:

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 ver。 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以使用此第三方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>(); 

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

暂无
暂无

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

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