是否可以仅在滚动文件的顶部包含标题信息?
我有以下配置文件:
<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender"> <file value="d:\temp\TTTest.log"/> <layout type="log4net.Layout.PatternLayout"> <header value="[Header] " /> <param name="ConversionPattern" value="%-25utcdate{dd/MM/yyyy HH:mm:ss.fff}%-20property{log4net:HostName}%-30logger%-30thread%-7level%message%newline"/> </layout> <lockingModel type="log4net.Appender.FileAppender+MinimalLock"/> <maximumFileSize value="5MB"/> <rollingStyle value="Size"/> <maxSizeRollBackups value="-1"/> <countDirection value="1"/> </appender>
当我运行我的应用程序时,例如两次我得到两次标题信息,例如
[Header] The Log line [Header] The Log line etc
我希望实现以下目标:
[Header] The Log line The Log line etc
解决方法
我发现这样做最简单的方法是创建一个继承自RollingFileAppender的类,并像这样覆盖WriteHeader方法:
using System.IO; using System.Text; using log4net.Core; using log4net.Layout; using log4net.Util; using log4net.Appender; namespace CsvLogging { public class HeaderOnceAppender : RollingFileAppender { protected override void WriteHeader() { if (LockingModel.AcquireLock().Length == 0) { base.WriteHeader(); } } } }
然后使用此类作为appender:
<appender name="CsvFileAppender" type="CsvLogging.HeaderOnceAppender">