示例#1
0
        // Create a new file appender
        public static RollingFileAppender CreateFileAppender(LoggerConfigurationElement element)
        {
            var appender = new RollingFileAppender();
            appender.Name = element.LoggerName;
            appender.File = element.Filename;
            appender.AppendToFile = true;
            appender.RollingStyle = RollingFileAppender.RollingMode.Composite;
            appender.MaximumFileSize = element.MaximumFileSize;
            appender.MaxSizeRollBackups = element.MaxSizeRollBackups;
            appender.PreserveLogFileNameExtension = element.PreserveLogFileNameExtension;
            appender.DatePattern = element.DatePattern;

            var layout = new PatternLayout();
            layout.ConversionPattern = "%message";
            layout.ActivateOptions();

            var filter = new LoggerMatchFilter();
            filter.LoggerToMatch = element.LoggerName;
            filter.ActivateOptions();

            var denyAllFilter = new DenyAllFilter();
            denyAllFilter.ActivateOptions();

            appender.AddFilter(filter);
            appender.AddFilter(denyAllFilter);

            appender.Layout = layout;
            appender.ActivateOptions();

            return appender;
        }
示例#2
0
 /// <summary>
 /// 初始化一个<see cref="Log4NetLoggerAdapter"/>类型的新实例
 /// </summary>
 public Log4NetLoggerAdapter()
 {
     const string fileName = "log4net.config";
     string configFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, fileName);
     if (File.Exists(configFile))
     {
         XmlConfigurator.ConfigureAndWatch(new FileInfo(configFile));
         return;
     }
     RollingFileAppender appender = new RollingFileAppender
     {
         Name = "root",
         File = "logs\\log_",
         AppendToFile = true,
         LockingModel = new FileAppender.MinimalLock(),
         RollingStyle = RollingFileAppender.RollingMode.Date,
         DatePattern = "yyyyMMdd-HH\".log\"",
         StaticLogFileName = false,
         MaxSizeRollBackups = 10,
         Layout = new PatternLayout("[%d{yyyy-MM-dd HH:mm:ss.fff}] %-5p %c.%M %t %w %n%m%n")
         //Layout = new PatternLayout("[%d [%t] %-5p %c [%x] - %m%n]")
     };
     appender.ClearFilters();
     appender.AddFilter(new LevelMatchFilter { LevelToMatch = Level.Info });
     //PatternLayout layout = new PatternLayout("[%d{yyyy-MM-dd HH:mm:ss.fff}] %c.%M %t %n%m%n");
     //appender.Layout = layout;
     BasicConfigurator.Configure(appender);
     appender.ActivateOptions();
 }
示例#3
0
        /// <summary>
        /// configure method
        /// </summary>
        /// <param name="key">key</param>
        /// <param name="repository">repository</param>
        public override void Configure(string key, ILoggerRepository repository)
        {
            var path = Path.Replace(":", "_");

            foreach (var level in Levels)
            {
                var appender = new log4net.Appender.RollingFileAppender();
                appender.File           = Folder + (string.IsNullOrEmpty(path) ? "" : path) + "/" + level.ToString().ToLower() + ".log";
                appender.AppendToFile   = true;
                appender.ImmediateFlush = true;
                appender.LockingModel   = new FileAppender.MinimalLock();
                appender.Threshold      = level;

                var layout = new PatternLayout(Pattern);
                layout.ActivateOptions();

                appender.Layout = layout;
                appender.Name   = key + "_" + level.ToString().ToLower();

                var filter = new LevelRangeFilter();
                filter.LevelMax = level;
                filter.LevelMin = level;
                filter.ActivateOptions();
                appender.AddFilter(filter);

                appender.ActivateOptions();

                BasicConfigurator.Configure(repository, appender);
            }
        }
    public Logging(string sFileName, string sLocation, bool bUseLogging)
    {
        m_sFileName = sFileName;
        if (!bUseLogging) return;

        if (sLocation.Length > 0)
            if (sLocation[sLocation.Length - 1] != '\\')
                sLocation += "\\";

        m_RFL = new log4net.Appender.RollingFileAppender();
        m_RFL.File = sLocation + m_sFileName + m_sFileExt;
        m_RFL.StaticLogFileName = true;
        m_RFL.AppendToFile = true;
        m_RFL.RollingStyle = log4net.Appender.RollingFileAppender.RollingMode.Size;
        m_RFL.MaximumFileSize = "10mb";
        m_RFL.MaxSizeRollBackups = 2;
        m_RFL.Threshold = log4net.Core.Level.All;

        //m_RFL.CountDirection = 1;
        //m_RFL.DatePattern = "HH:MM::SS"; 
        log4net.Layout.PatternLayout layout = new log4net.Layout.PatternLayout("%message%newline");
        layout.ActivateOptions();
        log4net.Filter.LevelRangeFilter filter = new log4net.Filter.LevelRangeFilter();
        filter.LevelMax = log4net.Core.Level.Emergency;
        filter.LevelMin = log4net.Core.Level.All;
        m_RFL.AddFilter(filter);
        m_RFL.Layout = layout;
        m_RFL.ActivateOptions();

        log4net.Config.BasicConfigurator.Configure(m_RFL);

        // Set up
        Log(Logging.LOGTYPE.ERROR, "Start logging...");

    }
