EnableLoggingForLevel() public method

Enables logging for a particular level.
public EnableLoggingForLevel ( NLog.LogLevel level ) : void
level NLog.LogLevel Level to be enabled.
return void
Esempio n. 1
0
        /// <summary>
        /// Add a rule for one loglevel.
        /// </summary>
        /// <param name="level">log level needed to trigger this rule. </param>
        /// <param name="target">Target to be written to when the rule matches.</param>
        /// <param name="loggerNamePattern">Logger name pattern. It may include the '*' wildcard at the beginning, at the end or at both ends.</param>
        public void AddRuleForOneLevel(LogLevel level, Target target, string loggerNamePattern = "*")
        {
            var loggingRule = new LoggingRule(loggerNamePattern, target);

            loggingRule.EnableLoggingForLevel(level);
            LoggingRules.Add(loggingRule);
        }
Esempio n. 2
0
        public static void EnableDebugConsoleOutput()
        {
            if (IsDebugConsoleOutputEnabled) {
                return;
            }

            LoggingConfiguration config = LogManager.Configuration;
            ConsoleTarget consoleTarget = new ConsoleTarget() { Name = "consoleDebugOutput" };
            LoggingRule consoleRule = new LoggingRule("*", consoleTarget);

            consoleRule.EnableLoggingForLevel(LogLevel.Trace);
            consoleRule.EnableLoggingForLevel(LogLevel.Debug);
            config.AddTarget(consoleTarget);
            config.LoggingRules.Add(consoleRule);
            IsDebugConsoleOutputEnabled = true;
        }
Esempio n. 3
0
        /// <summary>
        /// Add a rule for one loglevel.
        /// </summary>
        /// <param name="level">log level needed to trigger this rule. </param>
        /// <param name="target">Target to be written to when the rule matches.</param>
        /// <param name="loggerNamePattern">Logger name pattern. It may include the '*' wildcard at the beginning, at the end or at both ends.</param>
        public void AddRuleForOneLevel(LogLevel level, Target target, string loggerNamePattern = "*")
        {
            if (target == null)
            {
                throw new ArgumentNullException(nameof(target));
            }
            var loggingRule = new LoggingRule(loggerNamePattern, target);

            loggingRule.EnableLoggingForLevel(level);
            AddLoggingRulesThreadSafe(loggingRule);
        }
Esempio n. 4
0
        private static void ConfigureLogging(bool enableVerboseLogging)
        {
            var config = new LoggingConfiguration();

            var consoleTarget = new ColoredConsoleTarget();
            config.AddTarget("console", consoleTarget);

            consoleTarget.Layout = "> ${message}";

            var rule1 = new LoggingRule("*", LogLevel.Info, consoleTarget);

            if (enableVerboseLogging)
            {
                rule1.EnableLoggingForLevel(LogLevel.Trace);
                rule1.EnableLoggingForLevel(LogLevel.Debug);
            }

            config.LoggingRules.Add(rule1);

            LogManager.Configuration = config;
        }
