c# – 使用Log4net实现彩色日志

现在我收到错误“无法在应用程序的.config文件中找到配置部分’log4net’”.这是我在log4net.config文件中的代码:

<?xml version="1.0" encoding="utf-8" ?>
<log4net>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />
</configSections>
<root>
<level Value="Info"/>
<level Value="Error"/>
<appender-ref ref="ColoredFileAppender" />
</root>

<appender name="ColoredFileAppender" type="log4net.Appender.RollingFileAppender" >
<file type="log4net.Util.PatternString"/>
<file value="C:\CL2.html" />
<encoding value="utf-8" />
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<appendToFile value="false" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%CC" />
<converter>
<name value="CC" />
<type value="Cluster2.ColoredMessageConverter" />
</converter>
<mapping>
<level value="Info" />
<foreColor value="Green" />
</mapping>
<mapping>
<level value="ERROR" />
<backColor value="Red, HighIntensity" />
</mapping>
</layout>
</appender>
</configuration>
</log4net>

我在汇编中包含了这个声明:

[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]

我在我的程序中包含了这个声明:

protected void Application_start(Object Sender, EventArgs e)
{
    log4net.Config.XmlConfigurator.Configure();
}

我不知道是什么问题.请帮忙.

解决方法:

您必须使用自定义模式布局来实现此目的,然后将其连接到log4net.config文件中.
您的代码如下所示:

public class ColoredMessageConverter : PatternLayoutConverter
{

    protected override void Convert(TextWriter writer, LoggingEvent loggingEvent)
    {
        string color = "";
        switch (loggingEvent.Level.Name)
        {
            case "DEBUG":
                color = "green";
                break;
            case "WARN":
            case "INFO":
                color = "white";
                break;
            case "ERROR":
                color = "pink";
                break;
            case "FATAL":
                color = "red";
                break;
        }
        string logToRender = string.Format(" <p style='color:{0}'>{1}</p>", color, loggingEvent.RenderedMessage);
        //Add logToRender to file

        writer.Write(logToRender);
    }
}

在您的log4net.config中,按照下面的说明连接此转换器.用正确的名称替换“您的命名空间”.

<log4net>
<root>
  <level value="DEBUG" />
  <appender-ref ref="ColoredFileAppender" />
</root>
<appender name="ColoredFileAppender" type="log4net.Appender.RollingFileAppender" >
  <file type="log4net.Util.PatternString" value="c:\test.html" />
  <layout type="log4net.Layout.PatternLayout">
    <conversionPattern value="%CC" />
    <converter>
      <name value="CC" />
      <type value="<<Your namespace>>.ColoredMessageConverter" />
    </converter>
  </layout>
</appender>
上一篇:c# – 记录Windows服务


下一篇:c# – 如何在发生异常时堆叠日志消息并记录它们?