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
460 views
in Technique[技术] by (71.8m points)

c# - Have a Log4Net RollingFileAppender set to roll weekly

The DatePattern string needs to be something that the SimpleDateFormatter will accept.

Unfortunately this means that, out of the box, this doesn't include being able to set the boundary to be a week number. There are ways of getting this value in C#, but it's not obvious that we can extend the SimpleDateFormatter or provide a different implementation of IDateFormatter and use that instead (or even in a custom RollingFileAppender).

So how might we get a Log4Net RollingFileAppender to roll weekly?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

I got mine rolling every week. You must set your dateformat to include the day of the month to generate unique filenames.

class RollingOverWeekFileAppender : RollingFileAppender
{
    private DateTime nextWeekendDate;

    public RollingOverWeekFileAppender()
    {
        CalcNextWeekend(DateTime.Now);
    }

    private void CalcNextWeekend(DateTime time)
    { 
        // Calc next sunday
        time = time.AddMilliseconds((double)-time.Millisecond);
        time = time.AddSeconds((double)-time.Second);
        time = time.AddMinutes((double)-time.Minute);
        time = time.AddHours((double)-time.Hour);
        nextWeekendDate = time.AddDays((double)(7 - (int)time.DayOfWeek));
    }

    protected override void AdjustFileBeforeAppend()
    {
        DateTime now = DateTime.Now;

        if (now >= nextWeekendDate)
        {
            CalcNextWeekend(now);
            // As you included the day and month AdjustFileBeforeAppend takes care of creating 
            // new file with the new name
            base.AdjustFileBeforeAppend();
        }
    }
}

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

...