有log4net的RollingFileAppender进行设置滚每周log4net、RollingFileAppender

2023-09-04 00:48:31 作者:安好ヾ勿念

在DatePattern字符串需要的东西的SimpleDateFormatter 将接受。

不幸的是,这意味着,开箱,这不包括能够设置边界是一个星期数。有获得在C#中这个值的方法,但不是很明显,我们可以扩展SimpleDateFormatter或提供不同的实现IDateFormatter并使用它(甚至在自定义RollingFileAppender进行)的。

那么,如何可能我们得到了一个log4net的RollingFileAppender进行滚动每周?

解决方案

我有我每周滚动。您必须设置您的日期格式,包括该月的一天,生成唯一的文件名。

 类RollingOverWeekFileAppender:RollingFileAppender进行
{
    私营的DateTime nextWeekendDate;

    公共RollingOverWeekFileAppender()
    {
        CalcNextWeekend(DateTime.Now);
    }

    私人无效CalcNextWeekend(DateTime的时间)
    {
        //计算器下周日
        时间= time.AddMilliseconds((双)-time.Millisecond);
        时间= time.AddSeconds((双)-time.Second);
        时间= time.AddMinutes((双)-time.Minute);
        时间= time.AddHours((双)-time.Hour);
        nextWeekendDate = time.AddDays((双)(7  - (INT)time.DayOfWeek));
    }

    保护覆盖无效AdjustFileBeforeAppend()
    {
        现在的DateTime = DateTime.Now;

        如果(现> = nextWeekendDate)
        {
            CalcNextWeekend(现在的);
            //当你包括日期和月份AdjustFileBeforeAppend以创照顾
            //以新名称新文件
            base.AdjustFileBeforeAppend();
        }
    }
}
 

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

log4j2的使用

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?

解决方案

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