private void SetupLogger()
        {
            Hierarchy     hierarchy     = (Hierarchy)LogManager.GetRepository();
            PatternLayout patternLayout = new PatternLayout();

            patternLayout.ConversionPattern = "%date [%thread] %-5level [%class.%method] - %message%newline";
            patternLayout.ActivateOptions();
            RollingFileAppender roller = new RollingFileAppender();

            roller.AppendToFile       = false;
            roller.File               = @"ResultExporterLog.txt";
            roller.Layout             = patternLayout;
            roller.MaxSizeRollBackups = 5;
            roller.MaximumFileSize    = "1GB";
            roller.RollingStyle       = RollingFileAppender.RollingMode.Size;
            roller.StaticLogFileName  = true;
            roller.ActivateOptions();
            ConsoleAppender console = new ConsoleAppender();
            PatternLayout   consolePatternLayout = new PatternLayout();

            consolePatternLayout.ConversionPattern = "%date [Testlink Result Exporter] [%level] %message%newline";
            consolePatternLayout.ActivateOptions();
            LevelRangeFilter consoleLevelFilter = new LevelRangeFilter();

            consoleLevelFilter.LevelMin = Level.Info;
            consoleLevelFilter.LevelMax = Level.Fatal;
            console.AddFilter(consoleLevelFilter);
            console.Layout = consolePatternLayout;
            hierarchy.Root.AddAppender(roller);
            hierarchy.Root.AddAppender(console);
            hierarchy.Root.Level = Level.All;
            hierarchy.Configured = true;
        }
예제 #2
0
        private static ConsoleAppender InitializeErrorLogger()
        {
            var errorPatternLayout = new PatternLayout
            {
                ConversionPattern = "%date %logger %level - %message%newline%exception%stacktracedetail",
                IgnoresException  = false,
            };

            errorPatternLayout.ActivateOptions();
            var filter = new LevelRangeFilter
            {
                LevelMin = Level.Warn,
                LevelMax = Level.Fatal
            };

            filter.ActivateOptions();
            var errorFileAppender = new ConsoleAppender
            {
                Layout = errorPatternLayout
            };

            errorFileAppender.AddFilter(filter);
            errorFileAppender.ActivateOptions();
            return(errorFileAppender);
        }
예제 #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);
            }
        }
예제 #4
0
        public static void InitLogging()
        {
            var layout = new PatternLayout {
                ConversionPattern = "%date [%thread] %-5level %logger - %message%newline"
            };

            layout.ActivateOptions();

            var filter = new LevelRangeFilter {
                LevelMin = Level.Warn, LevelMax = Level.Fatal
            };

            filter.ActivateOptions();

            var eventLogAppender = new EventLogAppender
            {
                ApplicationName = "NServiceBus Sample Server",
                Threshold       = Level.All,
                Layout          = layout
            };

            eventLogAppender.AddFilter(filter);
            eventLogAppender.ActivateOptions();

            var consoleAppender = new ConsoleAppender
            {
                Threshold = Level.Info,
                Layout    = layout
            };

            BasicConfigurator.Configure(consoleAppender);

            LogManager.Use <Log4NetFactory>();
        }
예제 #5
0
        private static ConsoleAppender InitializeInfoLogger()
        {
            var infoPatternLayout = new PatternLayout
            {
                ConversionPattern = "%date %logger %level - %message%newline",
            };

            infoPatternLayout.ActivateOptions();

            var filter = new LevelRangeFilter
            {
                LevelMin = Level.Debug,
                LevelMax = Level.Info,
            };

            filter.ActivateOptions();
            var infofileAppender = new ConsoleAppender
            {
                Layout = infoPatternLayout,
            };

            infofileAppender.AddFilter(filter);
            infofileAppender.ActivateOptions();

            return(infofileAppender);
        }
