Reputation: 726
I'm using log4net in a WPF application. log4net works when running the application from Visual Studio, however, it's not working when we run the application via the executable from bin
.
We're using a log4net.config
file, here's what it looks like:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<log4net debug="true">
<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
<param name="File" value="C:/ProgramData/CompApps/Logs/AppName/log.txt" />
<appendToFile value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="25" />
<maximumFileSize value="20MB" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%utcdate UTC %property{log4net:HostName} [%thread] %-5level %logger - %method() - %message%newline" />
</layout>
</appender>
<root>
<level value="Info" />
<appender-ref ref="RollingFileAppender" />
</root>
</log4net>
</configuration>
log4net.config
properties
Build Action: Content
Copy to Output Directory: Copy always
AssemblyInfo.cs
:
// log4net config
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]
And this is used in each class we want to use the logger:
private static readonly ILog log = LogManager.GetLogger(typeof(App));
Upvotes: 2
Views: 2140
Reputation: 1424
Another approach for configuration in code:
namespace Company.Product
{
using System.Text;
using log4net;
using log4net.Appender;
using log4net.Core;
using log4net.Layout;
using log4net.Repository.Hierarchy;
public static class LogHelper
{
static LogHelper()
{
var hierarchy = (Hierarchy)LogManager.GetRepository();
hierarchy.Root.Level = Level.All;
hierarchy.Configured = true;
}
public static ILog GetLoggerRollingFileAppender(string logName, string fileName)
{
var log = LogManager.Exists(logName);
if (log != null) return log;
var appenderName = $"{logName}Appender";
log = LogManager.GetLogger(logName);
((Logger)log.Logger).AddAppender(GetRollingFileAppender(appenderName, fileName));
return log;
}
public static RollingFileAppender GetRollingFileAppender(string appenderName, string fileName)
{
var layout = new PatternLayout { ConversionPattern = "%date{dd.MM.yyyy HH:mm:ss.fff} [%-5level] %message%newline" };
layout.ActivateOptions();
var appender = new RollingFileAppender
{
Name = appenderName,
File = fileName,
AppendToFile = true,
RollingStyle = RollingFileAppender.RollingMode.Size,
MaxSizeRollBackups = 2,
MaximumFileSize = "500KB",
Layout = layout,
ImmediateFlush = true,
LockingModel = new FileAppender.MinimalLock(),
Encoding = Encoding.UTF8,
};
appender.ActivateOptions();
return appender;
}
}
}
Usage for your case:
private static readonly ILog log = LogHelper.GetLoggerRollingFileAppender(typeof(App), "C:/ProgramData/CompApps/Logs/AppName/log.txt");
Or reference log file full path from your application config file.
Upvotes: 1