我需要创建一个JSON格式的日志与下面的格式我的Web API项目。
{
"LEVEL":"ERROR",
"TIMESTAMP":"2023-06-07 14:07:59,983",
"CALLER" : "CLIENT NAME",
"EVENT_NAME":"WHICH METHOD CALLED HERE",
"ERRORID":"10001",
"MESSAGE":"INVALID REQUEST/REQUEST COMPLETED"
}
下面是我的appsetting.json文件。
"Serilog": {
"Using": ["Serilog.Sinks.Console"],
"MinimumLevel": {
"Default": "Information"
},
"Enrich": [ "FromLogContext"],
"WriteTo": [
{
"Name": "Console",
"Args": {
"theme": "Serilog.Sinks.SystemConsole.Themes.AnsiConsoleTheme::Code, Serilog.Sinks.Console",
"outputTemplate": "[{Level}][{Timestamp:yyyy-MM-dd HH:mm:ss.fff}] Message:{Message}{NewLine}{Exception}"
}
}
]
}
我的logConfig.cs文件是
public static void ConfigureSerilogServices(this IServiceCollection services)
{
var configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.Build();
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();
}
我在控制台上可以看到serilog中的一些值,比如timestamp,level,message,但是我不知道如何将它转换成json格式和添加一些运行时值
1条答案
按热度按时间x3naxklr1#
我可以展示我是如何为我自己的用例实现自定义 Package 器的,你可以用它作为编写自己的日志 Package 器的例子。
我的用例是,我想在每个日志消息前面加上文件和方法名称,说明日志来自何处。
Program.cs
LogRegister.cs:
注意上面的
[{CallerFileName}.{CallerMethodName}]
。这就是我注射的东西。在您的情况下,您可能希望将整行替换为占位符,如下所示:var outputTemplate = "{MyJsonMessage}";
Package 器
Log.cs
:ClassAndMethodContextEnricher.cs:
用法:只需在应用程序中的任何位置使用
Log.
即可。不需要注射任何东西:在本例中,您需要编写用于在Enricher类中创建和注入JSON的主要逻辑。实际上,有很多方法可以将您自己的自定义Message封装为json。我的日志 Package 器对于您的需要来说可能太复杂了,但这是一种方法。如果你想要更简单的方法,你将需要深入挖掘Serilog肠道。
祝你好运