Esempio n. 5
0
 private static void ChangeRuleMinLevel(LoggingRule rule, LogLevel minLevel)
 {
     /*
      * Based on how the LoggingLevel initializes its logging levels when given a minLevel,
      * but because LogLevel.MinLevel and LogLevel.MaxLevel are not publically accessible,
      * their current values are hardcoded. TODO: This is fragile!
      */
     for (var i = LogLevel.Trace.Ordinal; i < minLevel.Ordinal; i++)
     {
         rule.DisableLoggingForLevel(LogLevel.FromOrdinal(i));
     }
     for (var i = minLevel.Ordinal; i <= LogLevel.Fatal.Ordinal; i++)
     {
         rule.EnableLoggingForLevel(LogLevel.FromOrdinal(i));
     }
     LogManager.ReconfigExistingLoggers();
 }
        /// <summary>
        /// Parse {Logger} xml element
        /// </summary>
        /// <param name="loggerElement"></param>
        /// <param name="rulesCollection">Rules are added to this parameter.</param>
        private void ParseLoggerElement(NLogXmlElement loggerElement, IList <LoggingRule> rulesCollection)
        {
            loggerElement.AssertName("logger");

            var namePattern = loggerElement.GetOptionalAttribute("name", "*");
            var enabled     = loggerElement.GetOptionalBooleanAttribute("enabled", true);

            if (!enabled)
            {
                InternalLogger.Debug("The logger named '{0}' are disabled");
                return;
            }

            var    rule     = new LoggingRule();
            string appendTo = loggerElement.GetOptionalAttribute("appendTo", null);

            if (appendTo == null)
            {
                appendTo = loggerElement.GetOptionalAttribute("writeTo", null);
            }

            rule.LoggerNamePattern = namePattern;
            if (appendTo != null)
            {
                foreach (string t in appendTo.Split(','))
                {
                    string targetName = t.Trim();
                    Target target     = FindTargetByName(targetName);

                    if (target != null)
                    {
                        rule.Targets.Add(target);
                    }
                    else
                    {
                        throw new NLogConfigurationException("Target " + targetName + " not found.");
                    }
                }
            }

            rule.Final = loggerElement.GetOptionalBooleanAttribute("final", false);

            string levelString;

            if (loggerElement.AttributeValues.TryGetValue("level", out levelString))
            {
                LogLevel level = LogLevel.FromString(levelString);
                rule.EnableLoggingForLevel(level);
            }
            else if (loggerElement.AttributeValues.TryGetValue("levels", out levelString))
            {
                levelString = CleanSpaces(levelString);

                string[] tokens = levelString.Split(',');
                foreach (string token in tokens)
                {
                    if (!string.IsNullOrEmpty(token))
                    {
                        LogLevel level = LogLevel.FromString(token);
                        rule.EnableLoggingForLevel(level);
                    }
                }
            }
            else
            {
                int    minLevel = 0;
                int    maxLevel = LogLevel.MaxLevel.Ordinal;
                string minLevelString;
                string maxLevelString;

                if (loggerElement.AttributeValues.TryGetValue("minLevel", out minLevelString))
                {
                    minLevel = LogLevel.FromString(minLevelString).Ordinal;
                }

                if (loggerElement.AttributeValues.TryGetValue("maxLevel", out maxLevelString))
                {
                    maxLevel = LogLevel.FromString(maxLevelString).Ordinal;
                }

                for (int i = minLevel; i <= maxLevel; ++i)
                {
                    rule.EnableLoggingForLevel(LogLevel.FromOrdinal(i));
                }
            }

            var children = loggerElement.Children.ToList();

            foreach (var child in children)
            {
                switch (child.LocalName.ToUpper(CultureInfo.InvariantCulture))
                {
                case "FILTERS":
                    this.ParseFilters(rule, child);
                    break;

                case "LOGGER":
                    this.ParseLoggerElement(child, rule.ChildRules);
                    break;
                }
            }

            rulesCollection.Add(rule);
        }
