在每次应用程序启动的代码滚动中配置log4net RollingFileAppender一次

本文关键字:配置 log4net RollingFileAppender 一次 滚动 代码 应用程序 启动 | 更新日期: 2024-09-21 16:52:10

我想创建一个log4net RollingFileAppender,每次程序启动时都会创建一个新文件。如果文件变大,它可以滚动,但每次启动应用程序时都必须滚动。如果在配置中配置了另一个appender,则不应添加appender。本质上是创建一个默认的日志配置,该配置可以通过更改配置文件来覆盖。

在每次应用程序启动的代码滚动中配置log4net RollingFileAppender一次

在拼凑了许多其他帖子后,我终于完成了这项工作。实现在一个静态包装类中。你所要做的就是将这些代码粘贴到你的应用程序中,设置创建文件的位置,并在应用程序启动时调用Log.Configure()。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using System.Windows.Threading;
using log4net;
using log4net.Core;
using log4net.Appender;
using log4net.Repository.Hierarchy;
using System.Reflection;
using System.IO;
namespace [Your Namespace]
{
    public static class Log
    {
        private static bool isConfigured = false;
        private static ILog iLog;
        public static void Configure()
        {
            if (isConfigured)
                return;
            var loggerName = typeof(DiagnosticsManager).FullName;
            var logger = (log4net.Repository.Hierarchy.Logger)log4net.LogManager.GetRepository().GetLogger(loggerName);
            var ilogger = log4net.LogManager.GetRepository().GetLogger(loggerName);
            //Add the default log appender if none exist
            if(logger.Appenders.Count == 0)
            {
                var directoryName = "[Your directory name here. e.c. 'C:'ProgramData'AppName'Logs']";
                //If the directory doesn't exist then create it
                if(!Directory.Exists(directoryName))
                    Directory.CreateDirectory(directoryName);
                var fileName = Path.Combine(directoryName, "[Your static file name here. e.c. 'AppName.log']");
                //Create the rolling file appender
                var appender = new log4net.Appender.RollingFileAppender();
                appender.Name = "RollingFileAppender";
                appender.File = fileName;
                appender.StaticLogFileName = true;
                appender.AppendToFile = false;
                appender.RollingStyle = log4net.Appender.RollingFileAppender.RollingMode.Size;
                appender.MaxSizeRollBackups = 10;
                appender.MaximumFileSize = "10MB";
                appender.PreserveLogFileNameExtension = true;
                //Configure the layout of the trace message write
                var layout = new log4net.Layout.PatternLayout()
                {
                    ConversionPattern = "%date{hh:mm:ss.fff} [%thread] %-5level - %message%newline"
                };
                appender.Layout = layout;
                layout.ActivateOptions();
                //Let log4net configure itself based on the values provided
                appender.ActivateOptions();
                log4net.Config.BasicConfigurator.Configure(appender);
            }
            iLog = LogManager.GetLogger(loggerName);
            isConfigured = true;
            Info("Logging Configured at " + DateTime.Now.ToString("g"));
        }
        public static event EventHandler<ExceptionLoggedEventArgs> ExceptionLogged;
        public static void Debug(object message) { Configure(); iLog.Debug(message); }
        public static void Debug(object message, Exception exception) { Configure(); iLog.Debug(message, exception); }
        public static void Error(object message) { Configure(); iLog.Error(message); }
        public static void Error(object message, Exception exception) { Configure(); iLog.Error(message, exception); }
        public static void Fatal(object message) { Configure(); iLog.Fatal(message); }
        public static void Fatal(object message, Exception exception) { Configure(); iLog.Fatal(message, exception); }
        public static void Info(object message) { Configure(); iLog.Info(message); }
        public static void Info(object message, Exception exception) { Configure(); iLog.Info(message, exception); }
        public static void Warn(object message) { Configure(); iLog.Warn(message); }
        public static void Warn(object message, Exception exception) { Configure(); iLog.Warn(message, exception); }
    }
}