【问题标题】:Log4net xml outputLog4net xml 输出
【发布时间】:2009-07-18 09:35:06
【问题描述】:

我想要完全控制 log4net xml 输出。

如何自定义输出模板?

【问题讨论】:

    标签: xml log4net


    【解决方案1】:

    作为 MrPeregrination 的 suggested,您需要编写一个派生自 XmlLayoutBase 的类,覆盖 FormatXml 方法并指示您的附加程序将其用作布局:

    class Program
    {
        static void Main(string[] args)
        {
            XmlConfigurator.Configure();
            ILog log = log4net.LogManager.GetLogger(typeof(Program));
            log.Debug("Hello world");
        }
    }
    
    public class MyXmlLayout : XmlLayoutBase
    {
        protected override void FormatXml(XmlWriter writer, LoggingEvent loggingEvent)
        {
            writer.WriteStartElement("LogEntry");
            writer.WriteStartElement("Message");
            writer.WriteString(loggingEvent.RenderedMessage);
            writer.WriteEndElement();
            writer.WriteEndElement();
        }
    }
    

    在 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="log.txt" />
          <param name="AppendToFile" value="true" />
          <rollingStyle value="Size" />
          <maxSizeRollBackups value="10" />
          <maximumFileSize value="10MB" />
          <staticLogFileName value="true" />
          <layout type="MyNamespace.MyXmlLayout" />
        </appender>
    
        <root>
          <level value="DEBUG" />
          <appender-ref ref="LogFileAppender" />
        </root>
      </log4net>
    </configuration>
    

    这将在您的日志文件中生成如下条目:

    <LogEntry><Message>Hello world</Message></LogEntry>
    

    【讨论】:

    • Darin,非常感谢,终于明白这一点,但你能告诉我,我是否需要在我的应用程序类库中拥有这个自定义布局库,在它自己的类库中,还是在 log4net 类库中(重新编译)?
    • 你可以在它自己的类库或你的应用程序类库中拥有这个类。如果您在自己的类库中有它,则需要指定包含它的程序集的名称:
    • 好的,一劳永逸地解决了……原来我不需要指定命名空间……谢谢!
    • 默认情况下如何在输出中开始结束标签:如 ...... ? ?
    【解决方案2】:

    添加到 Darin 的回答中,在 log4net 2.0.8 中,我不得不稍微更改布局:

    <layout type="MyNamespace.MyClass, MyNamespace"/>
    

    我在这里找到了这个http://www.codewrecks.com/blog/index.php/2008/04/29/writing-a-custom-formatter-for-log4net/

    【讨论】:

      【解决方案3】:

      查看 XmlLayoutBase 类。我想这可能是你需要的。您需要重写一个 FormatXML 函数,以便为 XmlWriter 提供格式正确的数据。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-06-10
        • 1970-01-01
        相关资源
        最近更新 更多