Esempio n. 7
0
        private void ConfigureRulesFromElement(LoggingConfiguration config, LoggingRuleCollection rules, XmlElement element)
        {
            if (element == null)
            {
                return;
            }

            foreach (XmlElement el in PropertyHelper.GetChildElements(element, "logger"))
            {
                XmlElement ruleElement = el;

                LoggingRule rule        = new LoggingRule();
                string      namePattern = GetCaseInsensitiveAttribute(ruleElement, "name");
                if (namePattern == null)
                {
                    namePattern = "*";
                }

                string appendTo = GetCaseInsensitiveAttribute(ruleElement, "appendTo");
                if (appendTo == null)
                {
                    appendTo = GetCaseInsensitiveAttribute(ruleElement, "writeTo");
                }

                rule.LoggerNamePattern = namePattern;
                if (appendTo != null)
                {
                    foreach (string t in appendTo.Split(','))
                    {
                        string targetName = t.Trim();
                        Target target     = config.FindTargetByName(targetName);

                        if (target != null)
                        {
                            rule.Targets.Add(target);
                        }
                        else
                        {
                            throw new NLogConfigurationException("Target " + targetName + " not found.");
                        }
                    }
                }
                rule.Final = false;

                if (HasCaseInsensitiveAttribute(ruleElement, "final"))
                {
                    rule.Final = true;
                }

                if (HasCaseInsensitiveAttribute(ruleElement, "level"))
                {
                    LogLevel level = LogLevel.FromString(GetCaseInsensitiveAttribute(ruleElement, "level"));
                    rule.EnableLoggingForLevel(level);
                }
                else if (HasCaseInsensitiveAttribute(ruleElement, "levels"))
                {
                    string levelsString = GetCaseInsensitiveAttribute(ruleElement, "levels");
                    levelsString = CleanWhitespace(levelsString);

                    string[] tokens = levelsString.Split(',');
                    foreach (string s in tokens)
                    {
                        if (s != "")
                        {
                            LogLevel level = LogLevel.FromString(s);
                            rule.EnableLoggingForLevel(level);
                        }
                    }
                }
                else
                {
                    int minLevel = 0;
                    int maxLevel = LogLevel.MaxLevel.Ordinal;

                    if (HasCaseInsensitiveAttribute(ruleElement, "minlevel"))
                    {
                        minLevel = LogLevel.FromString(GetCaseInsensitiveAttribute(ruleElement, "minlevel")).Ordinal;
                    }

                    if (HasCaseInsensitiveAttribute(ruleElement, "maxlevel"))
                    {
                        maxLevel = LogLevel.FromString(GetCaseInsensitiveAttribute(ruleElement, "maxlevel")).Ordinal;
                    }

                    for (int i = minLevel; i <= maxLevel; ++i)
                    {
                        rule.EnableLoggingForLevel(LogLevel.FromOrdinal(i));
                    }
                }

                foreach (XmlElement el2 in PropertyHelper.GetChildElements(ruleElement, "filters"))
                {
                    ConfigureRuleFiltersFromXmlElement(rule, el2);
                }

                ConfigureRulesFromElement(config, rule.ChildRules, ruleElement);

                rules.Add(rule);
            }
        }
Esempio n. 8
0
        /// <summary>
        /// Parse {Logger} xml element
        /// </summary>
        /// <param name="loggerElement"></param>
        /// <param name="rulesCollection">Rules are added to this parameter.</param>
        private void ParseLoggerElement(NLogXmlElement loggerElement, IList<LoggingRule> rulesCollection)
        {
            loggerElement.AssertName("logger");

            var namePattern = loggerElement.GetOptionalAttribute("name", "*");
            var enabled = loggerElement.GetOptionalBooleanAttribute("enabled", true);
            if (!enabled)
            {
                InternalLogger.Debug("The logger named '{0}' are disabled");
                return;
            }

            var rule = new LoggingRule();
            string appendTo = loggerElement.GetOptionalAttribute("appendTo", null);
            if (appendTo == null)
            {
                appendTo = loggerElement.GetOptionalAttribute("writeTo", null);
            }

            rule.LoggerNamePattern = namePattern;
            if (appendTo != null)
            {
                foreach (string t in appendTo.Split(','))
                {
                    string targetName = t.Trim();
                    Target target = FindTargetByName(targetName);

                    if (target != null)
                    {
                        rule.Targets.Add(target);
                    }
                    else
                    {
                        throw new NLogConfigurationException("Target " + targetName + " not found.");
                    }
                }
            }

            rule.Final = loggerElement.GetOptionalBooleanAttribute("final", false);

            string levelString;

            if (loggerElement.AttributeValues.TryGetValue("level", out levelString))
            {
                LogLevel level = LogLevel.FromString(levelString);
                rule.EnableLoggingForLevel(level);
            }
            else if (loggerElement.AttributeValues.TryGetValue("levels", out levelString))
            {
                levelString = CleanSpaces(levelString);

                string[] tokens = levelString.Split(',');
                foreach (string s in tokens)
                {
                    if (!string.IsNullOrEmpty(s))
                    {
                        LogLevel level = LogLevel.FromString(s);
                        rule.EnableLoggingForLevel(level);
                    }
                }
            }
            else
            {
                int minLevel = 0;
                int maxLevel = LogLevel.MaxLevel.Ordinal;
                string minLevelString;
                string maxLevelString;

                if (loggerElement.AttributeValues.TryGetValue("minLevel", out minLevelString))
                {
                    minLevel = LogLevel.FromString(minLevelString).Ordinal;
                }

                if (loggerElement.AttributeValues.TryGetValue("maxLevel", out maxLevelString))
                {
                    maxLevel = LogLevel.FromString(maxLevelString).Ordinal;
                }

                for (int i = minLevel; i <= maxLevel; ++i)
                {
                    rule.EnableLoggingForLevel(LogLevel.FromOrdinal(i));
                }
            }

            foreach (var child in loggerElement.Children)
            {
                switch (child.LocalName.ToUpper(CultureInfo.InvariantCulture))
                {
                    case "FILTERS":
                        this.ParseFilters(rule, child);
                        break;

                    case "LOGGER":
                        this.ParseLoggerElement(child, rule.ChildRules);
                        break;
                }
            }

            rulesCollection.Add(rule);
        }
