不知道这里发生了什么,但是除非每次调用我都调用XmlConfigurator.Configure(),否则我的日志记录代码将不会写入rollingFileAppender.我已经在以下代码中打开了调试功能,并且可以确认在构造函数中仅一次调用Configure时,它确实似乎在我的配置中被拉出,但是当实际调用Log()时,日志文件没有任何反应或显示在调试窗口中.
如果我取消对Log()中对Configure()的调用的注释,并让它在每次调用时都重新配置,那么它就可以正常工作,但是我认为这不是预期的用法.
奖励积分! -我注意到对log.Info()的第一次调用未记录日志,但是在该过程的每次运行中所有后续调用都很好.
谢谢!
public static class LogToFile
{
public const string RollingFileAppenderName = "RollingFileLogger";
static LogToFile()
{
log4net.Config.XmlConfigurator.Configure();
}
public static void Log(string fileNameBase, string message, string context)
{
if (fileNameBase == null) throw new ArgumentNullException("fileNameBase");
if (message == null) throw new ArgumentNullException("message");
if (context == null) throw new ArgumentNullException("context");
//log4net.Config.XmlConfigurator.Configure();
string fileName = string.Format("{0}_{1}.log", fileNameBase, context);
string fullFileName = Path.Combine(Properties.Settings.Default.LogFilePath, fileName);
if (!Directory.Exists(Properties.Settings.Default.LogFilePath)) Directory.CreateDirectory(Properties.Settings.Default.LogFilePath);
LogicalThreadContext.Properties["LogName"] = string.Format(fullFileName);
ILog log = LogManager.GetLogger(RollingFileAppenderName);
log.Info(message);
}
}
<appender name="rollingFileAppender" type="log4net.Appender.RollingFileAppender">
<file type="log4net.Util.PatternString" value="%property{LogName}" />
<appendToFile value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="2MB" />
<countDirection value="-1"/>
<LockingModel value="log4net.Appender.FileAppender+MinimalLock"/>
<staticLogFileName value="false" />
<immediateFlush value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="AlertMessageHandler Message : %-25date [%thread] - %newline%message%newline" />
</layout>
</appender>
解决方法:
您的配置文件说日志文件名设置为使用您在运行时更改的LogName属性.我一直以为,如果不重新初始化附加程序(通过调用ActivateOptions)或调用XmlConfigurator.Configure()会更容易,但这样做会做很多很多,那么在运行时不允许更改附加程序的属性.
同样在您的日志方法中,如果您在设置LogName之前调用XmlConfigurator.Configure(),那么我怀疑您的第一个调用将失败(尝试写入null),而第二个调用将写入应该与之一起使用的文件.第一次电话.
如果在设置LogName之后将XmlConfigurator.Configure()移至,则它应该可以正常工作.