/// <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);
            }
        }
Exemple #2
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;
                }
            }
        }
        /// <summary>
        /// Initializes the configuration.
        /// </summary>
        /// <param name="reader"><see cref="XmlReader"/> containing the configuration section.</param>
        /// <param name="fileName">Name of the file that contains the element (to be used as a base for including other files).</param>
        /// <param name="ignoreErrors">Ignore any errors during configuration.</param>
        private void Initialize(XmlReader reader, string fileName, bool ignoreErrors)
        {
            try
            {
                InitializeSucceeded = null;
                reader.MoveToContent();
                var content = new NLogXmlElement(reader);
                if (fileName != null)
                {
#if SILVERLIGHT
                    string key = fileName;
#else
                    string key = Path.GetFullPath(fileName);
#endif
                    this.visitedFile[key] = true;

                    this.originalFileName = fileName;
                    this.ParseTopLevel(content, Path.GetDirectoryName(fileName));

                    InternalLogger.Info("Configured from an XML element in {0}...", fileName);
                }
                else
                {
                    this.ParseTopLevel(content, null);
                }
                InitializeSucceeded = true;

                this.CheckUnusedTargets();
            }
            catch (Exception exception)
            {
                InitializeSucceeded = false;
                if (exception.MustBeRethrown())
                {
                    throw;
                }

                NLogConfigurationException ConfigException = new NLogConfigurationException("Exception occurred when loading configuration from " + fileName, exception);

                if (!ignoreErrors)
                {
                    if (LogManager.ThrowExceptions)
                    {
                        throw ConfigException;
                    }
                    else
                    {
                        InternalLogger.Error("Error in Parsing Configuration File. Exception : {0}", ConfigException);
                    }
                }
                else
                {
                    InternalLogger.Error("Error in Parsing Configuration File. Exception : {0}", ConfigException);
                }
            }
        }
        /// <summary>
        /// Initializes the configuration.
        /// </summary>
        /// <param name="reader"><see cref="XmlReader"/> containing the configuration section.</param>
        /// <param name="fileName">Name of the file that contains the element (to be used as a base for including other files).</param>
        /// <param name="ignoreErrors">Ignore any errors during configuration.</param>
        private void Initialize(XmlReader reader, string fileName, bool ignoreErrors)
        {
            try
            {
                InitializeSucceeded = null;
                reader.MoveToContent();
                var content = new NLogXmlElement(reader);
                if (fileName != null)
                {
                    this.originalFileName = fileName;
                    this.ParseTopLevel(content, fileName, autoReloadDefault: false);

                    InternalLogger.Info("Configured from an XML element in {0}...", fileName);
                }
                else
                {
                    this.ParseTopLevel(content, null, autoReloadDefault: false);
                }
                InitializeSucceeded = true;

                // Automatically reconfigure existing pools as soon as the configuration has been loaded
                this.PoolConfiguration.ReconfigurePools(this.PoolFactory);

                this.CheckUnusedTargets();
            }
            catch (Exception exception)
            {
                InitializeSucceeded = false;
                if (exception.MustBeRethrownImmediately())
                {
                    throw;
                }

                var configurationException = new NLogConfigurationException("Exception occurred when loading configuration from " + fileName, exception);
                InternalLogger.Error(configurationException, "Error in Parsing Configuration File.");

                if (!ignoreErrors)
                {
                    if (exception.MustBeRethrown())
                    {
                        throw configurationException;
                    }
                }
            }
        }
Exemple #5
0
        /// <summary>
        /// Initializes the configuration.
        /// </summary>
        /// <param name="reader"><see cref="XmlReader"/> containing the configuration section.</param>
        /// <param name="fileName">Name of the file that contains the element (to be used as a base for including other files).</param>
        /// <param name="ignoreErrors">Ignore any errors during configuration.</param>
        private void Initialize([NotNull] XmlReader reader, [CanBeNull] string fileName, bool ignoreErrors)
        {
            try
            {
                InitializeSucceeded = null;
                _originalFileName   = fileName;
                reader.MoveToContent();
                var content = new NLogXmlElement(reader);
                if (!string.IsNullOrEmpty(fileName))
                {
                    InternalLogger.Info("Configuring from an XML element in {0}...", fileName);
                    ParseTopLevel(content, fileName, autoReloadDefault: false);
                }
                else
                {
                    ParseTopLevel(content, null, autoReloadDefault: false);
                }
                InitializeSucceeded = true;
                CheckParsingErrors(content);
                base.CheckUnusedTargets();
            }
            catch (Exception exception)
            {
                InitializeSucceeded = false;
                if (exception.MustBeRethrownImmediately())
                {
                    throw;
                }

                var configurationException = new NLogConfigurationException(exception, "Exception when parsing {0}. ", fileName);
                InternalLogger.Error(configurationException, "Parsing configuration from {0} failed.", fileName);

                if (!ignoreErrors && configurationException.MustBeRethrown())
                {
                    throw configurationException;
                }
            }
        }
