这是扩展方法
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
。
我们如何才能做到这一点?
答案 0 :(得分:1)
我想你可以查看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;
}