示例#5
0
        /// <summary>
        /// 初始化一个<see cref="Log4NetAdapter"/>类型的新实例
        /// </summary>k
        public Log4NetAdapter()
        {
//            var configFile = Path.Combine(ConfigPath, FileName);
//            if (File.Exists(configFile))
//            {
//                XmlConfigurator.ConfigureAndWatch(new FileInfo(configFile));
//                return;
//            }
            var appender = new RollingFileAppender
            {
                Name = "root",
                File = "logs\\log_",
                AppendToFile = true,
                LockingModel = new FileAppender.MinimalLock(),
                RollingStyle = RollingFileAppender.RollingMode.Date,
                DatePattern = "yyyyMMdd-HH\".log\"",
                StaticLogFileName = false,
                MaxSizeRollBackups = 10,
                Layout = new PatternLayout("[%d{yyyy-MM-dd HH:mm:ss.fff}] %-5p %c %t %w %n%m%n")
                //Layout = new PatternLayout("[%d [%t] %-5p %c [%x] - %m%n]")
            };
            appender.ClearFilters();
            appender.AddFilter(new LevelRangeFilter
            {
                LevelMin = Level.Debug,
                LevelMax = Level.Fatal
            });
            BasicConfigurator.Configure(appender);
            appender.ActivateOptions();
        }
示例#6
0
 private AqiRemind()
 {
     RollingFileAppender appender = new RollingFileAppender();
     appender.File = this.getLogFile();
     appender.AppendToFile = true;
     appender.RollingStyle = RollingFileAppender.RollingMode.Date;
     appender.StaticLogFileName = true;
     appender.Layout = new PatternLayout(AqiManage.Setting["AqiRemind.LogLayout"]);
     LevelRangeFilter filter = new LevelRangeFilter();
     filter.LevelMax = Level.Fatal;
     filter.LevelMin = Level.Debug;
     appender.AddFilter(filter);
     appender.ActivateOptions();
     BasicConfigurator.Configure(appender);
     this.log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
 }
 public Log4NetLoggerAdapter()
 {
     var appender = new RollingFileAppender
     {
         Name = "root",
         File = "logs\\log4net.log",
         AppendToFile = true,
         LockingModel = new FileAppender.MinimalLock(),
         RollingStyle = RollingFileAppender.RollingMode.Size,
         StaticLogFileName = false,
         Threshold = Level.Debug,
         MaxSizeRollBackups = 10,
         Layout = new PatternLayout("%n[%d{yyyy-MM-dd HH:mm:ss.fff}] %-5p %c %t %w %n%m%n"),
     };
     appender.ClearFilters();
     appender.AddFilter(new LevelMatchFilter { LevelToMatch = Level.Info });
     BasicConfigurator.Configure(appender);
     appender.ActivateOptions();
 }
 private RollingFileAppender CloneAppender(RollingFileAppender appender)
 {
     var newAppender = new RollingFileAppender();
     newAppender.Name = appender.Name;
     newAppender.RollingStyle = appender.RollingStyle;
     newAppender.StaticLogFileName = appender.StaticLogFileName;
     newAppender.Threshold = appender.Threshold;
     newAppender.MaxSizeRollBackups = appender.MaxSizeRollBackups;
     newAppender.MaximumFileSize = appender.MaximumFileSize;
     newAppender.MaxFileSize = appender.MaxFileSize;
     //newAppender.LockingModel = appender.LockingModel;
     newAppender.Layout = appender.Layout;
     newAppender.ImmediateFlush = appender.ImmediateFlush;
     newAppender.File = appender.File;
     newAppender.ErrorHandler = appender.ErrorHandler;
     newAppender.Encoding = appender.Encoding;
     newAppender.DatePattern = appender.DatePattern;
     newAppender.CountDirection = appender.CountDirection;
     newAppender.AppendToFile = appender.AppendToFile;
     newAppender.AddFilter(appender.FilterHead);
     return newAppender;
 }
