Created
August 6, 2020 20:55
-
-
Save scheffler/4e3aff0a727db07936fcfd14bb30fd46 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Reflection; | |
using log4net; | |
using log4net.Appender; | |
using log4net.Core; | |
using log4net.Layout; | |
using log4net.Repository.Hierarchy; | |
using Microsoft.Extensions.Configuration; | |
// also need Microsoft.Extensions.Configuration.Binding for the Bind to work | |
namespace ControlCenter.Model | |
{ | |
// First cut at configuring log4net through code in dotnet core | |
public class LoggingConfigurator | |
{ | |
class Log4NetSettings | |
{ | |
public string FileName { get; set; } | |
} | |
public static void ConfigureLogging(IConfiguration config) | |
{ | |
var settings = new Log4NetSettings(); | |
config.Bind("log4net", settings); | |
var hierarchy = (Hierarchy)LogManager.GetRepository(Assembly.GetExecutingAssembly()); | |
hierarchy.Root.RemoveAllAppenders(); | |
PatternLayout fileLayout = new PatternLayout(); | |
fileLayout.ConversionPattern = "[%-5level] %date{yyyy-MM-dd HH:mm:ss}: %message%newline"; | |
fileLayout.ActivateOptions(); | |
PatternLayout consoleLayout = new PatternLayout(); | |
consoleLayout.ConversionPattern = "[%-5level] %date{yyyy-MM-dd HH:mm:ss}: %message%newline"; | |
consoleLayout.ActivateOptions(); | |
RollingFileAppender roller = new RollingFileAppender(); | |
roller.AppendToFile = true; | |
roller.File = settings.FileName ?? "log.txt"; | |
roller.MaximumFileSize = "100MB"; | |
roller.MaxSizeRollBackups = 5; | |
roller.RollingStyle = RollingFileAppender.RollingMode.Size; | |
roller.CountDirection = -1; | |
roller.LockingModel = new FileAppender.MinimalLock(); | |
roller.Layout = fileLayout; | |
roller.ActivateOptions(); | |
hierarchy.Root.AddAppender(roller); | |
ConsoleAppender console = new ConsoleAppender(); | |
console.Layout = consoleLayout; | |
console.ActivateOptions(); | |
hierarchy.Root.AddAppender(console); | |
hierarchy.Root.Level = Level.Info; | |
var nhiblog = hierarchy.GetLogger("NHiberate"); | |
nhiblog.Repository.Threshold = Level.Warn; | |
hierarchy.Configured = true; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment