Ejemplo n.º 1
0
        private static void ConfigureAppender(AppenderSkeleton appender)
        {
            if (appender.Layout == null)
            {
                appender.Layout = new log4net.Layout.PatternLayout("%d [%t] %-5p %c [%x] <%X{auth}> - %m%n");
            }

            var cfg = Configure.GetConfigSection <Config.Logging>();

            if (cfg != null)
            {
                foreach (var f in typeof(Level).GetFields(BindingFlags.Public | BindingFlags.Static))
                {
                    if (string.Compare(cfg.Threshold, f.Name, true) == 0)
                    {
                        var val = f.GetValue(null);
                        appender.Threshold = val as Level;
                        break;
                    }
                }
            }

            if (appender.Threshold == null)
            {
                appender.Threshold = Level.Info;
            }

            appender.ActivateOptions();

            log4net.Config.BasicConfigurator.Configure(appender);
        }
Ejemplo n.º 2
0
        public static void Initialize(string logfilePath, string optionalLog4NetConfigPath)
        {
            // When interactice, also activate logging to the console.
            if (Environment.UserInteractive)
            {
                BasicConfigurator.Configure();
            }

            // Use a full-featured log4net log4net configuration file it it exist, otherwise
            // use a simple hardcoded default.
            if (string.IsNullOrWhiteSpace(optionalLog4NetConfigPath) || !File.Exists(optionalLog4NetConfigPath))
            {
                _appender = new RollingFileAppender
                {
                    Name                         = "DefaultAppended",
                    File                         = logfilePath,
                    RollingStyle                 = RollingFileAppender.RollingMode.Size,
                    MaxSizeRollBackups           = 10,
                    PreserveLogFileNameExtension = true,
                    Threshold                    = _debug ? Level.Debug : Level.Info,
                    Layout                       = new PatternLayout("%date [%2thread] %-5level %logger %ndc - %message%newline"),
                };
                _appender.ActivateOptions();
                BasicConfigurator.Configure(_appender);
            }
            else
            {
                XmlConfigurator.ConfigureAndWatch(new FileInfo(optionalLog4NetConfigPath));
            }

            Log.Info(new string('-', 30));
        }
Ejemplo n.º 3
0
        private static void LoadLayout(AppenderSkeleton appender, ILoggerRepository repository)
        {
            PatternLayout patternLayout = new PatternLayout();

            patternLayout.ConversionPattern = "记录时间:%date 线程ID:[%thread] 日志级别:%-5level :%logger %n%message%n%n";
            patternLayout.ActivateOptions();
            appender.Layout = patternLayout;
            appender.ActivateOptions();
            BasicConfigurator.Configure(repository, appender);
        }
Ejemplo n.º 4
0
            private static ILog LoadConf(TextLog.Default.Config config)
            {
                PatternLayout    layout           = new PatternLayout(config.PatternLayout);
                AppenderSkeleton appenderSkeleton = config.Appender as TextWriterAppender;

                appenderSkeleton.Layout = layout;
                appenderSkeleton.ActivateOptions();
                ILoggerRepository loggerRepository = LogManager.CreateRepository(Guid.NewGuid().ToString());

                BasicConfigurator.Configure(loggerRepository, appenderSkeleton);
                return(LogManager.GetLogger(loggerRepository.Name, Guid.NewGuid().ToString()));
            }
