这里使用的配置为三种分别是控制台(Console),文件(File),数据库(SQL Server)
项目引用
首先引入三种模式的nuget包
<PackageReference Include="Serilog.Sinks.Console" Version="6.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="6.0.0" />
<PackageReference Include="Serilog.Sinks.MSSqlServer" Version="7.0.1" />
配置
static void Main(string[] args)
{
//这里读取配置我使用的是一个nuget包直接通过类型名就能获取到
var configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.Build();
string strConn = configuration["connectionString"];
//定义数据存储的自定义列
var columnOptions = new ColumnOptions
{
AdditionalDataColumns = new Collection<DataColumn>
{
new DataColumn {DataType = typeof (string), ColumnName = "User"},
new DataColumn {DataType = typeof (string), ColumnName = "Class"},
}
};
//开始配置serilog
Log.Logger = new LoggerConfiguration()
.WriteTo.Console(restrictedToMinimumLevel: Serilog.Events.LogEventLevel.Debug)
.WriteTo.File("logs/log.txt", restrictedToMinimumLevel: Serilog.Events.LogEventLevel.Information,
rollingInterval: RollingInterval.Day,
rollOnFileSizeLimit: true)
.WriteTo.MSSqlServer(strConn,
sinkOptions:new MSSqlServerSinkOptions { TableName = "LogTest", AutoCreateSqlTable = true,BatchPeriod=TimeSpan.FromSeconds(10) , BatchPostingLimit = 100 },
columnOptions: columnOptions,
restrictedToMinimumLevel: LogEventLevel.Debug)
.CreateLogger();
//测试数据
for (int i = 0; i < 50; i++)
{
// Log.ForContext使用是为了把自定义列数据输入
Log.ForContext("User", "127.0.0.1")
.ForContext("Class", "Tom")
.Information("Hello, {Name}!", "World");
Thread.Sleep(200);
}
Console.WriteLine("ok");
}