Have a Log4Net RollingFileAppender set to roll weekly

前端 未结 3 1838
感动是毒
感动是毒 2020-12-11 07:23

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

Unfortunately this means that, out of the box, this

3条回答
  •  温柔的废话
    2020-12-11 07:36

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

提交回复
热议问题