这是扩展方法
public static IApplicationBuilder UseLoggerConfig(this IApplicationBuilder app)
{
//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("log.txt", 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
一样使用它
app.UseLoggerConfig();
我想保存\\%windir%\log\callingAppName\logfile.log
上的日志。
有什么想法我们怎么做到这一点?
我想你可以检查hosting environment这样的信息。
IHostingEnvironment.ApplicationName
获取或设置应用程序的名称。该属性由主机自动设置为包含应用程序入口点的程序集。
强调我的
鉴于这是为了共享,应该从它被使用/调用的位置明确注入。即运行应用程序的Web托管环境。
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;
}