我想在Serilog文件接收器生成的日志文件中添加主机名。
我尝试在下面,但我的文件名显示为log-{fileName}-20210910.txt
下面的代码,
vservices.AddLogging(logging => logging.AddSerilog(
new LoggerConfiguration()
.WriteTo.RollingFile(Path.Combine(Environment.CurrentDirectory, $"log-{fileName}.txt"),
outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {fileName}, {Message:lj}{NewLine}{Exception}")
.CreateLogger()));
在定义serilog
配置时如何访问fileName
变量?
您缺少$符号
var fileName = Environment.GetEnvironmentVariable("HOSTNAME") ?? "add-on";
services.AddLogging(logging => logging.AddSerilog(new LoggerConfiguration()
.WriteTo.RollingFile(Path.Combine(Environment.CurrentDirectory, $"log-{fileName}.txt"))
.CreateLogger()));
其他选项为:
var fileName = Environment.GetEnvironmentVariable("HOSTNAME") ?? "add-on";
services.AddLogging(logging => logging.AddSerilog(new LoggerConfiguration()
.WriteTo.RollingFile(Path.Combine(Environment.CurrentDirectory, "log-" + fileName + ".txt"))
.CreateLogger()));
对于我的asp.net Core 6 WebApp,我添加了steeltoe占位符扩展库
https://docs.steeltoe.io/api/v2/configuration/placeholder-provider.html
将解析器添加到配置
public Startup(IConfiguration configuration)
{
_configuration = configuration.AddPlaceholderResolver();
}
然后更改了我的appsettings
{
"Serilog": {
"Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.File" ],
"MinimumLevel": "Debug",
"WriteTo": [
{ "Name": "Console" },
{
"Name": "File",
"Args": {
"formatter": "Serilog.Formatting.Compact.CompactJsonFormatter, Serilog.Formatting.Compact",
"path": "/tmp/logs/webapi/${HOSTNAME}_.log", //Linux version
//"path": "/tmp/logs/webapi/${COMPUTERNAME}_.log", //Windows version
"rollingInterval": "Day",
"rollOnFileSizeLimit": true,
"fileSizeLimitBytes": 1073741824,
"retainedFileCountLimit": 31
}
},
{
"Name": "Seq",
"Args": { "serverUrl": "http://dc-seq-service:5341" }
}
]
}
}
我用这个
将用户名添加到路径中{"path": "/tmp/logs/webapi/%USERNAME%_.log"}
从环境变量
中获取用户名