log4net 到 class 库

log4net to a class library

我有一个附加到 Internet Explorer 的 class 库项目(Explorer 的附加组件),我想用 log4net 记录这个 class 库,我添加了一个 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:\IExtonsionsTests\bin\Debug\ClassLibrary.dll.config");
log4net.Config.XmlConfigurator.Configure(fi);

But it doesn't write log file, what am I missing?

请确保您的文件值正确且路径确实存在。你错过了最重要的东西,记录器。只需在您的 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");
    }
}