Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Serilog Typical setup for Log to RollingFile from Config. with fallback
static class LoggingConfig
{
/// <summary>
/// After calling this method, use the logger with
/// <code>Log.Logger....</code>
/// e.g.
/// <see cref="Log.Logger"/>.<see cref="ILogger.Debug(string,object[])"/>
/// </summary>
public static ILogger RegisterLogger(ILogger overrideLogger=null)
{
IsInitted = true;
return Log.Logger = overrideLogger ?? (LoggerConfigurationForWriteToLogFile().CreateLogger());
}
static LoggerConfiguration LoggerConfigurationForWriteToLogFile()
{
var loggingPath = @"C:\Logs\AppName.{Date}.txt";
var fileSizeLimitBytes = 1000000;
var retainedFileCountLimit = 99;
try
{
loggingPath = ConfigurationManager.AppSettings["serilog:write-to:RollingFile.pathFormat"];
retainedFileCountLimit = int.Parse(ConfigurationManager.AppSettings["serilog:write-to:RollingFile.retainedFileCountLimit"]);
fileSizeLimitBytes = int.Parse(ConfigurationManager.AppSettings["serilog:write-to:RollingFile.fileSizeLimitBytes"]);
}
catch{}
return new LoggerConfiguration()
.MinimumLevel.Is(RestrictedToMinimumLevel)
.WriteTo.RollingFile(
loggingPath,
retainedFileCountLimit: retainedFileCountLimit,
fileSizeLimitBytes: fileSizeLimitBytes,
shared: true
);
}
public static ILogger Logger { get { return IsInitted ? Log.Logger : RegisterLogger(); } }
public static string Template { get; private set; }
internal static bool IsInitted;
internal static LogEventLevel RestrictedToMinimumLevel;
static LoggingConfig()
{
Serilog.Debugging.SelfLog.Enable(Console.Out);
try { RestrictedToMinimumLevel = (LogEventLevel)Enum.Parse(typeof(LogEventLevel), ConfigurationManager.AppSettings["serilog:minimum-level"]); }
catch { RestrictedToMinimumLevel = LogEventLevel.Debug; }
Template = " \nUrl: {RequestUrl}\nUrlReferrer: {UrlReferrer}\n";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.