netcore3.1 使用Nlog 將本地日誌寫入到elk
阿新 • • 發佈:2020-12-07
- 新建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"> <
- 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