我有一个 ASP.NET Core Web API。我需要将用户名添加到 Serilog 文件名中。我的
appsettings.json
文件如下所示:
"Serilog": {
"MinimumLevel": {
"Default": "Information",
"Override": {
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"WriteTo": [
{
"Name": "File",
"Args": {
"Path": "E:\\WebSite\\Development\\HealthAPI\\Logs\\log.txt",
"rollingInterval": "Hour",
"outputTemplate": "[{Timestamp:yyyy-MM-dd HH:mm:ss} {CorrelationId} {Level:u3}] [{Username}] {Message:lj}{NewLine}{Exception}"
}
}
]
}
这是
program.cs
:
var _logger = new LoggerConfiguration()
.ReadFrom.Configuration(builder.Configuration)
.MinimumLevel.Override("Microsoft.AspNetCore", LogEventLevel.Warning)
.Enrich.FromLogContext()
.CreateLogger();
builder.Logging.AddSerilog(_logger);
app.UseMiddleware<LogUserNameMiddleware>();
app.UseSerilogRequestLogging();
我的中间件是
public class LogUserNameMiddleware
{
private readonly RequestDelegate next;
public LogUserNameMiddleware(RequestDelegate next)
{
this.next = next;
}
public async Task Invoke(HttpContext context)
{
using (LogContext.PushProperty("UserName", context.User.Identity.Name ?? "anonymous"))
{
await next(context);
}
}
}
我需要在文件名中包含用户名,例如
Log_ABC_Date.txt
。
更新1: 我更改了 Program.cs :
var _logger = new LoggerConfiguration()
.WriteTo.Map("LoginController", "Other", (name, wt) => wt.File(@"E:\Logs\log-{name}.txt"))
.MinimumLevel.Override("Microsoft.AspNetCore", LogEventLevel.Warning)
.Enrich.FromLogContext()
.CreateLogger();
还有我的控制器:
private readonly Serilog.ILogger _logger = Log.Logger.ForContext("LoginController","Username");
_logger.Warning("Helllo !! {Name}",user.UserName);
这仍然是一个问题。由于 Serilog.Sinks.Map 是围绕映射函数构建的,因此无法使用 JSON 配置,因此我使用 Program.cs 来配置 Serilog。
根据Nicholas Blumhardt的建议,我实现了,请查看下面。
1。项目结构
2。 LogUserNameMiddleware.cs
using Serilog.Context;
namespace LogUserName1
{
public class LogUserNameMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger<LogUserNameMiddleware> _logger;
public LogUserNameMiddleware(RequestDelegate next, ILogger<LogUserNameMiddleware> logger)
{
_next = next;
_logger = logger;
}
public async Task Invoke(HttpContext context)
{
var userName = context.User.Identity.Name ?? "anonymous";
using (LogContext.PushProperty("UserName", userName))
{
await _next(context);
}
}
}
}
3.程序.cs
using Microsoft.AspNetCore.Authentication.Negotiate;
using Serilog.Events;
using Serilog;
var builder = WebApplication.CreateBuilder(args);
var _logger = new LoggerConfiguration()
.MinimumLevel.Override("Microsoft.AspNetCore", LogEventLevel.Information)
.Enrich.FromLogContext()
.WriteTo.Map(
keyPropertyName: "UserName",
defaultKey: "anonymous",
(userName, logConfiguration) => logConfiguration.File($"E:\\WebSite\\Development\\HealthAPI\\Logs\\log_{userName}_Date.txt")
)
.CreateLogger();
builder.Logging.AddSerilog(_logger);
// Add services to the container.
builder.Services.AddControllersWithViews();
...
4。套餐
5。测试结果