I'm using Serilog to log information on my app. I'm using an appsettings.json file (see below) to setup the configuration settings of the logger. In that file, I have two configurations - one for writing to a file and another for writing to the console output. What I would like to be able to do is to only write to a file if my application is running in the IIS context. Otherwise, it should only output the log to the console. However, I'm a bit stuck on how to do this.
appsettings.json
{
"Serilog": {
"Using": [ "SeriLog.Sinks.Console", "Serilog.Sinks.File", "Serilog.Sinks.Async" ],
"MinimumLevel": {
"Default": "Information",
"Override": {
"Microsoft": "Information",
"Microsoft.AspNetCore": "Warning",
"System": "Warning"
}
},
"WriteTo": [
{
"Name": "File",
"Args": {
"outputTemplate": "RC [{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}",
"path": "logs/mylog-.txt",
"rollingInterval": "Day"
}
},
{
"Name": "Console",
"Args": {
"outputTemplate": "RC [{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}"
}
}
],
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
"Properties": {
"Application": "MyApplication"
}
},
"AllowedHosts": "*"
}
Program.cs
public static IConfiguration Configuration { get; } = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddEnvironmentVariables()
.Build();
public static void Main(string[] args)
{
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
Config.Load();
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(Configuration)
.Filter.ByExcluding("RequestPath in ['/healthcheck', '/favicon.ico']")
.CreateLogger();
var host = Host.CreateDefaultBuilder(args)
.UseSerilog()
.ConfigureWebHostDefaults(webBuilder =>
{
var b = webBuilder.ConfigureKestrel((context, options) =>
{
// Handle requests up to 50 MB
options.Limits.MaxRequestBodySize = Config.MaxRequestSize;
})
.UseIISIntegration()
.UseStartup<Startup>()
.CaptureStartupErrors(true);
}).Build();
var logger = host.Services.GetRequiredService<ILogger<ReverseProxyModule>>();
ReverseProxyModule.InitializeConcurrentRequestLogging(logger);
host.Run();
}

