我认为您可以检查托管环境以获取此类信息。
IHostingEnvironment.ApplicationName
获取或设置应用程序的名称。此属性由主机自动设置为包含应用程序入口点的程序集。
强调我的
鉴于这是要共享的,它应该从它被使用/调用的地方显式注入。即应用程序运行的网络托管环境。
public static IApplicationBuilder UseLoggerConfig(this IApplicationBuilder app, IHostingEnvironment env) {
var callingAppName = env.ApplicationName;
var path = $"{callingAppName}/logfile.log";
//add serilog https://github.com/serilog/serilog-extensions-logging
// https://github.com/serilog/serilog-extensions-logging/blob/dev/samples/Sample/Program.cs
Log.Logger = new LoggerConfiguration()
.Enrich.FromLogContext()
.WriteTo.File(path, rollingInterval: RollingInterval.Day)
.CreateLogger();
var startTime = DateTimeOffset.UtcNow;
Log.Logger.Information("Started at {StartTime} and 0x{Hello:X} is hex of 42", startTime, 42);
return app;
}
我们可以Startup
像这样使用它
public void Configure(IApplicationBuilder app, IHostingEnvironment env) {
//...code removed for brevity
app.UseLoggerConfig(env);
}
这也将允许更改基于日志记录位置的环境类型,如开发、登台、生产等。
public static IApplicationBuilder UseLoggerConfig(this IApplicationBuilder app, IHostingEnvironment env) {
var callingAppName = env.ApplicationName;
var path = $"{callingAppName}/logfile.log";
if (env.IsDevelopment()) {
// In Development logging path
} else {
// In Staging/Production logging path
}
//add serilog https://github.com/serilog/serilog-extensions-logging
// https://github.com/serilog/serilog-extensions-logging/blob/dev/samples/Sample/Program.cs
Log.Logger = new LoggerConfiguration()
.Enrich.FromLogContext()
.WriteTo.File(path, rollingInterval: RollingInterval.Day)
.CreateLogger();
var startTime = DateTimeOffset.UtcNow;
Log.Logger.Information("Started at {StartTime} and 0x{Hello:X} is hex of 42", startTime, 42);
return app;
}