tags:

views:

342

answers:

2

I want to know how to dynamically assign file name using Log4net .My application is such that 10 different files should be dynamically created based on user input ,and later based on the name the corresponding file name needs to be picked up and information written to it

For example in my application based on my buisness requirement for every xml file a corresponding log file with the same name as xml file should be created .Later whenever I do any modification to the xml file an entry needs to be in the corresponding log file

Please help . I having trouble to get control of the appropriate log to write it

+1  A: 

Have not done this, but there are probably a number of ways of doing this, so this may not be the best way, but it should work

public OpenLogFile(string fileName)
{
    log4net.Layout.ILayout layout = new log4net.Layout.PatternLayout("%d [%t]%-5p : - %m%n");;    
    log4net.Appender.FileAppender appender = new log4net.Appender.FileAppender(layout ,    filename);
    appender.Threshold = log4net.Core.Level.Info;
    log4net.Config.BasicConfigurator.Configure(appender);
}

Then just call OpenLogfile when you need to switch files.

You might need to tweak the layout or appender type.

A big disadvantage of this method is you losing the xml configuration and the ability to change settings at runtime. So a better way might be to configure your appender in the xml file to use a property

eg

file type="log4net.Util.PatternString" value="Logfiles\Log_For_%property{MyLogFileName}"

Then in your code you could change the property

log4net.GlobalContext.Properties["MyLogFileName"] =  ...;

The tricky bit is to get log4net to reload itself. I haven't read the documentation of this, so I don't know if there is a way of forcing a reload. It might work if you just call log4net.Config.XmlConfigurator.ConfigureAndWatch again. Otherwise it should work if you opened the xml file and saved it again (without needing to change anything)

Hope this helps.

sgmoore
A: 

hi sgmoore,

i have tried your solution but does not creates the logfile.

on the global.asax file i have put on the next:

    log4net.Config.XmlConfigurator.ConfigureAndWatch(new System.IO.FileInfo(AppDomain.CurrentDomain.SetupInformation.ApplicationBase 
                                                            + "log4net.config"));

and the codebehind, when i use the log, looks like this:

log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
log4net.GlobalContext.Properties["LogName"] = sito + "_Truck_Log_" +DateTime.Today.ToString("dd-MM-yyyy")+".txt";

thx in advance!!!