Esempio n. 9
0
        private void ParseLoggerElement(XmlReader reader, ICollection<LoggingRule> rulesCollection)
        {
            LoggingRule rule = new LoggingRule();
            string namePattern = this.GetCaseInsensitiveAttribute(reader, "name", "*");
            string appendTo = this.GetCaseInsensitiveAttribute(reader, "appendTo", null);
            if (appendTo == null)
            {
                appendTo = this.GetCaseInsensitiveAttribute(reader, "writeTo", null);
            }

            rule.LoggerNamePattern = namePattern;
            if (appendTo != null)
            {
                foreach (string t in appendTo.Split(','))
                {
                    string targetName = t.Trim();
                    Target target = FindTargetByName(targetName);

                    if (target != null)
                    {
                        rule.Targets.Add(target);
                    }
                    else
                    {
                        throw new NLogConfigurationException("Target " + targetName + " not found.");
                    }
                }
            }

            rule.Final = false;

            if (this.GetCaseInsensitiveAttribute(reader, "final", "false") == "true")
            {
                rule.Final = true;
            }

            string levelString;

            if (this.TryGetCaseInsensitiveAttribute(reader, "level", out levelString))
            {
                LogLevel level = LogLevel.FromString(levelString);
                rule.EnableLoggingForLevel(level);
            }
            else if (this.TryGetCaseInsensitiveAttribute(reader, "levels", out levelString))
            {
                levelString = this.CleanWhitespace(levelString);

                string[] tokens = levelString.Split(',');
                foreach (string s in tokens)
                {
                    if (!string.IsNullOrEmpty(s))
                    {
                        LogLevel level = LogLevel.FromString(s);
                        rule.EnableLoggingForLevel(level);
                    }
                }
            }
            else
            {
                int minLevel = 0;
                int maxLevel = LogLevel.MaxLevel.Ordinal;
                string minLevelString;
                string maxLevelString;

                if (this.TryGetCaseInsensitiveAttribute(reader, "minLevel", out minLevelString))
                {
                    minLevel = LogLevel.FromString(minLevelString).Ordinal;
                }

                if (this.TryGetCaseInsensitiveAttribute(reader, "maxLevel", out maxLevelString))
                {
                    maxLevel = LogLevel.FromString(maxLevelString).Ordinal;
                }

                for (int i = minLevel; i <= maxLevel; ++i)
                {
                    rule.EnableLoggingForLevel(LogLevel.FromOrdinal(i));
                }
            }

            if (!reader.IsEmptyElement)
            {
                while (this.MoveToNextElement(reader))
                {
                    switch (reader.LocalName.ToLower(CultureInfo.InvariantCulture))
                    {
                        case "filters":
                            this.ParseFilters(rule, reader);
                            break;

                        case "logger":
                            this.ParseLoggerElement(reader, rule.ChildRules);
                            break;

                        default:
                            reader.Skip();
                            break;
                    }
                }
            }

            rulesCollection.Add(rule);
        }