예제 #6
0
        public void Configure()
        {
            var traceLevelFilter = new LevelRangeFilter
            {
                LevelMax = Level.Error
            };
            var infoLevelFilter = new LevelRangeFilter
            {
                LevelMax = Level.Info
            };

            var errorLevelFilter = new LevelRangeFilter
            {
                LevelMin = Level.Warn,
                LevelMax = Level.Error
            };

            var hierarchy = (Hierarchy)LogManager.GetRepository();

            var traceAppender            = CreateTraceAppender(traceLevelFilter);
            var eventLogAppender         = CreateEventLogAppender(Level.Warn);
            var infoRollingFileAppender  = CreateRollingFileAppender(CreateFileName("Info"), "InfoRollingFileAppender", infoLevelFilter);
            var errorRollingFileAppender = CreateRollingFileAppender(CreateFileName("Error"), "ErrorRollingFileAppender", errorLevelFilter);

            //Configure loggers
            hierarchy.Root.Level = Level.All;
            hierarchy.Root.AddAppender(infoRollingFileAppender);  //Debug-Info
            hierarchy.Root.AddAppender(errorRollingFileAppender); //Warn-Error
            hierarchy.Root.AddAppender(eventLogAppender);         //Wann
            hierarchy.Root.AddAppender(traceAppender);            //Debug only


            hierarchy.Configured = true;
        }
    private static RollingFileAppender InitializeInfoLogger(string logFilePath)
    {
        var infoPatternLayout = new PatternLayout
        {
            ConversionPattern = "%date %logger %level - %message%newline",
        };

        infoPatternLayout.ActivateOptions();

        var filter = new LevelRangeFilter
        {
            LevelMin = Level.Debug,
            LevelMax = Level.Info,
        };

        filter.ActivateOptions();
        var infofileAppender = new RollingFileAppender
        {
            AppendToFile      = true,
            File              = logFilePath,
            Layout            = infoPatternLayout,
            LockingModel      = new FileAppender.MinimalLock(),
            MaximumFileSize   = "10MB",
            RollingStyle      = RollingFileAppender.RollingMode.Size,
            StaticLogFileName = false
        };

        infofileAppender.AddFilter(filter);
        infofileAppender.ActivateOptions();

        return(infofileAppender);
    }
예제 #8
0
        public CustomLogger(string path, string prefix, Level minLevel, Level maxLevel)
        {
            this.string_0 = prefix;
            this.level_0  = minLevel ?? Level.All;
            this.level_1  = maxLevel ?? Level.Emergency;
            Directory.CreateDirectory(path);
            PatternLayout layout = new PatternLayout("%-4utcdate [%thread] %-5level %logger{1} %ndc - %message%newline");
            DateTime      now    = DateTime.Now;

            object[] args = new object[] { now.Year, now.Month, now.Day, now.Hour, now.Minute, Process.GetCurrentProcess().Id, path, this.string_0 };
            this.FileName = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), string.Format(@"{6}\{7} {5} {0:0000}-{1:00}-{2:00} {3:00}.{4:00}.txt", args));
            FileAppender newAppender = new FileAppender {
                File         = this.FileName,
                Layout       = layout,
                LockingModel = new FileAppender.MinimalLock()
            };
            LevelRangeFilter filter = new LevelRangeFilter {
                LevelMin      = this.level_0,
                LevelMax      = this.level_1,
                AcceptOnMatch = true
            };

            newAppender.AddFilter(filter);
            layout.ActivateOptions();
            newAppender.ActivateOptions();
            AsyncAppender appender2 = new AsyncAppender();

            appender2.AddAppender(newAppender);
            appender2.ActivateOptions();
            log4net.Repository.Hierarchy.Hierarchy hierarchy1 = (log4net.Repository.Hierarchy.Hierarchy)LogManager.CreateRepository(this.string_0);
            hierarchy1.Root.AddAppender(appender2);
            hierarchy1.Configured = true;
        }
예제 #9
0
파일: FileLog.cs 프로젝트: openzones/OMI
        private static RollingFileAppender CreateFileAppender(string appName)
        {
            PatternLayout layout = new PatternLayout();

            layout.ConversionPattern = "%d{yyyy-MM-dd HH:mm:ss.fff} %-5p [%C{1}] %m%n";
            layout.ActivateOptions();

            RollingFileAppender appender = new RollingFileAppender();
            string path         = ConfiguraionProvider.LogPath;
            string fileSizeInMb = ConfiguraionProvider.FileSizeInMb;

            appender.AppendToFile       = true;
            appender.File               = Path.Combine(Path.Combine(path, appName), string.Format("{0}.log", appName));
            appender.ImmediateFlush     = true;
            appender.Layout             = layout;
            appender.MaximumFileSize    = string.Format("{0}MB", fileSizeInMb);
            appender.MaxSizeRollBackups = 2;
            appender.RollingStyle       = RollingFileAppender.RollingMode.Size;
            appender.StaticLogFileName  = true;
            appender.LockingModel       = new FileAppender.MinimalLock();

            LevelRangeFilter levelFilter = new LevelRangeFilter();

            levelFilter.LevelMin = Level.Info;
            levelFilter.LevelMax = Level.Fatal;

            appender.ErrorHandler = new EventLogErrorHandler();
            appender.AddFilter(levelFilter);
            appender.ActivateOptions();

            return(appender);
        }
    private static RollingFileAppender InitializeErrorLogger(string logFilePath)
    {
        var errorPatternLayout = new PatternLayout
        {
            ConversionPattern = "%date %logger %level - %message%newline%exception%stacktracedetail",
            IgnoresException  = false,
        };

        errorPatternLayout.ActivateOptions();
        var filter = new LevelRangeFilter
        {
            LevelMin = Level.Warn,
            LevelMax = Level.Fatal
        };

        filter.ActivateOptions();
        var errorFileAppender = new RollingFileAppender
        {
            AppendToFile      = true,
            File              = logFilePath,
            LockingModel      = new FileAppender.MinimalLock(),
            Layout            = errorPatternLayout,
            MaximumFileSize   = "10MB",
            RollingStyle      = RollingFileAppender.RollingMode.Size,
            StaticLogFileName = false
        };

        errorFileAppender.AddFilter(filter);
        errorFileAppender.ActivateOptions();
        return(errorFileAppender);
    }
