.Net Core項目中整合Serilog

前言:Serilog是.NET應用程序的診斷日誌記錄庫。它易於設置,具備簡潔的API,而且能夠在全部最新的.NET平臺上運行。儘管即便在最簡單的應用程序中它也頗有用,但當對複雜的,分佈式的和異步的應用程序和系統進行檢測時,Serilog對結構化日誌記錄的支持便會更加出色。html

首先導入要用到的NuGet包:web

#region 這兩個包是引入Serilog的關鍵 Serilog Serilog.AspNetCore #endregion
//控制檯輸出
Serilog.Sinks.Console //發送郵件
Serilog.Sinks.Email //將日誌寫入到文件
Serilog.Sinks.File //推送日誌至數據庫
Serilog.Sinks.MssqlServer

1.輸出到控制檯sql

public static void Main(string[] args) { Log.Logger = new LoggerConfiguration() .MinimumLevel.Information()//最小的記錄等級
                .MinimumLevel.Override("Microsoft", LogEventLevel.Information)//對其餘日誌進行重寫,除此以外,目前框架只有微軟自帶的日誌組件
                .WriteTo.Console()//輸出到控制檯
 .CreateLogger(); Log.Information("info"); Log.Error("err"); CreateHostBuilder(args).Build().Run(); }

在終端中不一樣等級的日誌顏色不一樣數據庫

Serilog提供了兩個類(SystemConsoleThemes和AnsiConsoleThemes)用於主題的變化json

.WriteTo.Console(theme: SystemConsoleTheme.Colored)

.WriteTo.Console(theme: AnsiConsoleTheme.Code)

 也能夠自定義輸出的模板服務器

.WriteTo.Console(theme: AnsiConsoleTheme.Code, outputTemplate: "發生時間:{Timestamp: HH:mm:ss.fff} 事件級別:{Level} 詳細信息:{Message}{NewLine}{Exception}")

 咱們也能夠將這些配置項寫入到appsettings.json文件中app

導包:Serilog.Settings.Configuration框架

在appsettings.json加入如下json塊兒異步

"Serilog": { "WriteTo": [ { "Name": "Console", "Args": { "theme": "Serilog.Sinks.SystemConsole.Themes.AnsiConsoleTheme::Code, Serilog.Sinks.Console", "outputTemplate": "發生時間:{Timestamp: HH:mm:ss.fff} 事件等級:{Level} 詳細信息:{Message}{NewLine}{Exception}" } } ] }
Log.Logger = new LoggerConfiguration() .MinimumLevel.Information()
                .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
                .ReadFrom.Configuration(new ConfigurationBuilder() .AddJsonFile("appsettings.json") .Build()) .CreateLogger();

2.將日誌寫入到文件分佈式

Log.Logger = new LoggerConfiguration() .MinimumLevel.Information()
                .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
                .ReadFrom.Configuration(new ConfigurationBuilder() .AddJsonFile("appsettings.json") .Build())  .WriteTo.File(Path.Combine("MyLogs", "log"), rollingInterval: RollingInterval.Day)//文件生成到當前路徑 rollingInterval:RollingInterval.Day:按天生成文件
                .CreateLogger();

將配置信息添加到json中

"Serilog": { "WriteTo": [ { "Name": "Console", "Args": { "theme": "Serilog.Sinks.SystemConsole.Themes.AnsiConsoleTheme::Code, Serilog.Sinks.Console", "outputTemplate": "發生時間:{Timestamp: HH:mm:ss.fff} 事件等級:{Level} 詳細信息:{Message}{NewLine}{Exception}", } },  { "Name": "File", "Args": { "path": "MyLogs/log.txt", "rollingInterval": "Day", "outputTemplate": "發生時間:{Timestamp: HH:mm:ss.fff} 事件等級:{Level} 詳細信息:{Message}{NewLine}{Exception}" } } ] }
將這句代碼註釋掉:.WriteTo.File(Path.Combine("MyLogs", "log"), rollingInterval: RollingInterval.Day)

3.將日誌推送到數據庫

Log.Logger = new LoggerConfiguration() .MinimumLevel.Information()
                .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
                .ReadFrom.Configuration(new ConfigurationBuilder() .AddJsonFile("appsettings.json") .Build()) .WriteTo.MSSqlServer("Data Source=DESKTOP-4TU9A6M;Initial Catalog=CoreFrame;User ID=sa;Password=123456", "logs", autoCreateSqlTable: true, restrictedToMinimumLevel: LogEventLevel.Information)//從左至右四個參數分別是數據庫鏈接字符串、表名、若是表不存在是否建立、最低等級。Serilog會默認建立一些列。  .CreateLogger();

 4.發送郵件

.WriteTo.Email(new EmailConnectionInfo() { EmailSubject = "系統警告,請速速查看!",//郵件標題
   FromEmail = "291***@qq.com",//發件人郵箱
   MailServer = "smtp.qq.com",//smtp服務器地址
   NetworkCredentials = new NetworkCredential("291***@qq.com", "###########"),//兩個參數分別是發件人郵箱與客戶端受權碼
   Port = 587,//端口號
   ToEmail = "183***@163.com"//收件人
  })

若是對客戶端受權碼不熟悉的同窗可移步此博客

https://www.cnblogs.com/zhangnever/p/11926020.html

 發送成功!

 

 完整代碼:

public class Program { public static void Main(string[] args) { Log.Logger = new LoggerConfiguration() .MinimumLevel.Information() .MinimumLevel.Override("Microsoft", LogEventLevel.Information) .ReadFrom.Configuration(new ConfigurationBuilder() .AddJsonFile("appsettings.json") .Build()) .WriteTo.MSSqlServer("Data Source=DESKTOP-4TU9A6M;Initial Catalog=CoreFrame;User ID=sa;Password=123456", "logs", autoCreateSqlTable: true, restrictedToMinimumLevel: LogEventLevel.Information)//從左至右四個參數分別是數據庫鏈接字符串、表名、若是表不存在是否建立、最低等級。Serilog會默認建立一些列。 
                .WriteTo.Email(new EmailConnectionInfo() { EmailSubject = "系統警告,請速速查看!",//郵件標題
                    FromEmail = "291***@qq.com",//發件人郵箱
                    MailServer = "smtp.qq.com",//smtp服務器地址
                    NetworkCredentials = new NetworkCredential("291***@qq.com", "###########"),//兩個參數分別是發件人郵箱與客戶端受權碼
                    Port = 587,//端口號
                    ToEmail = "188***@163.com"//收件人
 }) .CreateLogger(); Log.Information("info"); Log.Error("err"); CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseSerilog()//在宿主機啓動的時候配置serilog,與微軟ILogger進行整合
                              .UseStartup<Startup>(); }); }

咱們在用的時候能夠直接在控制器中注入ILogger

例如微軟的天氣預報的控制器:

private readonly ILogger<WeatherForecastController> _logger; public WeatherForecastController(ILogger<WeatherForecastController> logger) { _logger = logger; }
//直接在接口中使用: _logger.LogInformation("success");

最好配合過濾器一塊兒使用,達到AOP的效果

請看此篇博客:

https://www.cnblogs.com/zhangnever/p/12397117.html

 其實Serilog還有N多插件,我只列舉了以上幾個。

 之後慢慢了解吧!

🙂

原文出處:https://www.cnblogs.com/zhangnever/p/12459399.html

相關文章
相關標籤/搜索