So I am adding logging functionality to an application using log4net. I have created a class to setup logging since I will need to instantiate multiple loggers. Every time I need to create a new logging instance I intent to invoke this method and pass it the necessary parameters.
public class Logging
{
/// <summary>
/// Sets up a new logging instance
/// </summary>
public void Setup(string logName, log4net.Core.Level logLevel)
{
Hierarchy hierarchy = (Hierarchy)LogManager.GetRepository();
PatternLayout patternLayout = new PatternLayout
{
ConversionPattern = "%date [%thread] %-5level - %message%newline"
};
patternLayout.ActivateOptions();
RollingFileAppender roller = new RollingFileAppender
{
Name = logName,
AppendToFile = true,
File = "path\\to\\log\\ " + logName + ".txt",
Layout = patternLayout,
MaxSizeRollBackups = 5,
MaximumFileSize = "1GB",
RollingStyle = RollingFileAppender.RollingMode.Size,
StaticLogFileName = true,
Threshold = logLevel
};
roller.ActivateOptions();
hierarchy.Root.AddAppender(roller);
//MemoryAppender memory = new MemoryAppender();
//memory.ActivateOptions();
//hierarchy.Root.AddAppender(memory);
hierarchy.Name = logName;
hierarchy.Root.Level = Level.Info;
hierarchy.Configured = true;
}
}
Using this code I can initialize and add new loggers to the collection like so:
//in a certain context
//loglevel is an assigned log level
var fileName = "Client Execution Log";
var logging = new Logging();
logging.Setup(fileName, logLevel);
var executionLog = log4net.LogManager.GetLogger(fileName);
//in another context
//loglevel is an assigned log level
var fileName = "Server Response Log";
var logging = new Logging();
logging.Setup(fileName, logLevel);
var serverLog = log4net.LogManager.GetLogger(fileName);
The problem is any time I call the method to write a log serverLog.info("server responded 404")
it ends up writing to all files rather that the file that was passed in when Setup
was called. How do I properly set up logging so that each logging instance only writes to its own file that was passed to the setup method?