예제 #11
0
        public Filter getFilter()
        {
            var filter = new LevelRangeFilter();

            filter.setLevelMin(Level.DEBUG);
            filter.setLevelMax(Level.FATAL);
            return(filter);
        }
예제 #12
0
파일: NLog.cs 프로젝트: jayrulez/TOMClassic
        public static void Start(LogTargets target) //server remote mode will be set auto when use SetRemote
        {
            type = target;
            List <IAppender> appenders = new List <IAppender>();

            if ((type & LogTargets.ServerRemote) != 0 && remoteIP != "")
            {
                UdpAppender appender = new UdpAppender();
                appender.Layout        = new PatternLayout(format);
                appender.RemoteAddress = IPAddress.Parse(remoteIP);
                appender.RemotePort    = remotePort;
                LevelRangeFilter filter = new LevelRangeFilter();
                filter.LevelMin = Level.Debug;
                filter.LevelMax = Level.Fatal;
                appender.AddFilter(filter);
                appender.ActivateOptions();
                appenders.Add(appender);
            }

            if ((type & LogTargets.ServerConsole) != 0)
            {
                ColoredConsoleAppender appender = new ColoredConsoleAppender();
                appender.Layout = new PatternLayout(format);
                ColoredConsoleAppender.LevelColors mapcolor = new ColoredConsoleAppender.LevelColors();
                mapcolor.Level     = Level.Fatal;
                mapcolor.BackColor = ColoredConsoleAppender.Colors.Red;
                appender.AddMapping(mapcolor);
                mapcolor           = new ColoredConsoleAppender.LevelColors();
                mapcolor.Level     = Level.Error;
                mapcolor.BackColor = ColoredConsoleAppender.Colors.Red;
                appender.AddMapping(mapcolor);
                mapcolor           = new ColoredConsoleAppender.LevelColors();
                mapcolor.Level     = Level.Warn;
                mapcolor.ForeColor = ColoredConsoleAppender.Colors.Purple;
                appender.AddMapping(mapcolor);
                mapcolor           = new ColoredConsoleAppender.LevelColors();
                mapcolor.Level     = Level.Info;
                mapcolor.ForeColor = ColoredConsoleAppender.Colors.Green;
                appender.AddMapping(mapcolor);
                appender.ActivateOptions();
                appenders.Add(appender);
            }

            if ((type & LogTargets.File) != 0)
            {
                FileAppender appender = new FileAppender();
                appender.Layout       = new PatternLayout(format);
                appender.File         = string.Format("Log/{0}-{1}-{2}.log", DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
                appender.AppendToFile = true;
                appender.Name         = "FileAppender";
                appender.ActivateOptions();
                appenders.Add(appender);
            }

            BasicConfigurator.Configure(appenders.ToArray());
        }
예제 #13
0
        private static void AddAppender(string directoryName, Level minLevel, Level maxLevel, Level threshold)
        {
            var layout   = new PatternLayout("%message");
            var appender = new CompressedRollingFileAppender();

            //string currentDirectoryPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

            string currentDirectoryPath = "C:\\DMS_LOGS\\"; // in case of Log Folder Path not configured

            try
            {
                currentDirectoryPath = ConfigurationManager.AppSettings["Log.LogFolder"].ToString();
            }
            catch (Exception)
            {
            }



            if (currentDirectoryPath != null)
            {
                var directory = Path.Combine(currentDirectoryPath, "Logs");

                if (!Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }

                directory = Path.Combine(directory, directoryName);

                if (!Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }

                appender.File = Path.Combine(directory, LOG_FILE_NAME + ".log");
            }
            appender.Layout             = layout;
            appender.AppendToFile       = true; // we will start a new one when the program starts'
            appender.Name               = "CompressedRollingFileAppender";
            appender.Threshold          = Level.All;
            appender.RollingStyle       = RollingFileAppender.RollingMode.Composite; //This means it will start a new log file each time the log grows to 20Mb'
            appender.MaximumFileSize    = "20MB";
            appender.DatePattern        = "yyyy-MM-dd";
            appender.MaxSizeRollBackups = 2000; // 'keep an infinite number of logs'
            appender.StaticLogFileName  = false;
            appender.CountDirection     = 1;    // ' to reduce rollover costs'
            var filter = new LevelRangeFilter {
                LevelMin = minLevel, LevelMax = maxLevel
            };

            appender.AddFilter(filter);
            appender.Threshold = threshold;
            log4net.Config.BasicConfigurator.Configure(appender);
            appender.ActivateOptions();
        }
예제 #14
0
        private static FilterSkeleton CreateLevelFilter(Level level)
        {
            var levelFilter = new LevelRangeFilter();

            levelFilter.LevelMin = level;
            levelFilter.LevelMax = level;
            levelFilter.ActivateOptions();

            return(levelFilter);
        }
예제 #15
0
        private static LevelRangeFilter GetLevelRange(Log4NetAppenderConfig appenderConfig)
        {
            var rangeFilter = new LevelRangeFilter
            {
                LevelMin = GetLevel(appenderConfig.LevelMin),
                LevelMax = GetLevel(appenderConfig.LevelMax)
            };

            return(rangeFilter);
        }
예제 #16
0
        /// <summary>
        /// Appends inclusive filter to the log
        /// </summary>
        /// <param name="minRange">The min range.</param>
        /// <param name="maxRange">The max range.</param>
        /// <returns>same syntax</returns>
        public LogSyntax Filter(LogLevel minRange, LogLevel maxRange)
        {
            var filter = new LevelRangeFilter
            {
                LevelMin      = minRange.ToLog4Net(),
                LevelMax      = maxRange.ToLog4Net(),
                AcceptOnMatch = true
            };

            filter.ActivateOptions();
            _skeleton.AddFilter(filter);
            //_skeleton.ActivateOptions();
            return(this);
        }
예제 #17
0
        /// <summary>
        /// 设置日志格式
        /// </summary>
        /// <param name="repositoryName">Repository(版本库)名称</param>
        /// <param name="level">日志等级</param>
        static void CreateLogger(string repositoryName, Level level)
        {
            ILoggerRepository curRepository = LogManager.GetRepository(repositoryName);

            //设置日志属性
            RollingFileAppender curAppender = new RollingFileAppender()
            {
                //日志的名称:版本库+日志登记命名
                Name = repositoryName,
                //日志的保存目录
                File = string.Format("log\\{0}\\", repositoryName),
                //是否静态日志名,静态通过fileAppender.File设置,动态通过日期或者文件大小进行设置
                StaticLogFileName = false,
                //根据日期设置日志文件名
                RollingStyle = RollingFileAppender.RollingMode.Composite,
                //日志文件名的命名规则
                DatePattern = string.Format("yyyyMMdd{0}.lo\\g", level),
                //是否把日志加入到原有日志中。
                AppendToFile = true,
                //每个单独日志文件的最大大小。
                MaxFileSize = 50 * 1024 * 1024,
                //日志可以重写的数量,log,log.1,log.2....
                MaxSizeRollBackups = 1000,
                //选择UTF8编码,确保中文不乱码
                Encoding     = Encoding.UTF8,
                LockingModel = new log4net.Appender.FileAppender.MinimalLock()
            };

            //过滤日志等级
            LevelRangeFilter filter = new LevelRangeFilter()
            {
                LevelMax = level == Level.All ? Level.Fatal : level, LevelMin = level
            };

            curAppender.AddFilter(filter);
            filter.ActivateOptions();

            //设置日志记录的内容
            PatternLayout pattenLayout = new PatternLayout()
            {
                ConversionPattern = "%date [%thread] %-5level  %logger %message%newline"
            };

            curAppender.Layout = pattenLayout;
            pattenLayout.ActivateOptions();

            curAppender.ActivateOptions();
            BasicConfigurator.Configure(curRepository, curAppender);
        }
 public void LevelRangeFilter_EntriesWithinRangeReturnsMatch()
 {
     LevelRangeFilter filter = new LevelRangeFilter { MinLevel = LogLevel.Information, MaxLevel = LogLevel.Debug, Action = LogFilterResult.Accept };
     Logger logger = new Logger(null, typeof(LevelRangeFilterTests));
     ILogEntry informationEntry = new LogEntry(DateTimeOffset.Now, LogLevel.Information, "", logger, null);
     ILogEntry verboseEntry = new LogEntry(DateTimeOffset.Now, LogLevel.Verbose, "", logger, null);
     ILogEntry debugEntry = new LogEntry(DateTimeOffset.Now, LogLevel.Debug, "", logger, null);
     ILogEntry errorEntry = new LogEntry(DateTimeOffset.Now, LogLevel.Error, "", logger, null);
     ILogEntry fatalEntry = new LogEntry(DateTimeOffset.Now, LogLevel.Fatal, "", logger, null);
     ILogEntry warningEntry = new LogEntry(DateTimeOffset.Now, LogLevel.Warning, "", logger, null);
     Assert.AreEqual(LogFilterResult.Accept, filter.Evaluate(informationEntry));
     Assert.AreEqual(LogFilterResult.Accept, filter.Evaluate(verboseEntry));
     Assert.AreEqual(LogFilterResult.Accept, filter.Evaluate(debugEntry));
     Assert.AreEqual(LogFilterResult.Neutral, filter.Evaluate(errorEntry));
     Assert.AreEqual(LogFilterResult.Neutral, filter.Evaluate(fatalEntry));
     Assert.AreEqual(LogFilterResult.Neutral, filter.Evaluate(warningEntry));
 }
예제 #19
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);
        }