示例#9
0
 public ILog GetLogger(LogDomain domain)
 {
     var repository = domain.ToString();
     try
     {
         return LogManager.GetLogger(repository, "default");
     }
     catch
     {
         lock (FileBase.Getlocker(repository))
         {
             try
             {
                 return LogManager.GetLogger(repository, "default");
             }
             catch
             {
                 try
                 {
                     var loggerRepository = LogManager.CreateRepository(repository);
                     var log4NetBaseDirectory = AppConfig.Log4NetBaseDirectory;
                     if (string.IsNullOrEmpty(log4NetBaseDirectory))
                     {
                         log4NetBaseDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory + "/../", "Log4NetBaseDirectory");
                     }
                     foreach (var filter in Filters)
                     {
                         var fileAppender = new RollingFileAppender
                         {
                             Name = domain + "_" + filter.Key + "_FileAppender",
                             LockingModel = new FileAppender.MinimalLock(),
                             File = log4NetBaseDirectory,
                             AppendToFile = true,
                             RollingStyle = RollingFileAppender.RollingMode.Date,
                             DatePattern = "/yyyy-MM-dd'/" + domain + "/'yyyy-MM-dd HH'" + filter.Key + ".log'",
                             StaticLogFileName = false,
                             Layout = Layout
                         };
                         fileAppender.AddFilter(filter.Value);
                         fileAppender.ActivateOptions();
                         BasicConfigurator.Configure(loggerRepository, fileAppender);
                     }
                     return LogManager.GetLogger(repository, "default");
                 }
                 catch
                 {
                     return default(ILog);
                 }
             }
         }
     }
 }
