c# - Serilog 多个文件 appsettings.json
问题描述
我试图将 serilog 配置为写入多个文件,但没有任何运气。使用此配置它只是写入第二个文件?
{
"AllowedHosts": "*",
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Debug",
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "c:\\temp\\audit-.log",
"rollingInterval": "Day",
"restrictedToMinimumLevel": "Information"
}
},
{
"Name": "File",
"Args": {
"path": "c:\\temp\\error-.log",
"rollingInterval": "Day",
"restrictedToMinimumLevel": "Error"
}
}
]
}
}
或者有什么方法可以从 appsettings.json 将许多记录器加载到具有不同配置的软件中。像这样的东西?
var errorLogConfiguration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", optional: true)
.AddEnvironmentVariables()
.Build();
_log = new LoggerConfiguration()
.ReadFrom
.Configuration(errorLogConfiguration)
.CreateLogger();
解决方案
我找到了解决方案。为 appsettings.json、ErrorLog 和 AuditLog 创建了单独的部分。
"ErrorLog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Debug",
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "c:\\temp\\error-.log",
"rollingInterval": "Day",
"restrictedToMinimumLevel": "Error"
}
}
]
},
"AuditLog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Debug",
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "c:\\temp\\audit-.log",
"rollingInterval": "Day",
"restrictedToMinimumLevel": "Information"
}
}
]
}
现在我可以创建 2 个单独的记录器:
var errorLogConfiguration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", optional: true)
.AddEnvironmentVariables()
.Build();
var errorSection = errorLogConfiguration.GetSection("ErrorLog");
var auditSection = errorLogConfiguration.GetSection("AuditLog");
_log = new LoggerConfiguration()
.ReadFrom
.ConfigurationSection(errorSection)
.CreateLogger();
_auditLog = new LoggerConfiguration()
.ReadFrom
.ConfigurationSection(auditSection)
.CreateLogger();
哪个更适合我的需要。
推荐阅读
- android - 按下登录按钮时,如何将电子邮件和密码与数据库中的进行比较?
- reactjs - 使用 useState 通过单击按钮来响应更新状态
- php - 使用 SUM 和 COUNT 显示 2 个表中的数据
- python-3.x - “DatasetGroupBy”对象不可下标
- sql - 我想创建一个映射表,我想在其中存储 old_id 和它各自的 new_id
- eclipse - 如何以编程方式将 URL 添加到“可用软件站点”首选项
- sql - 检索每组的第二高计数
- mongodb - Golang 从嵌套映射结构构建 Mongo 查询
- makefile - 在特定位置创建 .so 文件
- unix - Unix命令在同一个文件中搜索多个模式