.netcore
/Program.cs
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
-- 读取日志配置(这里单独创建了一个serilogsetting.json文件)
private static IConfiguration GetLogConfig()
{
var builder = new ConfigurationBuilder()
.AddJsonFile("serilogsetting.json", optional: false, reloadOnChange: true);
return builder.Build();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>().UseSerilog((context, logger) => {
logger.ReadForm.Configuration(GetLogConfig());
logger.Enrich.FromLogContext();
});
});
注入使用:
private readonly ILogger<TestController> _logger;
public TestController(ILogger<TestController> logger)
{
_logger = logger;
}
任何地方直接使用:
using Serilog;
Log.Information("Hello Information, Serilog!");
Log.Error("Hello Error, Serilog!");
serilogsetting.json 文件
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": {
"Default": "Information",
"Override": {
"Microsoft": "Error",
"System": "Error"
}
},
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "C:\\Logs\\OrangeCloud.Service.log",
"rollingInterval": "Day",
"buffered": false,
"rollOnFileSizeLimit": true,
"shared": true,
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff} {Level:u4} {ProcessId} [{RequestId}] --- [{ThreadId,3}] {LoggerName,-40} : {Message:lj}{NewLine}{Exception}"
}
}
]
}
}