示例#10
0
        public void Config(string[] domains, IZicEmailConfig emailConfig) {
            foreach (string domain in domains) {
                ILoggerRepository repository = LogManager.CreateRepository(domain);

                //FileLog
                foreach (KeyValuePair<string, LevelRangeFilter> Filter in Filters) {
                    RollingFileAppender fileAppender = new RollingFileAppender();
                    fileAppender.Name = domain + "_" + Filter.Key + "_FileAppender";
                    fileAppender.File = "Log_" + domain + "\\" + Filter.Key + "\\";
                    fileAppender.AppendToFile = true;
                    fileAppender.RollingStyle = RollingFileAppender.RollingMode.Date;
                    fileAppender.DatePattern = "yyyy-MM-dd'.log'";
                    fileAppender.StaticLogFileName = false;
                    fileAppender.Layout = ZicLayout;
                    fileAppender.AddFilter(Filter.Value);
                    fileAppender.ActivateOptions();
                    BasicConfigurator.Configure(repository, fileAppender);
                }

                //SmtpLog
                ZicSmtpAppender smtpAppender = new ZicSmtpAppender(emailConfig);
                smtpAppender.Name = domain + "_SmtpAppender";
                smtpAppender.Authentication = ZicSmtpAppender.SmtpAuthentication.Basic;
                smtpAppender.Subject = domain + " logging message";
                //zic:邮件日志与其他日志同级别(甚至更高),所以不允许丢失或缓冲,所以Buffer、lossy、Evaluator全部忽略
                //如果缓冲区溢出在触发事件之前,日志事件可能会丢失。
                //如果log4net.Appender.BufferingAppenderSkeleton.Lossy设置为false防止日志事件被丢失。
                //如果log4net.Appender.BufferingAppenderSkeleton.Lossy设置为true,那么log4net.Appender.BufferingAppenderSkeleton.Evaluator必须被指定。
                //也就是说如果LevelEvaluator设为WARN,则在WARN或之上级别的日志肯定不会丢失,之下级别的日志有可能因为缓冲区溢出而丢失。
                smtpAppender.BufferSize = 0;
                smtpAppender.Lossy = false;
                smtpAppender.Layout = ZicLayout;
                smtpAppender.AddFilter(EmailFilter);
                smtpAppender.ActivateOptions();
                BasicConfigurator.Configure(repository, smtpAppender);
            }
        }
        /// <summary>
        ///   Adds a file appender to all current loggers. Only runs one time.
        /// </summary>
        /// <param name="outputDirectory">The output directory.</param>
        private static void set_file_appender(string outputDirectory)
        {
            if (!_alreadyConfiguredFileAppender)
            {
                _alreadyConfiguredFileAppender = true;

                var layout = new PatternLayout
                    {
                        ConversionPattern = "%date [%-5level] - %message%newline"
                    };
                layout.ActivateOptions();

                var app = new RollingFileAppender
                    {
                        Name = "{0}.changes.log.appender".format_with(ApplicationParameters.Name),
                        File = Path.Combine(Path.GetFullPath(outputDirectory), ApplicationParameters.LoggingFile),
                        Layout = layout,
                        AppendToFile = true,
                        RollingStyle = RollingFileAppender.RollingMode.Size,
                        MaxFileSize = 1024 * 1024,
                        MaxSizeRollBackups = 10,
                        LockingModel = new FileAppender.MinimalLock(),
                    };
                app.ActivateOptions();

                var infoOnlyAppender = new RollingFileAppender
                {
                    Name = _summaryLogAppenderName,
                    File = Path.Combine(Path.GetFullPath(outputDirectory), ApplicationParameters.LoggingSummaryFile),
                    Layout = layout,
                    AppendToFile = true,
                    RollingStyle = RollingFileAppender.RollingMode.Size,
                    MaxFileSize = 1024 * 1024,
                    MaxSizeRollBackups = 10,
                    LockingModel = new FileAppender.MinimalLock(),

                };
                infoOnlyAppender.AddFilter(new LevelRangeFilter { LevelMin = Level.Info, LevelMax = Level.Fatal });
                infoOnlyAppender.ActivateOptions();

                ILoggerRepository logRepository = LogManager.GetRepository(Assembly.GetCallingAssembly().UnderlyingType);
                foreach (ILogger log in logRepository.GetCurrentLoggers())
                {
                    var logger = log as Logger;
                    if (logger != null)
                    {
                        logger.AddAppender(app);
                        logger.AddAppender(infoOnlyAppender);
                    }
                }
            }
        }
示例#12
0
        public static log4net.Appender.IAppender CreateFileAppender(string name, string fileName, string levelName)
        {
            log4net.Appender.RollingFileAppender appender = new
                                                            log4net.Appender.RollingFileAppender();
            appender.Name               = name + Settings._Main.appenderSufix;
            appender.File               = Settings._Main.logFolder + fileName + ".log";
            appender.AppendToFile       = true;
            appender.RollingStyle       = log4net.Appender.RollingFileAppender.RollingMode.Size;
            appender.MaxSizeRollBackups = 5;
            appender.MaximumFileSize    = Settings._Main.masterSize;
            appender.CountDirection     = 1;

            log4net.Layout.PatternLayout layout = new
                                                  log4net.Layout.PatternLayout();
            layout.ConversionPattern = Settings._Main.pattern;
            layout.ActivateOptions();

            log4net.Filter.LevelRangeFilter filter = new log4net.Filter.LevelRangeFilter();
            switch (levelName)
            {
            case "All":
                filter.LevelMin = log4net.Core.Level.All;
                break;

            case "Alert":
                filter.LevelMin = log4net.Core.Level.Alert;
                break;

            case "Debug":
                filter.LevelMin = log4net.Core.Level.Debug;
                break;

            case "Critical":
                filter.LevelMin = log4net.Core.Level.Critical;
                break;

            case "Error":
                filter.LevelMin = log4net.Core.Level.Error;
                break;

            case "Fatal":
                filter.LevelMin = log4net.Core.Level.Fatal;
                break;

            case "Info":
                filter.LevelMin = log4net.Core.Level.Info;
                break;

            case "Warn":
                filter.LevelMin = log4net.Core.Level.Warn;
                break;

            default:
                filter.LevelMin = log4net.Core.Level.All;
                break;
            }



            filter.ActivateOptions();

            appender.Layout = layout;
            appender.AddFilter(filter);

            appender.ActivateOptions();

            return(appender);
        }
