NuGet 安装 Serilog
核心的包是 Serilog 和 Serilog.AspNetCore
建议安装 Serilog.AspNetCore,几乎包含了Serilog常用的所有包
异步写入 Serilog.Sinks.Async
写入MSSQL Serilog.Sinks.MSSqlServer
Install-Package Serilog.AspNetCore
Install-Package Serilog # winform 安装
Install-Package Serilog.Sinks.Async
Install-Package Serilog.Sinks.MSSqlServer
日志输出
输出到控制台
using Serilog;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;namespace NetCoreConsoleApp
{class Program{static void Main(string[] args){Log.Logger = new LoggerConfiguration().WriteTo.Console() //输出到控制台.CreateLogger();Log.Information("log");}}
}
输出到本地日志文件
using Serilog;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;namespace NetCoreConsoleApp
{class Program{static void Main(string[] args){/*WriteTo.File详解path:默认路径是程序的bin目录+path参数,当然也可以写绝对路径,只需要写入参数就可以了rollingInterval:创建文件的类别,可以是分钟,小时,天,月。 此参数可以让创建的log文件名 + 时间。例如log20191219.logoutputTemplate:日志模板,可以自定义retainedFileCountLimit:设置日志文件个数最大值,默认31,意思就是只保留最近的31个日志文件,等于null时永远保留文件*/string SerilogOutputTemplate = "{NewLine}{NewLine}Date:{Timestamp:yyyy-MM-dd HH:mm:ss.fff}{NewLine}LogLevel:{Level}{NewLine}Message:{Message}{NewLine}{Exception}" + new string('-', 100);Log.Logger = new LoggerConfiguration().MinimumLevel.Debug() // 所有Sink的最小记录级别.WriteTo.Console() //输出到控制台.WriteTo.File("00_Logs\\log.log", //$"{AppContext.BaseDirectory}00_Logs\log.log"rollingInterval: RollingInterval.Day,outputTemplate: SerilogOutputTemplate//,retainedFileCountLimit: 31).CreateLogger();Log.Information("log");}}
}
输出到本地日志文件(异步)
using Serilog;namespace NetCoreConsoleApp
{class Program{static void Main(string[] args){Log.Logger = new LoggerConfiguration().WriteTo.Async(a => a.File("00_Logs\\log.log", rollingInterval: RollingInterval.Day)).CreateLogger();Log.Information("log");Log.CloseAndFlush();}}
}
需要Serilog.Sinks.Async包
不同的日志级别输出到不同的文件夹下
using Serilog;
using Serilog.Events;
using System;namespace NetCoreConsoleApp
{class Program{static void Main(string[] args){string LogFilePath(string LogEvent) => $@"{AppContext.BaseDirectory}00_Logs\{LogEvent}\log.log";string SerilogOutputTemplate = "{NewLine}{NewLine}Date:{Timestamp:yyyy-MM-dd HH:mm:ss.fff}{NewLine}LogLevel:{Level}{NewLine}Message:{Message}{NewLine}{Exception}" + new string('-', 50);Log.Logger = new LoggerConfiguration()
.Enrich.FromLogContext()
.WriteTo.Console()
.MinimumLevel.Debug() // 所有Sink的最小记录级别
.WriteTo.Logger(lg => lg.Filter.ByIncludingOnly(p => p.Level == LogEventLevel.Debug).WriteTo.File(LogFilePath("Debug"), rollingInterval: RollingInterval.Day, outputTemplate: SerilogOutputTemplate))
.WriteTo.Logger(lg => lg.Filter.ByIncludingOnly(p => p.Level == LogEventLevel.Information).WriteTo.File(LogFilePath("Information"), rollingInterval: RollingInterval.Day, outputTemplate: SerilogOutputTemplate))
.WriteTo.Logger(lg => lg.Filter.ByIncludingOnly(p => p.Level == LogEventLevel.Warning).WriteTo.File(LogFilePath("Warning"), rollingInterval: RollingInterval.Day, outputTemplate: SerilogOutputTemplate))
.WriteTo.Logger(lg => lg.Filter.ByIncludingOnly(p => p.Level == LogEventLevel.Error).WriteTo.File(LogFilePath("Error"), rollingInterval: RollingInterval.Day, outputTemplate: SerilogOutputTemplate))
.WriteTo.Logger(lg => lg.Filter.ByIncludingOnly(p => p.Level == LogEventLevel.Fatal).WriteTo.File(LogFilePath("Fatal"), rollingInterval: RollingInterval.Day, outputTemplate: SerilogOutputTemplate))
.CreateLogger();Log.Information("log");Log.Error("log");}}
}
输出到MySQL
using Serilog;
using Serilog.Events;
using Serilog.Sinks.MSSqlServer;
using System;
using System.Collections.ObjectModel;
using System.Data;namespace ConsoleApp1
{class Program{static void Main(string[] args){string connectionString = @"Server=....";string tableNameA = "LogsA";string tableNameB = "LogsB";string tableNameC = "LogsC";static void Write(){Log.Information("测试信息");Log.Error("Error");Log.Write(LogEventLevel.Error, new Exception("错误"), "致命错误");};//A:默认配置//autoCreateSqlTable为true 时 会自动创建日志表Log.Logger = new LoggerConfiguration().WriteTo.MSSqlServer(connectionString, tableNameA, autoCreateSqlTable: true).CreateLogger();Write();//B:移除列var options = new ColumnOptions();options.Store.Remove(StandardColumn.Properties);options.Store.Remove(StandardColumn.MessageTemplate);Log.Logger = new LoggerConfiguration().WriteTo.MSSqlServer(connectionString, tableNameB, columnOptions: options, autoCreateSqlTable: true).CreateLogger();Write();//C:添加自定义列options = new ColumnOptions();options.AdditionalColumns = new Collection<SqlColumn>{new SqlColumn { DataType = SqlDbType.NVarChar, DataLength =-1, ColumnName = "IP" },new SqlColumn { DataType = SqlDbType.NVarChar, DataLength =-1, ColumnName = "IP2" }};Log.Logger = new LoggerConfiguration().Enrich.WithProperty("IP", "8.8.8.8").Enrich.WithProperty("IP2", "9.9.9.9").WriteTo.MSSqlServer(connectionString, tableNameC, columnOptions: options, autoCreateSqlTable: true).CreateLogger();Write();Console.WriteLine("Hello World!");Console.ReadKey();}}
}
需要Serilog.Sinks.MSSqlServer包
ASP.NET Core 中使用 Serilog
在Program.cs程序启动时注入Serilog 加载配置,有两种方法:
1.
using System;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using Serilog;namespace WebApplication1
{public class Program{public static void Main(string[] args){Log.Logger = new LoggerConfiguration().MinimumLevel.Debug().WriteTo.Console().WriteTo.File($"{AppContext.BaseDirectory}00_Logs\\log.log", rollingInterval: RollingInterval.Day).CreateLogger();try{Log.Information("Starting up");CreateHostBuilder(args).Build().Run();}catch (Exception ex){Log.Fatal(ex, "Application start-up failed");}finally{Log.CloseAndFlush();}}public static IHostBuilder CreateHostBuilder(string[] args) =>Host.CreateDefaultBuilder(args).ConfigureWebHostDefaults(webBuilder =>{webBuilder.UseStartup<Startup>();}).UseSerilog();}
}
using System;using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using Serilog;namespace WebApplication1
{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>();webBuilder.UseSerilog((hostingContext, loggerConfiguration) =>{loggerConfiguration.ReadFrom.Configuration(hostingContext.Configuration).Enrich.FromLogContext().WriteTo.File($"{AppContext.BaseDirectory}00_Logs\\log.log", rollingInterval: RollingInterval.Day).WriteTo.Console();});});}
}
Serilog