我有一个类库项目附加到internet explorer(explorer的附加组件(,我想用log4net
记录这个类库,我向项目添加了一个App.config
文件:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="log4net.Config" value="log4net.config"/>
<add key="log4net.Config.Watch" value="True"/>
</appSettings>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
<log4net>
<appender name="RollingFileAppenderSize" type="log4net.Appender.RollingFileAppender">
<file value="FromLog4netLon.log" />
<appendToFile value="true" />
<rollingStyle value="Size" />
<encoding value="utf-8" />
<maximumFileSize value="10MB" />
<maxSizeRollBackups value="5" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date{ABSOLUTE} [%logger] %level - %message%newline%exception" />
</layout>
</appender>
<root>
<level value="FATAL" />
<level value="WARN" />
<level value="INFO" />
<level value="DEBUG" />
<appender-ref ref="RollingFileAppenderSize" />
</root>
</log4net>
</configuration>
在AssemblysInfo.cs
下,我添加了[assembly: log4net.Config.XmlConfigurator(Watch = true)]
在我的项目中,我添加了
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
我试着这样写:
log.Info("test log");
我也试着添加这个:
FileInfo fi = new FileInfo(@"D:IExtonsionsTests1binDebugClassLibrary.dll.config");
log4net.Config.XmlConfigurator.Configure(fi);
但它不写日志文件,我缺少什么?
确保文件值正确且路径确实存在。你错过了最重要的东西,记录器。只需在您的appender后面插入以下代码:
(如果您想添加多个记录器,可以添加多个(
<logger name="STANDART" additivity="false">
<level value="ALL"/>
<appender-ref ref="RollingFileAppenderSize"/>
</logger>
您的代码应该如下所示:
public enum LoggerTypes
{
STANDART = 0
}
public class Logger1
{
private static readonly string _loggerConfigDic = "..\..\YOURFOLDER\YOURFILENAME.xml";
private static readonly List<string> _names = new List<string> { "STANDART" }; /*Logger names in config file*/
public static ILog GetLogger(LoggerTypes loggerType)
{
var fileInfo = new FileInfo(_loggerConfigDic);
XmlConfigurator.ConfigureAndWatch(fileInfo);
return LogManager.GetLogger(_names[(int)loggerType]);
}
}
public class myClass
{
public void SomeMethod()
{
var logger = Logger1.GetLogger(LoggerTypes.STANDART);
logger.Debug("your message here");
}
}