示例#13
0
        /// <summary>
        /// Warning: this is not tread-safe, so only call this at startup or at a time that you are sure your
        /// process is not performing any logging!
        /// </summary>
        /// <param name="filePath">The path to the log file.</param>
        /// <param name="sourceLevels">The lowest log level to log.</param>
        public static void SetLogFilePath(string filePath, SourceLevels sourceLevels)
        {
            if (!Path.IsPathRooted(filePath))
            {
                filePath = Path.Combine(ArgusTVLogFolder, filePath);
            }

            Level level = Level.Debug;
            if (_sourceLevels == SourceLevels.Information)
            {
                level = Level.Info;
            }
            else if (_sourceLevels == SourceLevels.Warning)
            {
                level = Level.Warn;
            }
            else if (_sourceLevels == SourceLevels.Error)
            {
                level = Level.Error;
            }
            else if (_sourceLevels == SourceLevels.Critical)
            {
                level = Level.Fatal;
            }
            _sourceLevels = sourceLevels;

            log4Hierarchy.Hierarchy hierarchy =
                (log4Hierarchy.Hierarchy)LogManager.GetAllRepositories().FirstOrDefault(r => r.Name == _argusTV);
            if (hierarchy == null)
            {
                hierarchy = (log4Hierarchy.Hierarchy)LogManager.CreateRepository(_argusTV);
            }
            hierarchy.Root.RemoveAllAppenders();

            RollingFileAppender roller = new RollingFileAppender();
            PatternLayout patternLayout = new PatternLayout();
            patternLayout.ConversionPattern = "%date [%-5level][%thread]: %message%newline";
            patternLayout.ActivateOptions();
            roller.Layout = patternLayout;
            roller.AppendToFile = true;
            roller.RollingStyle = RollingFileAppender.RollingMode.Size;
            roller.MaxSizeRollBackups = 4;
            roller.MaximumFileSize = "1000KB";
            roller.StaticLogFileName = true;
            roller.File = filePath;
            roller.ActivateOptions();
            roller.AddFilter(new log4net.Filter.LevelRangeFilter()
            {
                LevelMin = level,
                LevelMax = Level.Fatal
            });
            log4net.Config.BasicConfigurator.Configure(hierarchy, roller);

            log4Hierarchy.Logger coreLogger = hierarchy.GetLogger(_argusTV) as log4Hierarchy.Logger;
            coreLogger.Level = level;

            _log = LogManager.GetLogger(hierarchy.Name, _argusTV);
        }
