# Serilog ###### tags: `.NetCore` ## 配置 ### Log Path ``` /// <summary> 存放 Log 的資料夾路徑 </summary> public static string LogFolderPath { get; } = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "MyLog"); ``` ### Startup.cs 建構子中建立 Logger 物件 ``` public Startup(IConfiguration configuration) { Configuration = configuration; // create serilog object { var flushInterval = TimeSpan.FromSeconds(60); Log.Logger = new LoggerConfiguration() .Enrich.FromLogContext() // 使用 LogContext ( PushProperty ) .MinimumLevel.Debug() .WriteTo.File( path: Path.Combine(AppValueService.System.LogFolderPath, $@"{nameof(dataApi)}.txt"), outputTemplate: "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff}][{ClientIP}][{Username}][{Level}] {Message}{NewLine}{Exception}", rollingInterval: RollingInterval.Day, flushToDiskInterval: flushInterval, fileSizeLimitBytes: 100 * 1024 * 1024, // 100MB rollOnFileSizeLimit: true, shared: true // Set true for multiple log write in same time. ) .WriteTo.Logger(errorLogger => errorLogger .MinimumLevel.Error() .WriteTo.File( path: Path.Combine(AppValueService.System.LogFolderPath, $@"{nameof(dataApi)}_ErrorOnly.txt"), outputTemplate: "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff}][{ClientIP}][{Username}][{Level}] {Message}{NewLine}{Exception}", rollingInterval: RollingInterval.Day, flushToDiskInterval: flushInterval, fileSizeLimitBytes: 100 * 1024 * 1024, // 100MB rollOnFileSizeLimit: true, shared: true // Set true for multiple log write in same time. ) ) .WriteTo.Console( Serilog.Events.LogEventLevel.Information ) .CreateLogger(); } } ``` ### Startup.cs > public void Configure Push 帳號和IP欄位資料 ``` public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ICommonHttpContext commonHttpContext) { // 將此時才能取得到的資料設置成 Property Push 到 Log,以利 OutputTemplate 書寫時取得資料 app.Use(async (httpContext, next) => { var userName = commonHttpContext.IsAuthenticated() ? commonHttpContext.GetUsername() : "Guest"; //Gets user Name from user Identity LogContext.PushProperty("Username", userName); LogContext.PushProperty("ClientIP", commonHttpContext.GetRequestIPAddress()); await next.Invoke(); }); /// 略 } ``` ## 使用時直接使用 Logger 物件就可 ``` _logger.LogError(JsonConvert.SerializeObject(new { FullUrl = context.Request.GetDisplayUrl(), // 完整的網址列 Error = errorResult, // 錯誤內容 }, Formatting.Indented)); ```