一、Serilog
NLog也能配置结构化日志记录,当配置过程相当麻烦,Serilog就相对的便捷很多,在集群中,可以方便的将日志集中到一个日志服务器中
二、导入Serilog包
Serilog.AspNetCore
三、编写实例
1.Console
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
using Serilog;
using Serilog.Formatting.Json;
using System;
namespace _01_Logging
{
class Program
{
static void Main(string[] args)
{
///模拟startup实例一个ServiceCollection
ServiceCollection services = new ServiceCollection();
services.AddLogging(
logBuilder=>
{
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.Enrich.FromLogContext()
.WriteTo.Console(new JsonFormatter())
.CreateLogger();
logBuilder.AddSerilog();
}
);
//注册服务
services.AddScoped<SystemService>();
//通过服务构建容器,ServiceProvider类型
using (var sp = services.BuildServiceProvider())
{ ///获取容器中的服务ITestService
var test2 = sp.GetRequiredService<SystemService>();
test2.Logging();
}
}
}
}
2.自定义服务类
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace _01_Logging
{
public class SystemService
{
private ILogger<SystemService> logger;
public SystemService(ILogger<SystemService> logger)
{
this.logger = logger;
}
public void Logging()
{
logger.LogDebug("开始执行数据库同步");
logger.LogDebug("开始执行数据库同成功");
logger.LogDebug("connection succed");
logger.LogWarning("read data faile, retry first");
//......
User person = new User { Id="1",Name="lty"};
logger.LogWarning("read data faile, retry second");
logger.LogError("read data faile");
//要记录的结构化数据通过占位符来输出;
logger.LogDebug("注册一个用户{@person}", person);
}
}
public class User
{
public string Id { get; set; }
public string Name { get; set; }
}
}
四、运行结果
日志记录类似与json格式的数据