我在我的项目中使用 Serilog 来跨不同公司进行文件处理。我正在寻找一种管理结构化日志的方法,根据公司名称将它们组织到单独的文件夹中。是否有可以添加到 appsettings.json 的配置,该配置允许我将公司名称作为参数传递给日志并将其存储在各自的文件夹中?或者,如果有更好的解决方案,我将不胜感激您的指导。
一种方法是利用 ILogEventEnricher 接口:
using Serilog.Core;
using Serilog.Events;
public class CustomerIdEnricher : ILogEventEnricher
{
private readonly string customerId;
public CustomerIdEnricher(string customerId)
{
this.customerId = customerId;
}
public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
{
logEvent.AddPropertyIfAbsent(new LogEventProperty("CustomerId", new ScalarValue(customerId)));
}
}
像这样接线:
Log.Logger = new LoggerConfiguration()
.WriteTo.Logger(customerLogger => customerLogger
.Filter.ByIncludingOnly(e => e.Properties.ContainsKey("CustomerId"))
.WriteTo.File((customerIdLogEvent) =>
{
var customerId = customerIdLogEvent.Properties["CustomerId"].ToString();
return $@"logs\{customerId}.log";
}, LogEventLevel.Information)
)
.CreateLogger();
用途:
var customerId = "12345";
Log.ForContext<CustomerIdEnricher>().Information("Customer {CustomerId} logged in.", customerId);
Log.CloseAndFlush();
如果没有太多问题,这对于小型网站来说可能没问题,尽管现在许多网站都使用 Grafana、Splunk、Sumo 等日志记录公司之一进行治理和合规性。
我认为这个问题与您想要完成的任务指向类似的方向,也许会有所帮助:Serilog,将日志插入多租户应用程序中的特定数据库
或者,如果有更好的解决方案,我将不胜感激您的指导。
我想说最好将它们放在一起,这样您就可以在需要时执行跨公司分析。为此,请在日志中添加
Tenant
字段。您可以按照本文的“ABP框架+Serilog”部分的说明进行操作。
主要有两个步骤:
public class SessionLoggingMiddleware : IMiddleware, ITransientDependency
{
private readonly ICurrentTenant _currentTenant;
public SessionLoggingMiddleware(ICurrentTenant currentTenant)
{
_currentTenant = currentTenant;
}
public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
using (Serilog.Context.LogContext.PushProperty("TenantId", _currentTenant.Id))
{
await next(context);
}
}
}
Log.Logger = new LoggerConfiguration()
.Enrich.FromLogContext()
.WriteTo.Async(c => c.File("Logs/logs.txt", outputTemplate:
"{Level:u4} [{TenantId}] [{Timestamp:HH:mm:ss}] {Message:lj}{NewLine}{Exception}"))
.WriteTo.Async(c => c.Console())
.CreateLogger();