1. 程式人生 > 實用技巧 >netcore3.1 使用Nlog 將本地日誌寫入到elk

netcore3.1 使用Nlog 將本地日誌寫入到elk

  • 新建webapi
  • 新增Nlog nuget包引用

  • 新增Nlog配置檔案
    <?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="Warn"
          internalLogFile="internal-nlog.txt">
    
      <
    extensions> <!--enable NLog.Web for ASP.NET Core--> <add assembly="NLog.Web.AspNetCore"/> </extensions> <!-- define various log targets --> <!--定義日誌檔案目錄--> <variable name="logDirectory" value="${basedir}/logs/${shortdate}"/> <variable name="nodeName"
    value="node1"/> <targets async="true"> <!-- 全部日誌target --> <target xsi:type="File" name="allfile" fileName="${logDirectory}/nlog-all/${shortdate}.log" layout="#node1#${longdate}#${logger}#${uppercase:${level}}#${callsite}#${callsite-linenumber}#${aspnet-request-url}#${aspnet-request-method}#${aspnet-mvc-controller}#${aspnet-mvc-action}#${message}#${exception:format=ToString}#"
    keepFileOpen="false" /> <!-- 本地檔案日誌target --> <target xsi:type="File" name="ownLog-file" fileName="${logDirectory}/nlog-${level}/${shortdate}.log" layout="#${longdate}#${nodeName}#${logger}#${uppercase:${level}}#${callsite}#${callsite-linenumber}#${aspnet-request-url}#${aspnet-request-method}#${aspnet-mvc-controller}#${aspnet-mvc-action}#${message}#${exception:format=ToString}#" keepFileOpen="false" /> <!-- Tcp日誌target --> <target xsi:type="Network" name="ownLog-tcp" keepConnection="false" address ="tcp://192.168.3.10:5000" layout="#${longdate}#${nodeName}#${logger}#${uppercase:${level}}#${callsite}#${callsite-linenumber}#${aspnet-request-url}#${aspnet-request-method}#${aspnet-mvc-controller}#${aspnet-mvc-action}#${message}#${exception:format=ToString}#" /> <!--grok 規則--> <!--%#{DATA:request_time}#%{DATA:node_name}#%{DATA:class_name}#%{DATA:log_level}#%{DATA:call_site}#%{DATA:line_number}#%{DATA:request_url}#%{DATA:request_method}#%{DATA:container_name}#%{DATA:action_name}#%{DATA:log_info}#%{DATA:exception_msg}#--> <!--空白--> <target xsi:type="Null" name="blackhole" /> </targets> <!--日誌級別 Trace -》Debug-》 Info -》Warn-》 Error-》 Fatal--> <!--日誌規則--> <rules> <!--全部日誌, 包括Microsoft日誌--> <logger name="*" minlevel="Trace" writeTo="allfile" /> <!--自定義日誌,排除Microsoft日誌--> <logger name="Microsoft.*" minlevel="Trace" writeTo="blackhole" final="true" /> <logger name="*" minlevel="Debug" writeTo="ownLog-file" /> <logger name="*" minlevel="Info" writeTo="ownLog-tcp" /> </rules> </nlog>

  • startup新增中介軟體
    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.Hosting;
    using Microsoft.Extensions.Logging;
    using NLog;
    using NLog.Extensions.Logging;
    using NLog.Web;namespace UserWebApplication
    {
        public class Startup
        {
    
            public Startup(IConfiguration configuration)
            {
                Configuration = configuration;
            }
    
            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)
            {
                var currentClassLogger = NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
                services.AddSingleton(currentClassLogger);
                services.AddControllers();
              
            }
    
            // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
            public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory, IHostApplicationLifetime lifetime)
            {
                //loggerFactory.AddNLog();
                //loggerFactory.ConfigureNLog("nlog.config");
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                }
    
                app.UseRouting();
    
                app.UseAuthorization();
    
                //停止時登出
                lifetime.ApplicationStopped.Register(() =>
                {
                    //Nlog 確保在應用程式退出之前重新整理並停止內部計時器/執行緒(避免Linux上出現分段錯誤)
                    LogManager.Shutdown();
                });
    
                app.UseEndpoints(endpoints =>
                {
                    endpoints.MapControllers();
                });
            }
        }
    }

  • Program 新增Loggin配置
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.Extensions.Hosting;
    using Microsoft.Extensions.Logging;
    using NLog.Web;
    
    namespace UserWebApplication
    {
        public class Program
        {
            public static void Main(string[] args)
            {
                CreateHostBuilder(args).Build().Run();
            }
    
            public static IHostBuilder CreateHostBuilder(string[] args) =>
                Host.CreateDefaultBuilder(args)
                    .ConfigureWebHostDefaults(webBuilder =>
                    {
                        webBuilder.UseStartup<Startup>();
                    }).ConfigureLogging(logging =>
                    {
                        logging.ClearProviders();
                        logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
                    }).UseNLog();
        }
    }

  • 修改appsetting.json 配置
    {
      "Logging": {
        "IncludeScopes": false,
        "LogLevel": {
          "Default": "Trace",
          "Microsoft": "Warning",
          "Microsoft.Hosting.Lifetime": "Information"
        }
      },
      "AllowedHosts": "*"
    }

  • 使用示例
      private readonly ILogger<WeatherForecastController> _logger;
    
            public WeatherForecastController(ILogger<WeatherForecastController> logger)
            {
                _logger = logger;
            }
    
            [HttpGet]
            public IEnumerable<WeatherForecast> Get()
            {
                var rng = new Random();
                _logger.LogInformation("這是一條測試訊息Information");
    
                _logger.LogError("這是一條測試訊息Erro");
    
                _logger.LogDebug("這是一條測試訊息Debug");
    
                return Enumerable.Range(1, 5).Select(index => new WeatherForecast
                {
                    Date = DateTime.Now.AddDays(index),
                    TemperatureC = rng.Next(-20, 55),
                    Summary = Summaries[rng.Next(Summaries.Length)]
                })
                .ToArray();
            }

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