Esempio n. 10
0
        private void SetLogLevelForRule(LoggingRule rule, LogLevel activeLogLevel)
        {
            // Reset all log levels to off
            for (int i = MinLogLevel; i <= MaxLogLevel; i++)
            {
                rule.DisableLoggingForLevel(LogLevel.FromOrdinal(i));
            }

            // Enable the active log level and all levels numerically higher
            for (int i = activeLogLevel.GetHashCode(); i <= MaxLogLevel; i++)
            {
                rule.EnableLoggingForLevel(LogLevel.FromOrdinal(i));
            }

            InternalLogger.Debug("*** Setting active log level for " + _logger.Name + " to " + activeLogLevel.Name);
        }
Esempio n. 11
0
        public static void EnableWarningLogging()
        {
            if (IsWarningLoggingEnabled) {
                return;
            }

            LoggingConfiguration config = LogManager.Configuration;
            FileTarget warningTarget = new FileTarget() {
                Name = "fileWarnings",
                Layout = "${longdate} | ${level:uppercase=true} | ${logger} | ${message}",
                FileName = BaseLogDirectory + @"\Warning\warning.log",
                ArchiveFileName = BaseLogDirectory + @"\MobiBot\Warning\warning.{###}.txt",
                ArchiveEvery = FileArchivePeriod.Day,
                ArchiveNumbering = ArchiveNumberingMode.Rolling,
                MaxArchiveFiles = 30,
                NetworkWrites = true,
                KeepFileOpen = true
            };
            LoggingRule warningRule = new LoggingRule("*", warningTarget);

            warningRule.EnableLoggingForLevel(LogLevel.Warn);
            config.AddTarget(warningTarget);
            config.LoggingRules.Add(warningRule);
            IsWarningLoggingEnabled = true;
        }
Esempio n. 12
0
        private void ApplyLogLevel(LoggingRule rule, IList<LogLevel> levels)
        {
            foreach (var level in rule.Levels)
                rule.DisableLoggingForLevel(level);

            foreach (var level in levels)
                rule.EnableLoggingForLevel(level);
        }
Esempio n. 13
0
        void MvcApplication_BeginRequest(object sender, EventArgs e)
        {
            try
            {
                if (HttpContext.Current.Request.QueryString["vm"] != null && Convert.ToInt32(HttpContext.Current.Request.QueryString["vm"]) == 10)
                {
                    MemoryTarget _logTarget = null;
                    _loggerName = Guid.NewGuid().ToString().Replace("-", string.Empty);
                    HttpContext.Current.Items.Add("LoggerName", _loggerName);
                    _logTarget = new MemoryTarget();
                    _logTarget.Name = _loggerName.ToString();

                    LoggingRule rule = new LoggingRule(_loggerName, _logTarget);
                    rule.EnableLoggingForLevel(LogLevel.Debug);
                    rule.EnableLoggingForLevel(LogLevel.Trace);
                    rule.EnableLoggingForLevel(LogLevel.Info);
                    rule.EnableLoggingForLevel(LogLevel.Warn);
                    rule.EnableLoggingForLevel(LogLevel.Error);
                    rule.EnableLoggingForLevel(LogLevel.Fatal);

                    LogManager.Configuration.LoggingRules.Add(rule);

                    LogManager.Configuration.Reload();
                }
            }
            catch (Exception ex)
            {
                LogEventInfo info = new LogEventInfo(LogLevel.Error, ECMSSettings.DEFAULT_LOGGER, ex.ToString());
                ECMSLogger.Instance.Log(info);
            }
        }