예제 #20
0
        internal static IAppender CreateConsoleAppender(string name)
        {
            ConsoleAppender appender = new ConsoleAppender
            {
                Name   = name + "ConsoleAppender",
                Layout = LogPatternHelper.GetConsolePatternLayout(),
            };

            // Filter to only allow INFO, ERROR and FATAL events to log to console.
            LevelRangeFilter filter = new LevelRangeFilter
            {
                LevelMin = Level.Info,
                LevelMax = Level.Fatal
            };

            appender.AddFilter(filter);

            appender.ActivateOptions();
            return(appender);
        }
예제 #21
0
파일: Log.cs 프로젝트: driesmeyers/Nitrox
        private static void Setup()
        {
            Hierarchy hierarchy = (Hierarchy)LogManager.GetRepository();

            PatternLayout patternLayout = new PatternLayout();

            patternLayout.ConversionPattern = "[%d{HH:mm:ss} %logger %level]: %m%n";
            patternLayout.ActivateOptions();

            LevelRangeFilter filter = new LevelRangeFilter();

            filter.LevelMin = Level.Debug;
            filter.LevelMax = Level.Fatal;

            RollingFileAppender fileAppender = new RollingFileAppender();
            string basePath = GameInstallationFinder.Instance.FindGame();

            fileAppender.File                         = Path.Combine(basePath ?? "", "Nitrox Logs", "nitrox-.log"); // Attempt to create 'Nitrox Logs' dir where the game is.
            fileAppender.AppendToFile                 = true;
            fileAppender.RollingStyle                 = RollingFileAppender.RollingMode.Date;
            fileAppender.MaxSizeRollBackups           = 10;
            fileAppender.DatePattern                  = "yyyy-MM-dd";
            fileAppender.StaticLogFileName            = false;
            fileAppender.PreserveLogFileNameExtension = true;
            fileAppender.LockingModel                 = new FileAppender.MinimalLock();
            fileAppender.Layout                       = patternLayout;
            fileAppender.ActivateOptions();
            fileAppender.AddFilter(filter);

            ConsoleAppender consoleAppender = new ConsoleAppender();

            consoleAppender.Layout = patternLayout;
            consoleAppender.AddFilter(filter);

            hierarchy.Root.AddAppender(consoleAppender);
            hierarchy.Root.AddAppender(fileAppender);

            hierarchy.Configured = true;
        }
