Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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();
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...