8

感谢这里的一位用户,我最近遇到了 log4net。无论如何,我想将每个 Console.Write() 和 Debug.Write() 自动记录到我配置的单个日志文件中。此外,我使用许多类库,它们也有对 log4net 一无所知的控制台/调试语句。这些也可以根据配置自动记录到日志文件吗?这有可能吗?

我想在滚动日志文件中记录的内容:

Console.WriteLine("console statement");
Debug.WriteLine("debug statement");

实例化记录器:

private static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private static void InitializeLogger()
{
    XmlConfigurator.Configure();
}

整个 app.config:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
  </configSections>

  <log4net>
    <appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender">
      <param name="File" value="SubToolsPortServerTest.log"/>
      <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
      <appendToFile value="true" />
      <rollingStyle value="Size" />
      <maxSizeRollBackups value="2" />
      <maximumFileSize value="1MB" />
      <staticLogFileName value="true" />
      <layout type="log4net.Layout.PatternLayout">
        <param name="ConversionPattern" value="%d [%t] %-5p %c %m%n"/>
      </layout>
    </appender>

    <root>
      <level value="ALL" />
      <appender-ref ref="LogFileAppender" />
    </root>
  </log4net>
</configuration>
4

1 回答 1

8

You can redirect Debug.WriteLine (in debug builds) and Trace.WriteLine to log4net by writing a custom TraceListener that logs to log4net. The salient bits of a simplistic implementation will look something like:

public class Log4NetTraceListener : TraceListener
{
    ILog _logger = ...;

    public override void WriteLine(string message)
    {
        _logger.Info(message);
    }
}

You would then configure this in your application configuration file something like:

<system.diagnostics>
  ...
    <listeners>
      <add name="traceListener" type="MyNamespace.Log4NetTraceListener,MyAssembly" />
    </listeners>
   ...
</system.diagnostics>

A more complete implementation might support configuration of the logger name, the logging level to use, and perhaps some internal buffering of messages.

For Console.WriteLine you could redirect to your own custom TextWriter by calling Console.SetOut, and your custom TextWriter could log to log4net.

于 2013-05-30T15:33:57.420 回答