예제 #22
0
        public OutputWindowPaneAppender(EnvDTE.OutputWindowPane outputWindowPane, Level maxLevel)
        {
            this.outputWindowPane = outputWindowPane;

            LevelRangeFilter filter = new LevelRangeFilter();

            filter.LevelMin = maxLevel;
            base.AddFilter(filter);

            PatternLayout layout = new PatternLayout();

            if (maxLevel.CompareTo(Level.Debug) <= 0)
            {
                layout.ConversionPattern = "%date %-5level %logger - %message%newline";
            }
            else
            {
                layout.ConversionPattern = "[%level] %message%newline";
            }
            layout.ActivateOptions();
            base.Layout = layout;
        }
예제 #23
0
        private static IAppender GetMemoryAppender(string station)
        {
            //MemoryAppender
            var memoryAppenderLayout = new PatternLayout("%date{HH:MM:ss} | %message%newline");

            memoryAppenderLayout.ActivateOptions();

            var memoryAppenderWithEventsName = string.Format("{0}{1}", MemoryAppenderNameDefault, station);
            var levelRangeFilter             = new LevelRangeFilter();

            levelRangeFilter.LevelMax = Level.Fatal;
            levelRangeFilter.LevelMin = Level.Info;

            var memoryAppenderWithEvents = new MemoryAppenderWithEvents();

            memoryAppenderWithEvents.Name = memoryAppenderWithEventsName;
            memoryAppenderWithEvents.AddFilter(levelRangeFilter);
            memoryAppenderWithEvents.Layout = memoryAppenderLayout;
            memoryAppenderWithEvents.ActivateOptions();

            return(memoryAppenderWithEvents);
        }