Ejemplo n.º 5
0
        /// <summary>
        /// Initializes the logging system with extra options used by unit tests.
        /// </summary>
        /// <param name="enableMemoryLogger">If true, stores a copy of all log events in memory. Used for testing.</param>
        /// <param name="enableFileLogger">If true, outputs log events to a file.</param>
        /// <param name="colorConsole">If True, colored logs will be used.</param>
        /// <param name="defaultLevel">The default level to set for the root logger.</param>
        /// <param name="quietConsole">If True limits the level on the appenders to <see cref="Level.Error"/></param>
        internal static void Initialize(
            bool enableMemoryLogger,
            bool enableFileLogger,
            bool colorConsole,
            Level defaultLevel,
            bool quietConsole)
        {
            Contract.Requires <InvalidOperationException>(!configured, "The logger system can only be initialised once");
            configured = true;

            repository = (Hierarchy)LogManager.GetRepository();

            repository.LevelMap.Add(LogExtensions.PromptLevel);
            repository.LevelMap.Add(LogExtensions.SuccessLevel);

            rootLogger      = repository.Root;
            cleanLogger     = (Logger)repository.GetLogger(Cleanlogger);
            noConsoleLogger = (Logger)repository.GetLogger(Logfileonly);

            // cleanLogger.Hierarchy = repository;
            // noConsoleLogger.Hierarchy = repository;

            // our two special loggers do not forward log events to the root logger
            cleanLogger.Additivity     = false;
            noConsoleLogger.Additivity = false;

            // this is the base level for the logging system
            repository.Threshold = defaultLevel;
            rootLogger.Level     = defaultLevel;

            // log to a file
            PatternLayout standardPattern = new PatternLayout
            {
                ConversionPattern = "%date{o} [%thread] %-5level %logger - %message%newline%exception",
            };

            standardPattern.ActivateOptions();

            string logFilePath = null;

            if (enableFileLogger)
            {
                var fileAppender = new RollingFileAppender()
                {
                    AppendToFile      = false,
                    Encoding          = Encoding.UTF8,
                    StaticLogFileName = true,

                    // We clean our logs ourselves, so it might be assumed that MaxSizeRollBackups is not needed,
                    // however this constraint is needed to trigger log4net's dedupe function for duplicate file names
                    MaxSizeRollBackups = 100,
                    Layout             = standardPattern,
                    Name = nameof(RollingFileAppender),
                    File = new PatternString("Logs/log_%utcdate{yyyyMMddTHHmmssZ}.txt").Format(),
                    PreserveLogFileNameExtension = true,
                    RollingStyle = RollingFileAppender.RollingMode.Once,
                };
                rootLogger.AddAppender(fileAppender);
                cleanLogger.AddAppender(fileAppender);
                noConsoleLogger.AddAppender(fileAppender);
                fileAppender.ActivateOptions();
                logFilePath = fileAppender.File;
            }

            if (enableMemoryLogger)
            {
                MemoryAppender = new MemoryAppender()
                {
                    Layout = standardPattern,
                };
                rootLogger.AddAppender(MemoryAppender);
                cleanLogger.AddAppender(MemoryAppender);
                noConsoleLogger.AddAppender(MemoryAppender);
                MemoryAppender.ActivateOptions();
            }

            // log to a console
            PatternLayout consolePattern = new PatternLayout
            {
                ConversionPattern = "[%date{o}] %-5level - %message%newline%exception",
            };

            consolePattern.ActivateOptions();
            standardConsoleAppender =
                colorConsole ? (AppenderSkeleton) new ManagedColoredConsoleAppender() : new ConsoleAppender();
            standardConsoleAppender.Layout = consolePattern;

            PatternLayout cleanPattern = new PatternLayout
            {
                ConversionPattern = "%message%newline",
            };

            cleanPattern.ActivateOptions();
            cleanConsoleAppender =
                colorConsole ? (AppenderSkeleton) new ManagedColoredConsoleAppender() : new ConsoleAppender();
            cleanConsoleAppender.Layout = cleanPattern;

            if (colorConsole)
            {
                var mapping = new[]
                {
                    new LevelColors {
                        ForeColor = ConsoleColor.Magenta, Level = LogExtensions.PromptLevel
                    },
                    new LevelColors {
                        ForeColor = ConsoleColor.Red, Level = Level.Fatal
                    },
                    new LevelColors {
                        ForeColor = ConsoleColor.DarkRed, Level = Level.Error
                    },
                    new LevelColors {
                        ForeColor = ConsoleColor.Yellow, Level = Level.Warn
                    },
                    new LevelColors {
                        ForeColor = ConsoleColor.Green, Level = LogExtensions.SuccessLevel
                    },
                    new LevelColors {
                        ForeColor = ConsoleColor.Green, Level = Level.Notice
                    },
                    new LevelColors {
                        ForeColor = ConsoleColor.Gray, Level = Level.Info
                    },
                    new LevelColors {
                        ForeColor = ConsoleColor.Cyan, Level = Level.Debug
                    },
                    new LevelColors {
                        ForeColor = ConsoleColor.DarkCyan, Level = Level.Trace
                    },
                    new LevelColors {
                        ForeColor = ConsoleColor.DarkBlue, Level = Level.Verbose
                    },
                };

                foreach (var map in mapping)
                {
                    ((ManagedColoredConsoleAppender)standardConsoleAppender).AddMapping(map);
                    ((ManagedColoredConsoleAppender)cleanConsoleAppender).AddMapping(map);
                }
            }

            standardConsoleAppender.ActivateOptions();
            cleanConsoleAppender.ActivateOptions();

            rootLogger.AddAppender(standardConsoleAppender);
            cleanLogger.AddAppender(cleanConsoleAppender);

            repository.Configured = true;
            ModifyVerbosity(defaultLevel, quietConsole);

            if (enableFileLogger)
            {
                // Fire and forget the async cleaning task.
                // We'll never know if this fails or not, the exception is captured in the task
                // that we do NOT await. We do however log any exceptions.
                _ = CleanLogs(logFilePath);
            }
        }