How to (programmatically, without xml config) configure multiple loggers with Log4Net? I need them to write to different files.
You can't log to separate appenders - you need to configure different loggers, and attach the appropriate appender to each one. Then log different messages to the different loggers.
For log4net to know where to store your log messages, you add one or more appenders to your configuration. An appender is a C# class that can transform a log message, including its properties, and persist it somewhere. Examples of appenders are the console, a file, a database, an API call, elmah.io, etc.
RollingFileAppender means the system creates a log file based on your filters, this way you can have log files based on dates (one file each day), or get the file splitted into small chunks when it hits certain size.
This thread at the log4net Dashboard details an approach.
To summarize a little, hopefully without ripping off too much code:
using log4net; using log4net.Appender; using log4net.Layout; using log4net.Repository.Hierarchy; // Set the level for a named logger public static void SetLevel(string loggerName, string levelName) { ILog log = LogManager.GetLogger(loggerName); Logger l = (Logger)log.Logger; l.Level = l.Hierarchy.LevelMap[levelName]; } // Add an appender to a logger public static void AddAppender(string loggerName, IAppender appender) { ILog log = LogManager.GetLogger(loggerName); Logger l = (Logger)log.Logger; l.AddAppender(appender); } // Create a new file appender public static IAppender CreateFileAppender(string name, string fileName) { FileAppender appender = new FileAppender(); appender.Name = name; appender.File = fileName; appender.AppendToFile = true; PatternLayout layout = new PatternLayout(); layout.ConversionPattern = "%d [%t] %-5p %c [%x] - %m%n"; layout.ActivateOptions(); appender.Layout = layout; appender.ActivateOptions(); return appender; } // In order to set the level for a logger and add an appender reference you // can then use the following calls: SetLevel("Log4net.MainForm", "ALL"); AddAppender("Log4net.MainForm", CreateFileAppender("appenderName", "fileName.log")); // repeat as desired
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With