예제 #24
0
 public void ChangeLogFilterLevel(Level minLevel = null, Level maxLevel = null)
 {
     if (minLevel != null)
     {
         this.level_0 = minLevel;
     }
     if (maxLevel != null)
     {
         this.level_1 = maxLevel;
     }
     if (this.wpfRtfAppender_0 != null)
     {
         this.wpfRtfAppender_0.ClearFilters();
         LevelRangeFilter filter = new LevelRangeFilter {
             LevelMin      = this.level_0,
             LevelMax      = this.level_1,
             AcceptOnMatch = true
         };
         this.wpfRtfAppender_0.AddFilter(filter);
         this.wpfRtfAppender_0.AddFilter(new DenyAllFilter());
     }
 }
예제 #25
0
파일: Log.cs 프로젝트: yawaraka/Nitrox
        private static void Setup()
        {
            Hierarchy hierarchy = (Hierarchy)LogManager.GetRepository();

            PatternLayout patternLayout = new PatternLayout();

            patternLayout.ConversionPattern = "[%d{HH:mm:ss} %level]: %m%n";
            patternLayout.ActivateOptions();

            LevelRangeFilter filter = new LevelRangeFilter();

            filter.LevelMin = Level.Debug;
            filter.LevelMax = Level.Fatal;

            RollingFileAppender fileAppender = new RollingFileAppender();

            fileAppender.File                         = "Nitrox Logs/nitrox-.log";
            fileAppender.AppendToFile                 = false;
            fileAppender.RollingStyle                 = RollingFileAppender.RollingMode.Date;
            fileAppender.MaxSizeRollBackups           = 10;
            fileAppender.DatePattern                  = "yyyy-MM-dd";
            fileAppender.StaticLogFileName            = false;
            fileAppender.PreserveLogFileNameExtension = true;
            fileAppender.LockingModel                 = new FileAppender.MinimalLock();
            fileAppender.Layout                       = patternLayout;
            fileAppender.ActivateOptions();
            fileAppender.AddFilter(filter);

            ConsoleAppender consoleAppender = new ConsoleAppender();

            consoleAppender.Layout = patternLayout;
            consoleAppender.AddFilter(filter);

            hierarchy.Root.AddAppender(consoleAppender);
            hierarchy.Root.AddAppender(fileAppender);

            hierarchy.Configured = true;
        }
        public void MessagesExcludedByFilterShouldNotBeAppended()
        {
            // Arrange
            var levelFilter =
                new LevelRangeFilter
            {
                LevelMin = Level.Warn,
                LevelMax = Level.Error,
            };

            asyncForwardingAppender.AddFilter(levelFilter);

            // Act
            log.Info("Info");
            log.Warn("Warn");
            log.Error("Error");
            log.Fatal("Fatal");

            asyncForwardingAppender.Close();

            //Assert
            Assert.That(debugAppender.LoggedEventCount, Is.EqualTo(2));
        }
예제 #27
0
        public void AddWpfListener(ScrollViewer scrollViewer, RichTextBox rtbLog)
        {
            PatternLayout  layout    = new PatternLayout("%message");
            WpfRtfAppender appender1 = new WpfRtfAppender(scrollViewer, rtbLog)
            {
                Layout = layout
            };

            this.wpfRtfAppender_0 = appender1;
            LevelRangeFilter filter = new LevelRangeFilter {
                LevelMin = this.level_0,
                LevelMax = this.level_1
            };

            this.wpfRtfAppender_0.AddFilter(filter);
            layout.ActivateOptions();
            this.wpfRtfAppender_0.ActivateOptions();
            AsyncAppender newAppender = new AsyncAppender();

            newAppender.AddAppender(this.wpfRtfAppender_0);
            newAppender.ActivateOptions();
            ((log4net.Repository.Hierarchy.Hierarchy)LogManager.GetRepository(this.string_0)).Root.AddAppender(newAppender);
        }