Exemple #6
0
        /// <summary>
        /// Initializes the configuration.
        /// </summary>
        /// <param name="reader"><see cref="XmlReader"/> containing the configuration section.</param>
        /// <param name="fileName">Name of the file that contains the element (to be used as a base for including other files). <c>null</c> is allowed.</param>
        /// <param name="ignoreErrors">Ignore any errors during configuration.</param>
        private void Initialize([NotNull] XmlReader reader, [CanBeNull] string fileName, bool ignoreErrors = false)
        {
            try
            {
                InitializeSucceeded = null;
                _originalFileName   = fileName;
                reader.MoveToContent();
                var content = new NLogXmlElement(reader);
                if (!string.IsNullOrEmpty(fileName))
                {
                    InternalLogger.Info("Configuring from an XML element in {0}...", fileName);
                    ParseTopLevel(content, fileName, autoReloadDefault: false);
                }
                else
                {
                    ParseTopLevel(content, null, autoReloadDefault: false);
                }
                InitializeSucceeded = true;
            }
            catch (Exception exception)
            {
                InitializeSucceeded = false;

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

                var configurationException = new NLogConfigurationException(exception, "Exception when loading configuration {0}", fileName);
                InternalLogger.Error(exception, configurationException.Message);
                if (!ignoreErrors && (LogFactory.ThrowConfigExceptions ?? LogFactory.ThrowExceptions || configurationException.MustBeRethrown()))
                {
                    throw configurationException;
                }
            }
        }
        /// <summary>
        /// Initializes the configuration.
        /// </summary>
        /// <param name="reader"><see cref="XmlReader"/> containing the configuration section.</param>
        /// <param name="fileName">Name of the file that contains the element (to be used as a base for including other files).</param>
        /// <param name="ignoreErrors">Ignore any errors during configuration.</param>
        private void Initialize(XmlReader reader, string fileName, bool ignoreErrors)
        {
            try
            {
                InitializeSucceeded = null;
                reader.MoveToContent();
                var content = new NLogXmlElement(reader);
                if (fileName != null)
                {
                    this.originalFileName = fileName;
                    this.ParseTopLevel(content, fileName, autoReloadDefault: false);

                    InternalLogger.Info("Configured from an XML element in {0}...", fileName);
                }
                else
                {
                    this.ParseTopLevel(content, null, autoReloadDefault: false);
                }
                InitializeSucceeded = true;

                this.CheckUnusedTargets();

            }
            catch (Exception exception)
            {
                InitializeSucceeded = false;
                if (exception.MustBeRethrown())
                {
                    throw;
                }

                NLogConfigurationException ConfigException = new NLogConfigurationException("Exception occurred when loading configuration from " + fileName, exception);

                if (!ignoreErrors)
                {
                    if (LogManager.ThrowExceptions)
                    {
                        throw ConfigException;
                    }
                    else
                    {
                        InternalLogger.Error("Error in Parsing Configuration File. Exception : {0}", ConfigException);
                    }
                }
                else
                {
                    InternalLogger.Error("Error in Parsing Configuration File. Exception : {0}", ConfigException);
                }
            }
        }
        private void ParseExtensionsElement(NLogXmlElement extensionsElement, string baseDirectory)
        {
            extensionsElement.AssertName("extensions");

            var addElements = extensionsElement.Elements("add").ToList();
            foreach (var addElement in addElements)
            {
                string prefix = addElement.GetOptionalAttribute("prefix", null);

                if (prefix != null)
                {
                    prefix = prefix + ".";
                }

                string type = StripOptionalNamespacePrefix(addElement.GetOptionalAttribute("type", null));
                if (type != null)
                {
                    try
                    {
                        this.ConfigurationItemFactory.RegisterType(Type.GetType(type, true), prefix);
                    }
                    catch (Exception exception)
                    {
                        if (exception.MustBeRethrownImmediately())
                        {
                            throw;
                        }

                        InternalLogger.Error(exception, "Error loading extensions.");
                        NLogConfigurationException configException =
                            new NLogConfigurationException("Error loading extensions: " + type, exception);

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

                string assemblyFile = addElement.GetOptionalAttribute("assemblyFile", null);
                if (assemblyFile != null)
                {
                    try
                    {
#if SILVERLIGHT && !WINDOWS_PHONE
                    var si = Application.GetResourceStream(new Uri(assemblyFile, UriKind.Relative));
                    var assemblyPart = new AssemblyPart();
                    Assembly asm = assemblyPart.Load(si.Stream);
#else
                        string fullFileName = Path.Combine(baseDirectory, assemblyFile);
                        InternalLogger.Info("Loading assembly file: {0}", fullFileName);

                        Assembly asm = Assembly.LoadFrom(fullFileName);
#endif
                        this.ConfigurationItemFactory.RegisterItemsFromAssembly(asm, prefix);

                    }
                    catch (Exception exception)
                    {
                        if (exception.MustBeRethrownImmediately())
                        {
                            throw;
                        }

                        InternalLogger.Error(exception, "Error loading extensions.");
                        NLogConfigurationException configException =
                            new NLogConfigurationException("Error loading extensions: " + assemblyFile, exception);

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

                    continue;
                }

                string assemblyName = addElement.GetOptionalAttribute("assembly", null);
                if (assemblyName != null)
                {
                    try
                    {
                        InternalLogger.Info("Loading assembly name: {0}", assemblyName);
#if SILVERLIGHT && !WINDOWS_PHONE
                    var si = Application.GetResourceStream(new Uri(assemblyName + ".dll", UriKind.Relative));
                    var assemblyPart = new AssemblyPart();
                    Assembly asm = assemblyPart.Load(si.Stream);
#else
                        Assembly asm = Assembly.Load(assemblyName);
#endif

                        this.ConfigurationItemFactory.RegisterItemsFromAssembly(asm, prefix);
                    }
                    catch (Exception exception)
                    {
                        if (exception.MustBeRethrownImmediately())
                        {
                            throw;
                        }

                        InternalLogger.Error(exception, "Error loading extensions.");
                        NLogConfigurationException configException =
                            new NLogConfigurationException("Error loading extensions: " + assemblyName, exception);

                        if (configException.MustBeRethrown())
                        {
                            throw configException;
                        }
                    }
                }
            }
        }
        /// <summary>
        /// Initializes the configuration.
        /// </summary>
        /// <param name="reader"><see cref="XmlReader"/> containing the configuration section.</param>
        /// <param name="fileName">Name of the file that contains the element (to be used as a base for including other files).</param>
        /// <param name="ignoreErrors">Ignore any errors during configuration.</param>
        private void Initialize(XmlReader reader, string fileName, bool ignoreErrors)
        {
            try
            {
                InitializeSucceeded = null;
                reader.MoveToContent();
                var content = new NLogXmlElement(reader);
                if (fileName != null)
                {
#if SILVERLIGHT
                    string key = fileName;
#else
                    string key = Path.GetFullPath(fileName);
#endif
                    this.visitedFile[key] = true;

                    this.originalFileName = fileName;
                    this.ParseTopLevel(content, Path.GetDirectoryName(fileName));

                    InternalLogger.Info("Configured from an XML element in {0}...", fileName);
                }
                else
                {
                    this.ParseTopLevel(content, null);
                }
                InitializeSucceeded = true;
            }
            catch (Exception exception)
            {
                InitializeSucceeded = false;
                if (exception.MustBeRethrown())
                {
                    throw;
                }

                NLogConfigurationException ConfigException = new NLogConfigurationException("Exception occurred when loading configuration from " + fileName, exception);

                if (!ignoreErrors)
                {
                    if (LogManager.ThrowExceptions)
                    {
                        throw ConfigException;
                    }
                    else
                    {
                        InternalLogger.Error("Error in Parsing Configuration File. Exception : {0}", ConfigException);
                    }
                }
                else
                {
                    InternalLogger.Error("Error in Parsing Configuration File. Exception : {0}", ConfigException);
                }
            }
        }
Exemple #10
0
        /// <summary>
        /// Initializes the configuration.
        /// </summary>
        /// <param name="reader"><see cref="XmlReader"/> containing the configuration section.</param>
        /// <param name="fileName">Name of the file that contains the element (to be used as a base for including other files).</param>
        /// <param name="ignoreErrors">Ignore any errors during configuration.</param>
        private void Initialize(XmlReader reader, string fileName, bool ignoreErrors)
        {
            try
            {
                InitializeSucceeded = null;
                reader.MoveToContent();
                var content = new NLogXmlElement(reader);
                if (fileName != null)
                {
                    this.originalFileName = fileName;
                    this.ParseTopLevel(content, fileName, autoReloadDefault: false);

                    InternalLogger.Info("Configured from an XML element in {0}...", fileName);
                }
                else
                {
                    this.ParseTopLevel(content, null, autoReloadDefault: false);
                }
                InitializeSucceeded = true;
                this.CheckParsingErrors(content);
                this.CheckUnusedTargets();

            }
            catch (Exception exception)
            {
                InitializeSucceeded = false;
                if (exception.MustBeRethrownImmediately())
                {
                    throw;
                }

                var configurationException = new NLogConfigurationException(exception, "Exception when parsing {0}. ", fileName);
                InternalLogger.Error(configurationException, "Parsing configuration from {0} failed.", fileName);

                if (!ignoreErrors)
                {
                    if (configurationException.MustBeRethrown())
                    {
                        throw configurationException;
                    }
                }

            }
        }