结构化日志工具 Serilog 使用
1. 添加 NuGet 包
在解决方案管理器视图中的目标项目上右键 -> 管理 NuGet 程序包;
添加 Serilog、Serilog.Sinks.Console、Serilog.Sinks.File、Serilog.Sinks.Seq、Serilog.AspNetCore、Microsoft.Extensions.Configuration.Json 包,如下图所示:
2. 安装日志监控组件 Seq
下载地址:https://datalust.co/download
安装完成后,打开:http://172.22.113.77:5341 验证是否成功安装(IP 为 Seq 安装电脑的 IP)。
注:该程序安装完成后以服务的形式运行,如下图所示:
3. 通过代码使用
using Microsoft.Extensions.Configuration; using Serilog; using Serilog.Core; using Serilog.Events; using System; using System.IO; using System.Net; using System.Net.Sockets; using System.Threading; namespace SerilogDemo { class Program { static string logConfigFilePath = "Config//logsettings.json"; static void Main(string[] args) { var configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile(path: logConfigFilePath, optional: false, reloadOnChange: true) .Build(); Log.Logger = new LoggerConfiguration() .Enrich.With(new ThreadIdEnricher()) .Enrich.With(new IpAddressEnricher()) .ReadFrom.Configuration(configuration) .CreateLogger(); Log.Information("Serilog test start. {Name}", Environment.UserName); Thread thread = new Thread(Thread_Test); thread.Start(); int a = 10, b = 0; try { Log.Debug("Dividing {A} by {B}", a, b); Console.WriteLine(a / b); } catch (Exception ex) { Log.Error(ex, "Something went wrong"); } finally { Log.CloseAndFlush(); } Console.ReadLine(); } private static void Thread_Test() { Log.Debug("Thread_Test() In."); Console.WriteLine("ThreadId = {0}", Thread.CurrentThread.ManagedThreadId); Log.Debug("Thread_Test() Out."); } } class ThreadIdEnricher : ILogEventEnricher { public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory) { logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty( "ThreadId", Thread.CurrentThread.ManagedThreadId)); } } class IpAddressEnricher : ILogEventEnricher { string localIp = ""; public IpAddressEnricher() { localIp = GetLocalIp(); } public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory) { logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty( "IpAddress", localIp)); } private string GetLocalIp() { string hostname = Dns.GetHostName(); IPHostEntry localhost = Dns.GetHostEntry(hostname); if (localhost != null) { foreach (IPAddress item in localhost.AddressList) { //判断是否是内网IPv4地址 if (item.AddressFamily == AddressFamily.InterNetwork) { return item.MapToIPv4().ToString(); } } } return "127.0.0.1"; } } }
{ "Serilog": { "Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.File" ], "MinimumLevel": "Debug", "WriteTo": [ { "Name": "Console", "Args": { "theme": "Serilog.Sinks.SystemConsole.Themes.SystemConsoleTheme::Colored, Serilog.Sinks.Console", "outputTemplate": "{Level:u3}: {Message}{NewLine}{Exception}" } }, { "Name": "File", "Args": { "path": "Logs/AEConsoleGatewayService_.log", "rollingInterval": "Day", "outputTemplate": "Thread ID: {ThreadId} Time: {Timestamp:yyyy-MM-dd HH:mm:ss.fff} Level: {Level:u3} Message: {Message:lj} {Exception} " } }, { "Name": "Seq", "Args": { "serverUrl": "http://172.22.113.77:5341" } } ] } }