/// <summary>
        /// Gets the optional boolean attribute value.
        /// </summary>
        /// <param name="element"></param>
        /// <param name="attributeName">Name of the attribute.</param>
        /// <param name="defaultValue">Default value to return if the attribute is not found or if there is a parse error</param>
        /// <returns>Boolean attribute value or default.</returns>
        public static bool GetOptionalBooleanValue(this ILoggingConfigurationElement element, string attributeName,
                                                   bool defaultValue)
        {
            string value = element.GetOptionalValue(attributeName, null);

            if (string.IsNullOrEmpty(value))
            {
                return(defaultValue);
            }

            try
            {
                return(Convert.ToBoolean(value.Trim(), CultureInfo.InvariantCulture));
            }
            catch (Exception exception)
            {
                var configException = new NLogConfigurationException(exception, $"'{attributeName}' hasn't a valid boolean value '{value}'. {defaultValue} will be used");
                if (configException.MustBeRethrown())
                {
                    throw configException;
                }
                InternalLogger.Error(exception, configException.Message);
                return(defaultValue);
            }
        }
Пример #2
0
        /// <summary>
        /// Parse {NLog} xml element.
        /// </summary>
        /// <param name="nlogElement"></param>
        /// <param name="filePath">path to config file.</param>
        /// <param name="autoReloadDefault">The default value for the autoReload option.</param>
        private void ParseNLogElement(ILoggingConfigurationElement nlogElement, [CanBeNull] string filePath, bool autoReloadDefault)
        {
            InternalLogger.Trace("ParseNLogElement");
            nlogElement.AssertName("nlog");

            bool autoReload = nlogElement.GetOptionalBooleanValue("autoReload", autoReloadDefault);

            try
            {
                string baseDirectory = null;
                if (!string.IsNullOrEmpty(filePath))
                {
                    _fileMustAutoReloadLookup[GetFileLookupKey(filePath)] = autoReload;
                    _currentFilePath.Push(filePath);
                    baseDirectory = Path.GetDirectoryName(filePath);
                }
                base.LoadConfig(nlogElement, baseDirectory);
            }
            finally
            {
                if (!string.IsNullOrEmpty(filePath))
                {
                    _currentFilePath.Pop();
                }
            }
        }
Пример #3
0
        private void ParseIncludeElement(ILoggingConfigurationElement includeElement, string baseDirectory, bool autoReloadDefault)
        {
            includeElement.AssertName("include");

            string newFileName = includeElement.GetRequiredValue("file", "nlog");

            var ignoreErrors = includeElement.GetOptionalBooleanValue("ignoreErrors", false);

            try
            {
                newFileName = ExpandSimpleVariables(newFileName);
                newFileName = SimpleLayout.Evaluate(newFileName);
                var fullNewFileName = newFileName;
                if (baseDirectory != null)
                {
                    fullNewFileName = Path.Combine(baseDirectory, newFileName);
                }

                if (File.Exists(fullNewFileName))
                {
                    InternalLogger.Debug("Including file '{0}'", fullNewFileName);
                    ConfigureFromFile(fullNewFileName, autoReloadDefault);
                }
                else
                {
                    //is mask?

                    if (newFileName.Contains("*"))
                    {
                        ConfigureFromFilesByMask(baseDirectory, newFileName, autoReloadDefault);
                    }
                    else
                    {
                        if (ignoreErrors)
                        {
                            //quick stop for performances
                            InternalLogger.Debug("Skipping included file '{0}' as it can't be found", fullNewFileName);
                            return;
                        }

                        throw new FileNotFoundException("Included file not found: " + fullNewFileName);
                    }
                }
            }
            catch (Exception exception)
            {
                if (exception.MustBeRethrownImmediately())
                {
                    throw;
                }

                var configurationException = new NLogConfigurationException(exception, "Error when including '{0}'.", newFileName);
                InternalLogger.Error(exception, configurationException.Message);
                if (!ignoreErrors)
                {
                    throw configurationException;
                }
            }
        }
        public static void AssertName(this ILoggingConfigurationElement section, params string[] allowedNames)
        {
            foreach (var en in allowedNames)
            {
                if (section.MatchesName(en))
                {
                    return;
                }
            }

            throw new InvalidOperationException(
                      $"Assertion failed. Expected element name '{string.Join("|", allowedNames)}', actual: '{section?.Name}'.");
        }
