目录
-
首先引用配置Serilog的NueGet包
Serilog
Serilog.AspNetCore
Serilog.Formatting.Compact
Serilog.Sinks.File
Serilog.Sinks.MySQL
-
Program.cs 添加如下代码
先封装一个类:
这里的将日志输出到数据库我给注释掉了,需要的伙伴可以解除注释哦
public static class InitScoped
{
/// <summary>
/// 注入容器
/// </summary>
/// <param name="services"></param>
public static void Register(this IServiceCollection services)
{
services.AddScoped<BllTarget,DalTarget>();
}
/// <summary>
/// Serilog 日志拓展
/// </summary>
public static void ConfigureLogging(WebApplicationBuilder builder)
{
string dateFile = DateTime.Now.ToString("yyyyMMdd");
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
.Enrich.FromLogContext()
.WriteTo.Console(new CompactJsonFormatter())
//.WriteTo.MySQL(connectionString: builder.Configuration.GetConnectionString("DbConnectionString"), tableName: "Logs") // 输出到数据库
.WriteTo.Logger(configure => configure
.Filter.ByIncludingOnly(e => e.Level == LogEventLevel.Debug)
.WriteTo.File(
$"logs/log-debug-{dateFile}.txt",
rollingInterval: RollingInterval.Day,
outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}"))
.WriteTo.Logger(configure => configure
.Filter.ByIncludingOnly(e => e.Level == LogEventLevel.Information)
.WriteTo.File(
$"logs/log-info-{dateFile}.txt",
rollingInterval: RollingInterval.Day,
outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}"))
.WriteTo.Logger(configure => configure
.Filter.ByIncludingOnly(e => e.Level == LogEventLevel.Error)
.WriteTo.File(
$"logs/log-error-{dateFile}.txt",
rollingInterval: RollingInterval.Day,
outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}"))
.WriteTo.File(
$"logs/log-total-{dateFile}.txt",
rollingInterval: RollingInterval.Day,
outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}",
restrictedToMinimumLevel: LogEventLevel.Debug)
.CreateLogger();
}
}
Program.cs 调用此方法
#region 配置Serilog 日志
InitScoped.ConfigureLogging(builder);
builder.Host.UseSerilog(); //向主机注册Serilog
#endregion
-
使用方法
直接在需要使用的控制器或方法类下进行注入即可,示例代码如下
public class DalTarget : BllTarget
{
private readonly ServerContext _context;
private readonly ILogger<DalTarget> _logger;
public DalTarget(ServerContext context, ILogger<DalTarget> logger)
{
_context = context;
_logger = logger;
}
public async Task<List<Target>> GetTarget(Guid guid)
{
try
{
var data = await _context.Targets.Where(s => s.Id == guid).AsNoTracking().ToListAsync();
if (data.Count <= 0)
{
throw new Exception("接口:GetTarget|报错:查询列表id返回空数据");
}
return data;
}
catch (Exception ex)
{
_logger.LogInformation($"GetTarget:{ex.Message},参数|id:{guid}");
_logger.LogError($"GetTarget:{ex.Message},参数|id:{guid}");
throw new Exception(ex.Message);
}
}
}
这里 的LogInformation 和 LogError 看情况写 我把两个都写出来了
-
测试应用
报错后会在项目地址自动创建log文件夹
控制台输出
好啦,今天分享到这里哦