示例#14
0
        public static log4net.Appender.IAppender CreateFileAppender(string name, string fileName, string levelName)
        {
            string AppDataPath = T1.Log.Settings._Main.logFolder;


            log4net.Appender.RollingFileAppender appender = new
                                                            log4net.Appender.RollingFileAppender();
            try {
                appender.Name               = name + T1.Log.Settings._Main.appenderSufix;
                appender.File               = AppDataPath + fileName + ".log";
                appender.AppendToFile       = true;
                appender.RollingStyle       = log4net.Appender.RollingFileAppender.RollingMode.Size;
                appender.MaxSizeRollBackups = Settings._Main.numberOfLogs;
                appender.MaximumFileSize    = T1.Log.Settings._Main.masterSize;
                appender.CountDirection     = 1;

                log4net.Layout.PatternLayout layout = new
                                                      log4net.Layout.PatternLayout();
                layout.ConversionPattern = T1.Log.Settings._Main.pattern;
                layout.ActivateOptions();

                log4net.Filter.LevelRangeFilter filter = new log4net.Filter.LevelRangeFilter();
                switch (levelName)
                {
                case "All":
                    filter.LevelMin = log4net.Core.Level.All;
                    break;

                case "Alert":
                    filter.LevelMin = log4net.Core.Level.Alert;
                    break;

                case "Debug":
                    filter.LevelMin = log4net.Core.Level.Debug;
                    break;

                case "Critical":
                    filter.LevelMin = log4net.Core.Level.Critical;
                    break;

                case "Error":
                    filter.LevelMin = log4net.Core.Level.Error;
                    break;

                case "Fatal":
                    filter.LevelMin = log4net.Core.Level.Fatal;
                    break;

                case "Info":
                    filter.LevelMin = log4net.Core.Level.Info;
                    break;

                case "Warn":
                    filter.LevelMin = log4net.Core.Level.Warn;
                    break;

                default:
                    filter.LevelMin = log4net.Core.Level.All;
                    break;
                }



                filter.ActivateOptions();

                appender.Layout = layout;
                appender.AddFilter(filter);

                appender.ActivateOptions();
            }
            catch (Exception er)
            {
                using (StreamWriter sw = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "\\FatalLogError.log", true))
                {
                    sw.WriteLine(er.Message);
                }
            }

            return(appender);
        }
示例#15
0
        private RollingFileAppender CreateAppender(string appenderName, string fileName, ComonLog.LogLevel logLevel)
        {
            PatternLayout layout = new PatternLayout();
            layout.ConversionPattern = "%d %-5p  %m%n";
            layout.ActivateOptions();

            RollingFileAppender appender = new RollingFileAppender();
            appender.Layout = layout;

            appender.Name = appenderName;
            appender.File = fileName;

            appender.RollingStyle = RollingFileAppender.RollingMode.Composite;
            //appender.Encoding = Encoding.Unicode;
            appender.AppendToFile = true;
            appender.MaximumFileSize = "4MB";
            appender.MaxSizeRollBackups = 100;
            appender.DatePattern = "yyyy-MM-dd";
            appender.PreserveLogFileNameExtension = true;
            appender.StaticLogFileName = false;
            appender.Threshold = FileAppenderHelper.ConvertLogLevel(logLevel);

            log4net.Filter.LevelRangeFilter levfilter = new log4net.Filter.LevelRangeFilter();
            levfilter.LevelMax = appender.Threshold;
            levfilter.LevelMin = appender.Threshold;
            levfilter.ActivateOptions();

            appender.AddFilter(levfilter);

            appender.ActivateOptions();

            return appender;
        }
示例#16
0
        /// <summary>
        /// The add file appender.
        /// </summary>
        /// <param name="hierarchy">
        /// The hierarchy.
        /// </param>
        /// <param name="layout">
        /// The layout.
        /// </param>
        private static void AddFileAppender(Hierarchy hierarchy, ILayout layout)
        {
            string logFileName = AppUtil.GetLocalDataPath("Logs\\" + AppUtil.EntryModuleName);
            string actualLogFileName = logFileName;

            int tryCount = 0;
            while (IOUtils.IsFileLocked(actualLogFileName + LOG_EXT))
            {
                if (tryCount++ == 0)
                {
                    logFileName = actualLogFileName += DateTime.Now.ToString("_yyyyMMdd");
                }
                else
                {
                    actualLogFileName = logFileName + "_" + (tryCount - 1);
                }
            }

            string targetFile = actualLogFileName + LOG_EXT;
            Console.WriteLine("Initializing log file: " + targetFile);
            var fileAppender = new RollingFileAppender
                                   {
                                       Layout = layout,
                                       File = targetFile,
                                       AppendToFile = true,
                                       RollingStyle = RollingFileAppender.RollingMode.Size,
                                       MaxSizeRollBackups = 10,
                                       MaximumFileSize = "10MB",
                                       StaticLogFileName = true
                                   };
            fileAppender.AddFilter(
                new LevelRangeFilter { AcceptOnMatch = true, LevelMin = AppUtil.IsDebugBuild ? Level.Debug : Level.Info, LevelMax = Level.Fatal });

            fileAppender.ActivateOptions();
            hierarchy.Root.AddAppender(fileAppender);
        }