This is the extension method
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;
}
and we can use this in Startup
like so
app.UseLoggerConfig();
I Would like to save the logs on \\%windir%\log\callingAppName\logfile.log
.
Any ideas how we could do this ?
I am thinking you could check the hosting environment for information like that.
IHostingEnvironment.ApplicationName
Gets or sets the name of the application. This property is automatically set by the host to the assembly containing the application entry point.
emphasis mine
Given that this is meant to be shared, it should be explicitly injected from where it is being used/called. ie the web hosting environment the application is running in.
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;
}
and we can use this in Startup
like so
public void Configure(IApplicationBuilder app, IHostingEnvironment env) {
//...code removed for brevity
app.UseLoggerConfig(env);
}
This would also allow for the changing of logging location based environment type like development, staging, production, etc.
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;
}