Пример #5
0
 /// <summary>
 /// Parses a single config section within the NLog-config
 /// </summary>
 /// <param name="configSection"></param>
 /// <returns>Section was recognized</returns>
 protected override bool ParseNLogSection(ILoggingConfigurationElement configSection)
 {
     if (configSection.MatchesName("include"))
     {
         string filePath = _currentFilePath.Peek();
         bool   autoLoad = !string.IsNullOrEmpty(filePath) && _fileMustAutoReloadLookup[GetFileLookupKey(filePath)];
         ParseIncludeElement(configSection, !string.IsNullOrEmpty(filePath) ? Path.GetDirectoryName(filePath) : null, autoLoad);
         return(true);
     }
     else
     {
         return(base.ParseNLogSection(configSection));
     }
 }
        public static string GetOptionalValue(this ILoggingConfigurationElement element, string attributeName,
                                              string defaultValue)
        {
            string value = element.Values
                           .Where(configItem => string.Equals(configItem.Key, attributeName, StringComparison.OrdinalIgnoreCase))
                           .Select(configItem => configItem.Value).FirstOrDefault();

            if (value == null)
            {
                return(defaultValue);
            }

            return(value);
        }
        public static string GetRequiredValue(this ILoggingConfigurationElement element, string attributeName, string section)
        {
            string value = element.GetOptionalValue(attributeName, null);

            if (value == null)
            {
                throw new NLogConfigurationException($"Expected {attributeName} on {element.Name} in {section}");
            }

            if (StringHelpers.IsNullOrWhiteSpace(value))
            {
                throw new NLogConfigurationException(
                          $"Expected non-empty {attributeName} on {element.Name} in {section}");
            }

            return(value);
        }
Пример #8
0
        /// <summary>
        /// Parse {NLog} xml element.
        /// </summary>
        /// <param name="nlogElement"></param>
        /// <param name="filePath">path to config file.</param>
        /// <param name="autoReloadDefault">The default value for the autoReload option.</param>
        private void ParseNLogElement(ILoggingConfigurationElement nlogElement, string filePath, bool autoReloadDefault)
        {
            InternalLogger.Trace("ParseNLogElement");
            nlogElement.AssertName("nlog");

            bool autoReload = nlogElement.GetOptionalBooleanValue("autoReload", autoReloadDefault);

            if (filePath != null)
            {
                _fileMustAutoReloadLookup[GetFileLookupKey(filePath)] = autoReload;
            }

            try
            {
                _currentFilePath.Push(filePath);
                base.LoadConfig(nlogElement, Path.GetDirectoryName(filePath));
            }
            finally
            {
                _currentFilePath.Pop();
            }
        }
 public static bool MatchesName(this ILoggingConfigurationElement section, string expectedName)
 {
     return(string.Equals(section?.Name?.Trim(), expectedName, StringComparison.OrdinalIgnoreCase));
 }
        public static string GetConfigItemTypeAttribute(this ILoggingConfigurationElement element, string sectionNameForRequiredValue = null)
        {
            var typeAttributeValue = sectionNameForRequiredValue != null?element.GetRequiredValue("type", sectionNameForRequiredValue) : element.GetOptionalValue("type", null);

            return(StripOptionalNamespacePrefix(typeAttributeValue)?.Trim());
        }
Пример #11
0
        private void ParseIncludeElement(ILoggingConfigurationElement includeElement, string baseDirectory, bool autoReloadDefault)
        {
            includeElement.AssertName("include");

            string newFileName = includeElement.GetRequiredValue("file", "nlog");

            var ignoreErrors = includeElement.GetOptionalBooleanValue("ignoreErrors", false);

            try
            {
                newFileName = ExpandSimpleVariables(newFileName);
                newFileName = SimpleLayout.Evaluate(newFileName);
                var fullNewFileName = newFileName;
                if (baseDirectory != null)
                {
                    fullNewFileName = Path.Combine(baseDirectory, newFileName);
                }

#if SILVERLIGHT && !WINDOWS_PHONE
                newFileName = newFileName.Replace("\\", "/");
                if (Application.GetResourceStream(new Uri(fullNewFileName, UriKind.Relative)) != null)
#else
                if (File.Exists(fullNewFileName))
#endif
                {
                    InternalLogger.Debug("Including file '{0}'", fullNewFileName);
                    ConfigureFromFile(fullNewFileName, autoReloadDefault);
                }
                else
                {
                    //is mask?

                    if (newFileName.Contains("*"))
                    {
                        ConfigureFromFilesByMask(baseDirectory, newFileName, autoReloadDefault);
                    }
                    else
                    {
                        if (ignoreErrors)
                        {
                            //quick stop for performances
                            InternalLogger.Debug("Skipping included file '{0}' as it can't be found", fullNewFileName);
                            return;
                        }

                        throw new FileNotFoundException("Included file not found: " + fullNewFileName);
                    }
                }
            }
            catch (Exception exception)
            {
                InternalLogger.Error(exception, "Error when including '{0}'.", newFileName);

                if (ignoreErrors)
                {
                    return;
                }

                if (exception.MustBeRethrown())
                {
                    throw;
                }

                throw new NLogConfigurationException("Error when including: " + newFileName, exception);
            }
        }