コード例 #1
0
        /// <summary>
        /// NLog Setup
        /// </summary>
        public static LoggingConfiguration Initialize()
        {
            // Create NLog configuration object
            var config = new LoggingConfiguration();

            // Create targets and add them to the configuration
            var fileTarget = GetFileTarget();

            config.AddTarget(fileTarget);

            // Define logging rules
            LoggingRule logRule = new LoggingRule("*", LogLevel.Trace, fileTarget);

            // Define filter to ignore logs from Microsoft DLLs
            var filterToIgnoreAllMicrosoftLogs = new ConditionBasedFilter
            {
                Condition = "starts-with(logger, 'Microsoft.')",
                Action    = FilterResult.Ignore
            };

            logRule.Filters.Add(filterToIgnoreAllMicrosoftLogs);

            config.LoggingRules.Add(logRule);

            // Define wrappers
            var asyncWrapper = GetAsyncTargetWrapper();

            asyncWrapper.WrappedTarget = fileTarget;
            SimpleConfigurator.ConfigureForTargetLogging(asyncWrapper, LogLevel.Trace);

            // Activate the configuration
            LogManager.Configuration = config;
            return(config);
        }
コード例 #2
0
        public static void AddCustomLogger(this ILoggingBuilder configureLogging, IConfiguration configuration)
        {
            var config = new LoggingConfiguration();

            configureLogging.AddConfiguration(configuration.GetSection("Logging"));
            // Create targets and add them to the configuration
            var fileTarget = GetFileTarget();

            config.AddTarget(fileTarget);

            // Define logging rules
            LoggingRule logRule = new LoggingRule("*", LogLevel.Trace, fileTarget);

            // Define filter to ignore logs from Microsoft DLLs
            var filterToIgnoreAllMicrosoftLogs = new ConditionBasedFilter
            {
                Condition = "starts-with(logger, 'Microsoft.')",
                Action    = FilterResult.Ignore
            };

            logRule.Filters.Add(filterToIgnoreAllMicrosoftLogs);

            // Define wrappers
            var asyncWrapper = GetAsyncTargetWrapper();

            asyncWrapper.WrappedTarget = fileTarget;
            SimpleConfigurator.ConfigureForTargetLogging(asyncWrapper, LogLevel.Trace);

            // Activate the configuration
            config.LoggingRules.Add(logRule);
            LogManager.Configuration = config;

            //Add nlog by default
            configureLogging.AddNLog(config);
        }
コード例 #3
0
        public NLogLogger(string fileName, LogLevel level, int portable)
        {
            var logPath = $@"{Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)}\MPTagThat\Log";

            if (portable == 1)
            {
                logPath = $@"{AppDomain.CurrentDomain.BaseDirectory}\Log";
            }

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

            var fullFileName = $@"{logPath}\{fileName}";

            _level = level;

            // Now configure the NLOG File Target looger
            var config     = new LoggingConfiguration();
            var fileTarget = new FileTarget();

            fileTarget.FileName                = fullFileName;
            fileTarget.MaxArchiveFiles         = Maxarchives;
            fileTarget.ArchiveFileName         = $@"{logPath}\Archive\{Path.GetFileNameWithoutExtension(fileName)}.log";
            fileTarget.ArchiveNumbering        = ArchiveNumberingMode.Rolling;
            fileTarget.ArchiveOldFileOnStartup = true;
            fileTarget.KeepFileOpen            = true;
            fileTarget.OpenFileCacheTimeout    = 30;

            fileTarget.Layout = "${date:format=yyyy-MM-dd HH\\:mm\\:ss.ffffff} " +
                                "[${level:fixedLength=true:padding=5}]" +
                                "[${threadid:padding=3}]" +
                                "[${stacktrace:format=Flat:topFrames=1:separator=\":\":fixedLength=true:padding=-30}]: " +
                                "${message} " +
                                "${exception:format=tostring}";

            config.AddTarget("file", fileTarget);

            level = LogLevel.Debug;

            var rule = new LoggingRule("*", ConvertLogLevel(level), fileTarget);

            // Create a filter to disable Raven Database Debugging
            var filter = new ConditionBasedFilter {
                Action = FilterResult.Ignore, Condition = "starts-with('${logger}','Raven')"
            };

            rule.Filters.Add(filter);
            filter = new ConditionBasedFilter {
                Action = FilterResult.Ignore, Condition = "contains('${logger}', 'Rachis')"
            };
            rule.Filters.Add(filter);
            config.LoggingRules.Add(rule);

            LogManager.Configuration = config;

            _logger = LogManager.GetLogger("MPTagThat");
        }
