环境:window10
- .netcore 3.1
- vs2019.16.5.1
- Serilog.AspNetCore 3.2.0
一、安装Serilog
首先,新建一个.netcore 3.1 的webapi项目,略。
然后在工程文件的根节点下添加:
<ItemGroup>
<PackageReference Include="Serilog.AspNetCore" Version="3.2.0" />
</ItemGroup>
或者 在nuget中直接搜索Serilog.AspNetCore安装
二、在Program.cs文件中配置Serilog
在这里,我将aspnetcore框架原有的日志组件删除掉,然后再加入Serilog,直接看代码:
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
})
//添加Serilog
.UseSerilog((hostingContext, loggerConfiguration) =>
//从appsettings.json中读取配置
loggerConfiguration.ReadFrom.Configuration(hostingContext.Configuration)
.Enrich.FromLogContext()
);
}
三、在appsettings.json中进行日志配置
下面给Serilog配置日志输出程序:控制台输出、文件日志(按照日期输出)
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"Serilog": {
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "log.txt",
"rollingInterval": "Day"
}
},
{
"Name": "Console",
"Args": {}
}
]
},
"AllowedHosts": "*"
}
四、编写测试日志代码
改造控制器:WeatherForecastController,修改Get方法如下:
[HttpGet]
public IEnumerable<WeatherForecast> Get()
{
_logger.LogTrace("LogTrace");
_logger.LogDebug("LogDebug");
_logger.LogInformation("LogInformation");
_logger.LogWarning("LogWarning");
_logger.LogError("LogError");
_logger.LogCritical("LogCritical");
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();
}
五、运行测试
直接调试运行:
控制台输出:
文件输出:
浏览器中输入:https://localhost:5001/WeatherForecast
控制台输出:
文件输出:
六、如何同时保留Serilog和其他日志记录提供程序?
在上面示例中,我们使用Serilog,但我们发现 asp.net core 原来的输出到控制台、调试窗口的都不管用了,有没有什么办法能同时保留它们吗?
看下面代码:
//只需要在UseSerilog中加入参数 writeToProviders: true
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
})
//添加Serilog
.UseSerilog((hostingContext, loggerConfiguration) =>
//从appsettings.json中读取配置
loggerConfiguration.ReadFrom.Configuration(hostingContext.Configuration)
.Enrich.FromLogContext()
, preserveStaticLogger: false, writeToProviders: true);
七、如何按照日志类别输出到不同的日志文件中?
参考下面代码(控制不输出以 Microsoft 开头的日志类别):
//只需要在UseSerilog中加入参数 writeToProviders: false
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
})
//添加Serilog
.UseSerilog((hostingContext, loggerConfiguration) =>
//从appsettings.json中读取配置
loggerConfiguration.ReadFrom.Configuration(hostingContext.Configuration)
.Enrich.FromLogContext()
.Filter.ByExcluding(evt =>
{
var SourceContext = evt.Properties.FirstOrDefault(i => i.Key == "SourceContext").Value.ToString();
SourceContext = SourceContext.Trim('\"');
//
return SourceContext.StartsWith("Microsoft") || SourceContext.StartsWith("System");
})
);
上面这段代码也没有实现不同的类别输出到不同的文件中,可以参考其他日志组件:
https://gitee.com/jackletter/jackletter.microsoft.extensions.logging.file
八、如何以json形式输出日志
如果我们需要分析日志或者是将已经存在的日志文件写入到 ELK,那么我们就需要提供格式良好的日志记录,比如:json。
下面演示,如何将日志输出成json形式。
其实,只需要在上面的 Appsettings.json 中 添加一行配置,如下:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"Serilog": {
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "log.txt",
"rollingInterval": "Day",
//增加的json格式化配置
"formatter": "Serilog.Formatting.Compact.RenderedCompactJsonFormatter, Serilog.Formatting.Compact"
}
},
{
"Name": "Console",
"Args": {}
}
]
},
"AllowedHosts": "*"
}
测试输出的效果:
{"@t":"2022-05-31T03:37:21.7033342Z","@m":"Now listening on: \"http://localhost:5000\"","@i":"d826f4b8","address":"http://localhost:5000","SourceContext":"Microsoft.Hosting.Lifetime"}
{"@t":"2022-05-31T03:37:21.7478674Z","@m":"Application started. Press Ctrl+C to shut down.","@i":"dcaefe54","SourceContext":"Microsoft.Hosting.Lifetime"}
{"@t":"2022-05-31T03:37:21.7496121Z","@m":"Hosting environment: \"Development\"","@i":"c3307c92","envName":"Development","SourceContext":"Microsoft.Hosting.Lifetime"}
{"@t":"2022-05-31T03:37:21.7511740Z","@m":"Content root path: \"D:\\jackletter\\codes\\TestSln\\WebApplication4\"","@i":"b5d60022","contentRoot":"D:\\jackletter\\codes\\TestSln\\WebApplication4","SourceContext":"Microsoft.Hosting.Lifetime"}
{"@t":"2022-05-31T03:37:22.3469402Z","@m":"Request starting HTTP/1.1 GET http://localhost:5000/weatherforecast ","@i":"ca22a1cb","Protocol":"HTTP/1.1","Method":"GET","ContentType":null,"ContentLength":null,"Scheme":"http","Host":"localhost:5000","PathBase":"","Path":"/weatherforecast","QueryString":"","HostingRequestStartingLog":"Request starting HTTP/1.1 GET http://localhost:5000/weatherforecast ","EventId":{"Id":1},"SourceContext":"Microsoft.AspNetCore.Hosting.Diagnostics","RequestId":"0HMI2MRFF185B:00000001","RequestPath":"/weatherforecast","SpanId":"|aa4d8bfc-47ed3d03c0b3e886.","TraceId":"aa4d8bfc-47ed3d03c0b3e886","ParentId":"","ConnectionId":"0HMI2MRFF185B"}
{"@t":"2022-05-31T03:37:22.4024912Z","@m":"Executing endpoint '\"WebApplication4.Controllers.WeatherForecastController.Get (WebApplication4)\"'","@i":"500cc934","EndpointName":"WebApplication4.Controllers.WeatherForecastController.Get (WebApplication4)","EventId":{"Name":"ExecutingEndpoint"},"SourceContext":"Microsoft.AspNetCore.Routing.EndpointMiddleware","RequestId":"0HMI2MRFF185B:00000001","RequestPath":"/weatherforecast","SpanId":"|aa4d8bfc-47ed3d03c0b3e886.","TraceId":"aa4d8bfc-47ed3d03c0b3e886","ParentId":"","ConnectionId":"0HMI2MRFF185B"}
{"@t":"2022-05-31T03:37:22.4558839Z","@m":"Route matched with \"{action = \\\"Get\\\", controller = \\\"WeatherForecast\\\"}\". Executing controller action with signature \"System.Collections.Generic.IEnumerable`1[WebApplication4.WeatherForecast] Get()\" on controller \"WebApplication4.Controllers.WeatherForecastController\" (\"WebApplication4\").","@i":"122b2fdf","RouteData":"{action = \"Get\", controller = \"WeatherForecast\"}","MethodInfo":"System.Collections.Generic.IEnumerable`1[WebApplication4.WeatherForecast] Get()","Controller":"WebApplication4.Controllers.WeatherForecastController","AssemblyName":"WebApplication4","EventId":{"Id":3,"Name":"ControllerActionExecuting"},"SourceContext":"Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker","ActionId":"c265f88c-1fa1-403d-bd11-2afe0cbab562","ActionName":"WebApplication4.Controllers.WeatherForecastController.Get (WebApplication4)","RequestId":"0HMI2MRFF185B:00000001","RequestPath":"/weatherforecast","SpanId":"|aa4d8bfc-47ed3d03c0b3e886.","TraceId":"aa4d8bfc-47ed3d03c0b3e886","ParentId":"","ConnectionId":"0HMI2MRFF185B"}