首先 ,安装这两个nuget
包
Install-Package Serilog.AspNetCore -Version 4.1.0
Install-Package Serilog.Sinks.MSSqlServer -Version 5.6.1
手动创建数据库 SerilogExample
Startup.cs
文件:
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using Serilog;
using Serilog.Sinks.MSSqlServer;
using System;
using System.Collections.ObjectModel;
namespace SerilogExample.Api
{
public class Program
{
[Obsolete]
public static void Main(string[] args)
{
var columOptions = new ColumnOptions
{
AdditionalColumns = new Collection<SqlColumn>
{
new SqlColumn
{
ColumnName="Name",DataType=System.Data.SqlDbType.NVarChar
}
}
};
var conn = @"Data Source=.;database=SerilogExample;User ID=sa;Password=123456;Pooling=true;Max Pool Size=40000;Min Pool Size=0;";
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.MinimumLevel.Override(source:"Microsoft", minimumLevel:Serilog.Events.LogEventLevel.Error)//筛选Microsoft的日志信息
.WriteTo.Console()//打印到控制台
.WriteTo.MSSqlServer(connectionString:conn,//连接字符串
tableName:"Logs", //表名
autoCreateSqlTable: true,//自动创建表
columnOptions: columOptions,//载入自定义表名
restrictedToMinimumLevel: Serilog.Events.LogEventLevel.Debug)
.CreateLogger();
CreateHostBuilder(args).Build().Run();
Log.CloseAndFlush(); //释放日志
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseSerilog().UseStartup<Startup>();//注册日志中间件
});
}
}
在Controller
使用注入:
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
正常使用:
_logger.LogInformation("this is information message");
使用 ForContext()
给自定义的列名添加值 (这种方式不知道规范不规范,但是可以使用):
Serilog.Log.ForContext("Name", "zhangsan").Information("this is information message") ;
Controller.cs
完整代码
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
namespace SerilogExample.Api.Controllers
{
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
[HttpGet]
public IEnumerable<WeatherForecast> Get()
{
Serilog.Log.ForContext("Name", "sunshauize").Information("111111") ;
_logger.LogInformation("this is information message");
var rng = new Random();
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = rng.Next(-20, 55),
Summary = Summaries[rng.Next(Summaries.Length)]
})
.ToArray();
}
}
}