コード例 #4
0
ファイル: Config.cs プロジェクト: PhoenixAki/discord-bot
        private static ILogger GetLog()
        {
            var config     = new NLog.Config.LoggingConfiguration();
            var fileTarget = new FileTarget("logfile")
            {
                FileName             = CurrentLogPath,
                ArchiveEvery         = FileArchivePeriod.Day,
                ArchiveNumbering     = ArchiveNumberingMode.DateAndSequence,
                KeepFileOpen         = true,
                ConcurrentWrites     = false,
                AutoFlush            = false,
                OpenFileFlushTimeout = 1,
                Layout = "${longdate} ${sequenceid:padding=6} ${level:uppercase=true:padding=-5} ${message} ${onexception:" +
                         "${newline}${exception:format=ToString}" +
                         ":when=not contains('${exception:format=ShortType}','TaskCanceledException')}",
            };
            var asyncFileTarget = new AsyncTargetWrapper(fileTarget)
            {
                TimeToSleepBetweenBatches = 0,
                OverflowAction            = AsyncTargetWrapperOverflowAction.Block,
                BatchSize = 500,
            };
            var logTarget = new ColoredConsoleTarget("logconsole")
            {
                Layout = "${longdate} ${level:uppercase=true:padding=-5} ${message} ${onexception:" +
                         "${newline}${exception:format=Message}" +
                         ":when=not contains('${exception:format=ShortType}','TaskCanceledException')}",
            };

#if DEBUG
            config.AddRule(LogLevel.Trace, LogLevel.Fatal, logTarget, "default"); // only echo messages from default logger to the console
#else
            config.AddRule(LogLevel.Info, LogLevel.Fatal, logTarget, "default");
#endif
            config.AddRule(LogLevel.Debug, LogLevel.Fatal, asyncFileTarget);

            var filter = new ConditionBasedFilter {
                Condition = "contains('${message}','TaskCanceledException')", Action = FilterResult.Ignore,
            };
            foreach (var rule in config.LoggingRules)
            {
                rule.Filters.Add(filter);
            }
            LogManager.Configuration = config;
            return(LogManager.GetLogger("default"));
        }
コード例 #5
0
        /// <summary>
        /// To disable logger for other assemblies.
        /// </summary>
        /// <param name="cfg">Configuration of logger</param>
        /// <param name="filter">Custom filter</param>
        protected void fixLoggerCfg(LoggingConfiguration cfg, ConditionBasedFilter filter)
        {
            if (cfg == null)
            {
                return;
            }

            LoggingRule rule = cfg.LoggingRules.FirstOrDefault(p => p.LoggerNamePattern == "*");

            if (rule == null)
            {
                return;
            }

            if (!rule.Filters.Contains(filter))
            {
                rule.Filters.Add(filter);
            }
        }
コード例 #6
0
        public void CustomFilter()
        {
            var filter = new ConditionBasedFilter();

            filter.Condition = "starts-with('${message}','badCategory')";
            filter.Action    = FilterResult.Ignore;

            FakeAWSTarget fakeawsTarget = new FakeAWSTarget();
            var           config        = new LoggingConfiguration();

            config.AddTarget("FakeAWSTarget", fakeawsTarget);

            var rule = new LoggingRule("CustomFilter", LogLevel.Warn, LogLevel.Fatal, fakeawsTarget);

            rule.Filters.Add(filter);

            config.LoggingRules.Add(rule);

            LogManager.Configuration = config;

            var logger = LogManager.GetLogger("CustomFilter");

            logger.Trace("goodCategory|trace");
            logger.Fatal("goodCategory|fatal");

            Assert.Single(fakeawsTarget._core.ReceivedMessages);
            Assert.Contains("fatal", fakeawsTarget._core.ReceivedMessages.ElementAt(0));

            string val;

            while (!fakeawsTarget._core.ReceivedMessages.IsEmpty)
            {
                fakeawsTarget._core.ReceivedMessages.TryDequeue(out val);
            }

            logger.Trace("badCategory|trace");
            logger.Warn("badCategory|warning");

            Assert.Empty(fakeawsTarget._core.ReceivedMessages);
        }