예제 #28
0
        public override void Configure(string key, ILoggerRepository repository)
        {
            foreach (var level in Levels)
            {
                var appender = new log4net.Appender.ConsoleAppender();

                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);
            }
        }
예제 #29
0
        private static RollingFileAppender GetNewFileApender(string appenderName, string file, int maxSizeRollBackups, bool appendToFile = true, bool staticLogFileName = false, string maximumFileSize = "5MB", RollingFileAppender.RollingMode rollingMode = RollingFileAppender.RollingMode.Composite, string layoutPattern = "%d [%t] %-5p %c  - %m%n")
        {
            var appender = new RollingFileAppender
            {
                Name         = appenderName,
                Encoding     = System.Text.Encoding.UTF8,
                File         = file,
                AppendToFile = appendToFile,
                LockingModel = new FileAppender.MinimalLock(),
                RollingStyle = rollingMode,
                //DatePattern = datePattern,
                StaticLogFileName  = staticLogFileName,
                MaxSizeRollBackups = maxSizeRollBackups,
                MaximumFileSize    = maximumFileSize,
                CountDirection     = 0,
                Threshold          = Level.All
            };
            var layout = new PatternLayout(layoutPattern)
            {
                Header = "[Header]" + Environment.NewLine,
                Footer = "[Footer]" + Environment.NewLine
            };

            appender.Layout = layout;
            var filter = new LevelRangeFilter
            {
                LevelMin = Level.All,
                LevelMax = Level.Fatal
            };

            appender.AddFilter(filter);

            layout.ActivateOptions();
            filter.ActivateOptions();
            appender.ActivateOptions();
            return(appender);
        }
예제 #30
0
        public static ILog  getlogger(string name)
        {
            string filterlevels   = "AID|STF";
            string filenames      = "C://NLog//AID_Log|C://NLog//STF_log|C://NLog//GIM_log";
            string LevelsToFilter = "Debug,Error|Error|Fatal";

            string[]  levelsToFilters = LevelsToFilter.Split('|');
            string[]  filterleveling  = filterlevels.Split('|');
            string[]  filenaming      = filenames.Split('|');
            Hierarchy hierarchy       = (Hierarchy)LogManager.GetRepository();
            Logger    newLogger       = hierarchy.GetLogger(name) as Logger;

            newLogger.Additivity = false;
            hierarchy.Configured = true;
            var filter  = new LevelRangeFilter();
            var filter1 = new LevelRangeFilter();
            var filter2 = new LevelRangeFilter();

            for (int i = 0; i < filterleveling.Length; i++)
            {
                if (newLogger.Name.Equals(filterleveling[i]))
                {
                    var           roller = new RollingFileAppender();
                    PatternLayout pl     = new PatternLayout();
                    pl.ConversionPattern = "%d [%2%t] %-5p [%-10c]   %m%n%n";
                    pl.ActivateOptions();
                    roller.Name         = filterleveling[i].ToString();
                    roller.AppendToFile = true;
                    roller.File         = filenaming[i].ToString() + ".log";

                    roller.Layout = pl;

                    string[] LevelsToFiltersArr = levelsToFilters[i].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                    foreach (string levels in LevelsToFiltersArr)
                    {
                        if ("INFO".Equals(levels.ToUpper()))
                        {
                            filter.LevelMax = Level.Info;
                            filter.LevelMin = Level.Info;

                            roller.AddFilter(filter);
                        }
                        if ("DEBUG".Equals(levels.ToUpper()))
                        {
                            filter.LevelMax = Level.Debug;
                            filter.LevelMin = Level.Debug;
                            filter.Next     = filter;
                            roller.AddFilter(filter);
                        }
                        if ("ERROR".Equals(levels.ToUpper()))
                        {
                            filter.LevelMax = Level.Error;
                            filter.LevelMin = Level.Error;

                            roller.AddFilter(filter);
                        }
                        if ("FATAL".Equals(levels.ToUpper()))
                        {
                            filter.LevelMax = Level.Fatal;
                            filter.LevelMin = Level.Fatal;

                            roller.AddFilter(filter);
                        }
                        if ("WARN".Equals(levels.ToUpper()))
                        {
                            filter.LevelMax = Level.Warn;
                            filter.LevelMin = Level.Warn;

                            roller.AddFilter(filter);
                        }
                        filter.Next = filter;
                        roller.AddFilter(filter);
                    }

                    newLogger.AddAppender(roller);
                    roller.ActivateOptions();
                }
            }
            return(LogManager.GetLogger(name));
        }
 public void LevelRangeFilter_ThrowsIfMinimumLevelIsGreaterThanMaximumLevelAtInitialization()
 {
     LevelRangeFilter filter = new LevelRangeFilter { MinLevel = LogLevel.Debug, MaxLevel = LogLevel.Verbose, Action = LogFilterResult.Accept };
     filter.Initialize(null);
 }
