簡體   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