Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
261 views
in Technique[技术] by (71.8m points)

c# - Having a log per day

Currently my application is using log4net to log errors, the web.config for this is as followed:

<log4net> 
    <appender name="FileAppender" type="log4net.Appender.FileAppender">
        <file value="c:/paypal/logs/gateway.log" />
        <appendToFile value="true" />
        <layout type="log4net.Layout.PatternLayout">
            <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] – %message%newline" />
        </layout>
    </appender>
    <root>
        <level value="DEBUG" />
        <appender-ref ref="FileAppender" />
    </root>
</log4net>

However, the problem with this is that everyday the logs always go to gateway.log

Does anybody know a way to have a different log file per day using log4net?

Ideally I don't want to have to manually edit the web.config every night using a scheduled task.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You should use RollingFileAppender with rollingStyle Date and datePattern yyyyMMdd (this will roll every day).

Example of configuration:

<appender name="FileAppender" type="log4net.Appender.RollingFileAppender">
    <file value="c:/paypal/logs/gateway.log" />
    <appendToFile value="true" />
    <rollingStyle value="Date" />
    <datePattern value="yyyyMMdd" />
    <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] – %message%newline" />
    </layout>
</appender>

UPDATE: I think a better way is to include the date into file name. And use datePattern value only to show when new log file should be created.

<appender name="FileAppender" type="log4net.Appender.RollingFileAppender">
  <file type="log4net.Util.PatternString" value="c:/paypal/logs/gateway_%date{yyyyMMdd}.log" />
  <appendToFile value="true" />
  <rollingStyle value="Date" />
  <datePattern value="yyyyMMdd" />
  <layout type="log4net.Layout.PatternLayout">
    <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] – %message%newline" />
  </layout>
</appender>

In this case all your files will have name like gateway_20120427.log.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...