目的 在寫nlog.config檔案時覺得怎麼有點複雜,我只是需要簡單的設定檔就好了,最後決定透過appsetting來做設定 將log文件採用非同步寫入,可大幅提升效能 建立新專案 選擇ASP.NET Core Web API專案範本,並執行下一步 設定新的專案 命名你的專案名稱,並選擇專案要存放的位置。 其他資訊 直接進行下一步 4.NuGet加入套件 NLog NLog.Web.AspNetCore 編輯Program.cs檔 using NLog; using NLog.Web; //初始化NLog var logger = LogManager.Setup() //載入Configuration並且讀取appsetting來使用 .LoadConfigurationFromAppSettings() .GetCurrentClassLogger(); try { logger.Debug("init main"); var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Logging.ClearProviders(); builder.Host.UseNLog(); builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); //以下省略 編輯appsetting.json 設定NLog,包含
throwConfigExceptions:設定檔錯誤時會跳exception 使用非同步方式寫入檔案 targets:設定輸出的格式,例如txt檔案或是Console顯示 rules:什麼情況要做什麼動作,例如log名稱為Microsoft.AspNetCore最小等級是warn時寫到Console ILogger NLog Level 0 Trace Trace Level 1 Debug Debug Level 2 Information Info Level 3 Warning Warn Level 4 Error Error Level 5 Critical Fatal Level 6 None NLog沒有 { "NLog": { "throwConfigExceptions": true, "targets": { "async": true, "logfile": { "type": "File", "fileName": "c:/temp/nlog-${shortdate}.txt" }, "logconsole": { "type": "Console" } }, "rules": [ { "logger": "Microsoft.AspNetCore", "minLevel": "Warn", "writeTo": "logconsole" }, { "logger": "*", "minLevel": "Info", "writeTo": "logfile" } ] } } ...