예제 #32
0
파일: Sigma.cs 프로젝트: xiaoxiongnpu/Sigma
        /// <summary>
        /// Loads the log4net configuration either from the corresponding app.config file (see log4net for more details) or by
        /// statically generating a default logger.
        /// </summary>
        /// <param name="xml">If <c>true</c>, the app.config file will be loaded. Otherwise, a default configuration.</param>
        /// <param name="printDebug">If <c>true</c>, debug statements will be printed to console (otherwise only <c>Level.Info</c> and up).</param>
        public static void EnableLogging(bool xml = false, bool printDebug = false)
        {
            if (xml)
            {
                XmlConfigurator.Configure();
            }
            else
            {
                // see https://stackoverflow.com/questions/37213848/best-way-to-access-to-log4net-wrapper-app-config
                Hierarchy hierarchy = (Hierarchy)LogManager.GetRepository();

                PatternLayout patternLayout = new PatternLayout
                {
                    ConversionPattern = "%date %level [%thread] %logger{1} - %message%newline"
                };
                patternLayout.ActivateOptions();

                // Create a colored console appender with color mappings and level range [Info, Fatal]
                ColoredConsoleAppender console = new ColoredConsoleAppender
                {
                    Threshold = Level.All,
                    Layout    = patternLayout
                };
                LevelRangeFilter consoleRangeFilter = new LevelRangeFilter
                {
                    LevelMin = printDebug ? Level.Debug : Level.Info,
                    LevelMax = Level.Fatal
                };
                console.AddFilter(consoleRangeFilter);
                console.AddMapping(new ColoredConsoleAppender.LevelColors
                {
                    Level     = Level.Debug,
                    ForeColor = ColoredConsoleAppender.Colors.White
                });
                console.AddMapping(new ColoredConsoleAppender.LevelColors
                {
                    Level     = Level.Info,
                    ForeColor = ColoredConsoleAppender.Colors.Green
                });
                console.AddMapping(new ColoredConsoleAppender.LevelColors
                {
                    Level     = Level.Warn,
                    ForeColor = ColoredConsoleAppender.Colors.Yellow | ColoredConsoleAppender.Colors.HighIntensity
                });
                console.AddMapping(new ColoredConsoleAppender.LevelColors
                {
                    Level     = Level.Error,
                    ForeColor = ColoredConsoleAppender.Colors.Red | ColoredConsoleAppender.Colors.HighIntensity
                });
                console.AddMapping(new ColoredConsoleAppender.LevelColors
                {
                    Level     = Level.Fatal,
                    ForeColor = ColoredConsoleAppender.Colors.White | ColoredConsoleAppender.Colors.HighIntensity,
                    BackColor = ColoredConsoleAppender.Colors.Red | ColoredConsoleAppender.Colors.HighIntensity
                });
                console.ActivateOptions();

                hierarchy.Root.AddAppender(console);

                // Create also an appender that writes the log to sigma.log
                RollingFileAppender roller = new RollingFileAppender
                {
                    AppendToFile       = true,
                    File               = "sigma.log",
                    Layout             = patternLayout,
                    MaxSizeRollBackups = 5,
                    MaximumFileSize    = "15MB",
                    RollingStyle       = RollingFileAppender.RollingMode.Size,
                    StaticLogFileName  = true
                };
                roller.ActivateOptions();

                hierarchy.Root.AddAppender(roller);

                hierarchy.Root.Level = Level.Debug;
                hierarchy.Configured = true;
            }
        }
 public void LevelRangeFilter_ThrowsIfMinLevelIsNotSetAtInitialization()
 {
     LevelRangeFilter filter = new LevelRangeFilter { MaxLevel = LogLevel.Debug, Action = LogFilterResult.Accept };
     filter.Initialize(null);
 }