Change log4net config to create every x hour new log

ぃ、小莉子 提交于 2019-12-12 11:23:05

问题


I still dont really get it how to change log4net if I would like to have every x hour a log. I have this:

      <log4net>
        <root>
          <level value="DEBUG"/>
          <appender-ref ref="LogFileAppender"/>
        </root>
        <appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender">
          <param name="File" value="C:\log.txt"/>
          <param name="AppendToFile" value="true"/>
          <rollingStyle value="Size"/>
          <maxSizeRollBackups value="10"/>
          <maximumFileSize value="100MB"/>
          <staticLogFileName value="true"/>
          <layout type="log4net.Layout.PatternLayout">
            <param name="ConversionPattern" value="%-5p%d{yyyy-MM-dd hh:mm:ss} – %m%n"/>
          </layout>
        </appender>
  </log4net>

I have one log and Im adding the logs always in this one log.txt - now I would like to have lets say for every day a new log file (24hours) or maybe for every 12hours a new log. What do I have to change in my config? Any suggestions to my config? Thank you


回答1:


RE: http://logging.apache.org/log4net/release/config-examples.html

This example shows how to configure the RollingFileAppender to roll log files on a date period. This example will roll the log file every minute! To change the rolling period adjust the DatePattern value. For example, a date pattern of "yyyyMMdd" will roll every day. See System.Globalization.DateTimeFormatInfo for a list of available patterns.

<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="logfile" />
<appendToFile value="true" />
<rollingStyle value="Date" />
<datePattern value="yyyyMMdd-HHmm" />
<layout type="log4net.Layout.PatternLayout">
    <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
</layout>

In your particular case, the above example with <datePattern value="yyyyMMdd-HH" /> would only allow you to log every hour.

However, if you wanted to log every X hour, you could create a custom appender derived from RollingFileAppender and override the AdjustFileBeforeAppend method that would check the current time against your next scheduled log interval date. See Have a Log4Net RollingFileAppender set to roll weekly for example.




回答2:


Replace your rolling style as follows:

<rollingStyle value="Date" />

You'll probably also want to remove the file size limitation.



来源:https://stackoverflow.com/questions/12100624/change-log4net-config-to-create-every-x-hour-new-log

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!