Skip to content

Instantly share code, notes, and snippets.

@scottoffen
Created December 7, 2022 21:33
Show Gist options
  • Save scottoffen/09e060f34f1c267d056494aa592b2c30 to your computer and use it in GitHub Desktop.
Save scottoffen/09e060f34f1c267d056494aa592b2c30 to your computer and use it in GitHub Desktop.
Configure Rolling Logs in ASP.NET 6.0
{
"FileLoggerOptions": {
"RetainedFileCountLimit": 3,
"FileName": "diagnostics-",
"LogDirectory": "logs",
"FileSizeLimit": 1048576,
"Extension": "txt",
"Periodicity": 1
}
}
using System.Diagnostics.CodeAnalysis;
namespace SampleApplication.Api
{
[ExcludeFromCodeCoverage]
public static class Program
{
private const string DefaultSettingsFile = "appsettings.json";
private static IConfiguration _configuration;
private static IConfiguration _loggerOptions;
public static void Main(string[] args)
{
var settingsFile = GetSettingsFile();
_configuration = new ConfigurationBuilder()
.AddJsonFile(settingsFile, false, true)
.AddJsonFile("other.stuff.json", false, true)
.AddEnvironmentVariables()
.Build();
_loggerOptions = _configuration.GetSection("FileLoggerOptions");
var factory = LoggerFactory.Create(builder =>
{
builder.ClearProviders();
builder.AddFile(options =>
{
_loggerOptions.Bind(options);
});
});
var logger = factory.CreateLogger("Program");
try
{
logger.LogInformation("Application Starting");
logger.LogInformation("Settings file {SettingsFile}", settingsFile);
CreateHostBuilder(args).Build().Run();
}
catch (Exception ex)
{
logger.LogCritical(ex, "The application failed to start");
}
}
public static IHostBuilder CreateHostBuilder(string[] args)
{
return Host.CreateDefaultBuilder(args)
.ConfigureLogging((context, logging) =>
{
logging.ClearProviders();
logging.AddFile(options =>
{
_loggerOptions.Bind(options);
});
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>()
.ConfigureAppConfiguration(builder =>
{
builder.SetBasePath(Directory.GetCurrentDirectory())
.AddConfiguration(_configuration);
});
});
}
private static string GetSettingsFile()
{
var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
if (string.IsNullOrWhiteSpace(environment))
{
return DefaultSettingsFile;
}
var settingsFile = $"appsettings.{environment}.json";
return File.Exists(Path.Combine(Environment.CurrentDirectory, settingsFile))
? settingsFile
: DefaultSettingsFile;
}
}
}
@scottoffen
Copy link
Author

NetEscapades.Extensions.Logging.RollingFile

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment