使用appsettings.json配置Serilog RollingFile
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用appsettings.json配置Serilog RollingFile相关的知识,希望对你有一定的参考价值。
我正在尝试为.NET Core项目配置Serilog。这是我在appsettings.json
中的内容:
"Serilog":
{
"MinimumLevel": "Verbose",
"Enrich": ["FromLogContext", "WithMachineName", "WithProcessId", "WithThreadId"],
"WriteTo": [
{ "Name": "RollingFile",
"Args": {
"pathFormat": "C:/Logfiles/testapp/log-{Date}.json",
"textFormatter": "JsonFormatter",
"fileSizeLimitBytes": 2147483648,
"retainedFileCountLimit": 5
}
}
]
}
我看到的问题是没有拾取JsonFormatter
,而是使用默认文本格式化器获取条目。我尝试使用"formatter": "JsonFormatter"
,但得到了相同的结果。
如果我在代码中配置Serilog,一切正常:
var jsonSink = new RollingFileSink(config["Logger:FilePath"], new JsonFormatter(), 2147483648, 5);
var logger = new Serilog.LoggerConfiguration().WriteTo.Sink(jsonSink);
这是我的project.json
的相关部分:
"Serilog": "2.2.1",
"Serilog.Extensions.Logging": "1.1.0",
"Serilog.Sinks.Literate": "2.0.0",
"Serilog.Sinks.Seq": "2.0.0",
"Microsoft.Extensions.Configuration.EnvironmentVariables": "1.0.0",
"Microsoft.Extensions.Configuration.Json": "1.0.0",
"Microsoft.Extensions.Configuration.UserSecrets": "1.0.0",
"Microsoft.Extensions.Logging": "1.0.0",
"Microsoft.Extensions.Logging.Console": "1.0.0",
"Microsoft.Extensions.Logging.Debug": "1.0.0",
"Microsoft.Extensions.Options.ConfigurationExtensions": "1.0.0",
"Serilog.Enrichers.Thread": "2.0.0",
"Serilog.Enrichers.Process": "2.0.0",
"Serilog.Sinks.ColoredConsole": "2.0.0",
"Serilog.Settings.Configuration": "2.2.0"
关于如何使这个工作的任何指针?
谢谢!
答案
formatter
参数必须是完全限定的类型名称。尝试:
"formatter": "Serilog.Formatting.Json.JsonFormatter, Serilog"
另一答案
以下作品:
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.WriteTo.RollingFile(Path.Combine(env.ContentRootPath, "C:\logs\log-{Date}.txt"),
outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] [{SourceContext}] [{EventId}] {Message}{NewLine}{Exception}")
//.ReadFrom.Configuration(Configuration)
.CreateLogger();
Log.Logger.Information("test");
以下也有效(仅显示CreateLogger部分):
Log.Logger = new LoggerConfiguration()
//.MinimumLevel.Debug()
//.WriteTo.RollingFile(Path.Combine(env.ContentRootPath, "C:\logs\log-{Date}.txt"),
// outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] [{SourceContext}] [{EventId}] {Message}{NewLine}{Exception}")
.ReadFrom.Configuration(Configuration)
.CreateLogger();
appsettings.json文件(这里的相关部分是Serilog):
{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
},
"Serilog": {
"MinimumLevel": "Debug",
"WriteTo": [
{
"Name": "RollingFile",
"Args": {
"pathFormat": "C:\logs\log-{Date}.txt",
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] [{SourceContext}] [{EventId}] {Message}{NewLine}{Exception}"
}
}
]
}
}
project.json中的NuGet包:
- “Serilog”:“2.3.0”,
- “Serilog.Extensions.Logging”:“1.3.1”,
- “Serilog.Sinks.RollingFile”:“3.2.0”,
- “Serilog.Sinks.File”:“3.1.1”,
- “Serilog.Settings.Configuration”:“2.2.0”
我的目标框架是net452。
另一答案
以下配置有效:
"Serilog": {
"Using": [ "Serilog.Sinks.Console" ],
"MinimumLevel": "Information",
"WriteTo": [
{
"Name": "Console",
"Args": {
"outputTemplate": "===> {Timestamp:HH:mm:ss} [{Level}] {Message}{NewLine}{Exception}"
}
},
{
"Name": "RollingFile",
"Args": {
"pathFormat": "Logs\log-{Date}.json",
"formatter": "Serilog.Formatting.Compact.CompactJsonFormatter, Serilog.Formatting.Compact",
"fileSizeLimitBytes": 104857600
}
}
]
}
在Program.cs中:
public static IConfiguration Configuration { get; } = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", optional: true)
.AddEnvironmentVariables()
.Build();
public static void Main(string[] args)
{
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(Configuration)
.CreateLogger();
...
}
和
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseConfiguration(Configuration)
.ConfigureLogging(log => { log.AddSerilog(Log.Logger); })
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
并将记录器注入您的控制器:
public class UsersController : ControllerBase
{
private readonly ILogger<UsersController> _logger;
public UsersController(ILogger<UsersController> logger)
{
_logger = logger;
}
//your code
}
我得到的结果示例:
{
"@t": "2019-04-12T14:03:08.2789776Z",
"@mt": "GetUserMessages()=> ",
"@r": [
"000117"
],
"Elapsed": 117,
"SourceContext": "MyProject.Web.Controllers.UsersController",
"ActionId": "1b8bc4b9-5858-415b-ab4e-56ba14a5a1ca",
"ActionName": "MyProject.Web.Controllers.UsersController.GetUserMessages (MyProject.Web)",
"RequestId": "0HLLVSDFSA43ES:00000001",
"RequestPath": "/TestAppId/messages",
"CorrelationId": null,
"ConnectionId": "0HLLVSDFSA43ES"
}
以上是关于使用appsettings.json配置Serilog RollingFile的主要内容,如果未能解决你的问题,请参考以下文章
在 EF 上下文中使用 appsettings.json 配置
使用appsettings.json配置Kestrel监听端口Dotnet core 2 preview 2
如何使用 .NET Core 根据发布配置文件更新 appsettings.json?