You may override the log4net.config specs for writing logs from code as seen below. In this example we override where the log gets written to and what its name is:
log4net.Repository.Hierarchy.Hierarchy hierarchy = LogManager.GetLoggerRepository()
as log4net.Repository.Hierarchy.Hierarchy;
RollingFileAppender appender = (RollingFileAppender)hierarchy.GetAppenders()
.Where(x => x.GetType() == typeof(RollingFileAppender)).FirstOrDefault();
string filePathToLogTo = "c:\myfolder\whatever.log";
appender.File = filePathToLogTo;
appender.ActivateOptions();
While I am thinking of it there is something to be wary of in this code. Somewhere upstream you will have something like so:
var fileInfo = new FileInfo("c:\something\log4net.config");
XmlConfigurator.Configure(fileInfo);
If the config file is not found at the path specified, then hierarchy.GetAppenders() will return an empty array and you will get an opague error message. That goes for this too. If this is happening to you, just make sure that your config file exists. I know this is hard to troubleshoot. Visual Studio will put a squiggly blue line under appender.File warning you that appender could be null either way, but honestly if it is null it is going to be because you cannot find the config file.
No comments:
Post a Comment