Log4net XML config configuration

I have a requirement to store my log files in the Logs subdirectory. You usually do this by changing the FileAppender in your App.config like this:

<file type="log4net.Util.PatternString" value="Logs\MyLog.log" />

      

However, this is not cross platform because if you run this on linux it will create a file called "Logs \ MyLog.log" rather than a directory. This is because '\' is not a path separator in linux.

We can change it to '/', but this will only work on Linux, not windows.

How can you use the XML configuration for log4net to put my logs in a subfolder that works cross platform?

+3


source to share


2 answers


A possible solution might be that you are configuring the file for windows rather than after testing the configuration if you are on Linux. When on Linux you can get the application and change the value of the file => value with replacement for Linux compatibility:



XmlConfigurator.Configure();
if (Environment.OSVersion.Platform == PlatformID.Unix){
        var repository = LogManager.GetRepository() as Hierarchy;
        if (repository != null)
        {
            var appenders = repository.GetAppenders();
            if (appenders != null)
            {
                foreach (var appender in appenders)
                {
                    if (appender is FileAppender)
                    {
                        var fileLogAppender = appender as FileAppender;
                        fileLogAppender.File = fileLogAppender.File.Replace (@"\", Path.DirectorySeparatorChar.ToString ());
                        fileLogAppender.ActivateOptions ();
                    }
                }
            }
        }
}

      

+1


source


Another solution would be to use it like this:



<file type="log4net.Util.PatternString" value=".//Logs//MyLog.log" />

+1


source







All Articles