private bool AddArrayItemFromElement(object o, NLogXmlElement element)
        {
            string name = element.LocalName;

            PropertyInfo propInfo;

            if (!PropertyHelper.TryGetPropertyInfo(o, name, out propInfo))
            {
                return(false);
            }

            Type elementType = PropertyHelper.GetArrayItemType(propInfo);

            if (elementType != null)
            {
                IList  propertyValue = (IList)propInfo.GetValue(o, null);
                object arrayItem     = FactoryHelper.CreateInstance(elementType);
                this.ConfigureObjectFromAttributes(arrayItem, element, true);
                this.ConfigureObjectFromElement(arrayItem, element);
                propertyValue.Add(arrayItem);
                return(true);
            }

            return(false);
        }
 private void ConfigureObjectFromElement(object targetObject, NLogXmlElement element)
 {
     foreach (var child in element.Children)
     {
         this.SetPropertyFromElement(targetObject, child);
     }
 }
        private bool SetLayoutFromElement(object o, NLogXmlElement layoutElement)
        {
            PropertyInfo targetPropertyInfo;
            string       name = layoutElement.LocalName;

            // if property exists
            if (PropertyHelper.TryGetPropertyInfo(o, name, out targetPropertyInfo))
            {
                // and is a Layout
                if (typeof(Layout).IsAssignableFrom(targetPropertyInfo.PropertyType))
                {
                    string layoutTypeName = StripOptionalNamespacePrefix(layoutElement.GetOptionalAttribute("type", null));

                    // and 'type' attribute has been specified
                    if (layoutTypeName != null)
                    {
                        // configure it from current element
                        Layout layout = this.ConfigurationItemFactory.Layouts.CreateInstance(this.ExpandSimpleVariables(layoutTypeName));
                        this.ConfigureObjectFromAttributes(layout, layoutElement, true);
                        this.ConfigureObjectFromElement(layout, layoutElement);
                        targetPropertyInfo.SetValue(o, layout, null);
                        return(true);
                    }
                }
            }

            return(false);
        }
        private Target WrapWithDefaultWrapper(Target t, NLogXmlElement defaultParameters)
        {
            string wrapperType = StripOptionalNamespacePrefix(defaultParameters.GetRequiredAttribute("type"));

            Target            wrapperTargetInstance = this.ConfigurationItemFactory.Targets.CreateInstance(wrapperType);
            WrapperTargetBase wtb = wrapperTargetInstance as WrapperTargetBase;

            if (wtb == null)
            {
                throw new NLogConfigurationException("Target type specified on <default-wrapper /> is not a wrapper.");
            }

            this.ParseTargetElement(wrapperTargetInstance, defaultParameters);
            while (wtb.WrappedTarget != null)
            {
                wtb = wtb.WrappedTarget as WrapperTargetBase;
                if (wtb == null)
                {
                    throw new NLogConfigurationException("Child target type specified on <default-wrapper /> is not a wrapper.");
                }
            }

            wtb.WrappedTarget          = t;
            wrapperTargetInstance.Name = t.Name;
            t.Name = t.Name + "_wrapped";

            InternalLogger.Debug("Wrapping target '{0}' with '{1}' and renaming to '{2}", wrapperTargetInstance.Name, wrapperTargetInstance.GetType().Name, t.Name);
            return(wrapperTargetInstance);
        }
        private void ParseVariableElement(NLogXmlElement variableElement)
        {
            variableElement.AssertName("variable");

            string name  = variableElement.GetRequiredAttribute("name");
            string value = this.ExpandSimpleVariables(variableElement.GetRequiredAttribute("value"));

            this.Variables[name] = value;
        }
Beispiel #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).</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);
                }
            }
        }
        private void ParseConfigurationElement(NLogXmlElement configurationElement, string baseDirectory)
        {
            InternalLogger.Trace("ParseConfigurationElement");
            configurationElement.AssertName("configuration");

            foreach (var el in configurationElement.Elements("nlog"))
            {
                this.ParseNLogElement(el, baseDirectory);
            }
        }
        private void ParseRulesElement(NLogXmlElement rulesElement, IList <LoggingRule> rulesCollection)
        {
            InternalLogger.Trace("ParseRulesElement");
            rulesElement.AssertName("rules");

            foreach (var loggerElement in rulesElement.Elements("logger"))
            {
                this.ParseLoggerElement(loggerElement, rulesCollection);
            }
        }
Beispiel #9
0
        /// <summary>
        /// Parse {configuration} xml element.
        /// </summary>
        /// <param name="configurationElement"></param>
        /// <param name="filePath">path to config file.</param>
        /// <param name="autoReloadDefault">The default value for the autoReload option.</param>
        private void ParseConfigurationElement(NLogXmlElement configurationElement, string filePath, bool autoReloadDefault)
        {
            InternalLogger.Trace("ParseConfigurationElement");
            configurationElement.AssertName("configuration");

            foreach (var el in configurationElement.Elements("nlog"))
            {
                this.ParseNLogElement(el, filePath, autoReloadDefault);
            }
        }
Beispiel #10
0
        private void ParseNLogElement(NLogXmlElement nlogElement, string baseDirectory)
        {
            InternalLogger.Trace("ParseNLogElement");
            nlogElement.AssertName("nlog");

            if (nlogElement.GetOptionalBooleanAttribute("useInvariantCulture", false))
            {
                this.DefaultCultureInfo = CultureInfo.InvariantCulture;
            }
            this.AutoReload             = nlogElement.GetOptionalBooleanAttribute("autoReload", false);
            LogManager.ThrowExceptions  = nlogElement.GetOptionalBooleanAttribute("throwExceptions", LogManager.ThrowExceptions);
            InternalLogger.LogToConsole = nlogElement.GetOptionalBooleanAttribute("internalLogToConsole", InternalLogger.LogToConsole);
#if !NET_CF
            InternalLogger.LogToConsoleError = nlogElement.GetOptionalBooleanAttribute("internalLogToConsoleError", InternalLogger.LogToConsoleError);
#endif
            InternalLogger.LogFile     = nlogElement.GetOptionalAttribute("internalLogFile", InternalLogger.LogFile);
            InternalLogger.LogLevel    = LogLevel.FromString(nlogElement.GetOptionalAttribute("internalLogLevel", InternalLogger.LogLevel.Name));
            LogManager.GlobalThreshold = LogLevel.FromString(nlogElement.GetOptionalAttribute("globalThreshold", LogManager.GlobalThreshold.Name));

            foreach (var el in nlogElement.Children)
            {
                switch (el.LocalName.ToUpper(CultureInfo.InvariantCulture))
                {
                case "EXTENSIONS":
                    this.ParseExtensionsElement(el, baseDirectory);
                    break;

                case "INCLUDE":
                    this.ParseIncludeElement(el, baseDirectory);
                    break;

                case "APPENDERS":
                case "TARGETS":
                    this.ParseTargetsElement(el);
                    break;

                case "VARIABLE":
                    this.ParseVariableElement(el);
                    break;

                case "RULES":
                    this.ParseRulesElement(el, this.LoggingRules);
                    break;

                case "TIME":
                    this.ParseTimeElement(el);
                    break;

                default:
                    InternalLogger.Warn("Skipping unknown node: {0}", el.LocalName);
                    break;
                }
            }
        }
Beispiel #11
0
        /// <summary>
        /// Parse {configuration} xml element.
        /// </summary>
        /// <param name="configurationElement"></param>
        /// <param name="filePath">path to config file.</param>
        /// <param name="autoReloadDefault">The default value for the autoReload option.</param>
        private void ParseConfigurationElement(NLogXmlElement configurationElement, [CanBeNull] string filePath, bool autoReloadDefault)
        {
            InternalLogger.Trace("ParseConfigurationElement");
            configurationElement.AssertName("configuration");

            var nlogElements = configurationElement.Elements("nlog").ToList();

            foreach (var nlogElement in nlogElements)
            {
                ParseNLogElement(nlogElement, filePath, autoReloadDefault);
            }
        }
        private void ParseFilters(LoggingRule rule, NLogXmlElement filtersElement)
        {
            filtersElement.AssertName("filters");

            foreach (var filterElement in filtersElement.Children)
            {
                string name = filterElement.LocalName;

                Filter filter = this.configurationItemFactory.Filters.CreateInstance(name);
                this.ConfigureObjectFromAttributes(filter, filterElement, false);
                rule.Filters.Add(filter);
            }
        }
        private void ParseTimeElement(NLogXmlElement timeElement)
        {
            timeElement.AssertName("time");

            string type = timeElement.GetRequiredAttribute("type");

            TimeSource newTimeSource = this.ConfigurationItemFactory.TimeSources.CreateInstance(type);

            this.ConfigureObjectFromAttributes(newTimeSource, timeElement, true);

            InternalLogger.Info("Selecting time source {0}", newTimeSource);
            TimeSource.Current = newTimeSource;
        }
        private void SetPropertyFromElement(object o, NLogXmlElement element)
        {
            if (this.AddArrayItemFromElement(o, element))
            {
                return;
            }

            if (this.SetLayoutFromElement(o, element))
            {
                return;
            }

            PropertyHelper.SetPropertyFromString(o, element.LocalName, this.ExpandVariables(element.Value));
        }
        /// <summary>
        /// Parse the root
        /// </summary>
        /// <param name="content"></param>
        /// <param name="filePath">path to config file.</param>
        /// <param name="autoReloadDefault">The default value for the autoReload option.</param>
        private void ParseTopLevel(NLogXmlElement content, string filePath, bool autoReloadDefault)
        {
            content.AssertName("nlog", "configuration");

            switch (content.LocalName.ToUpper(CultureInfo.InvariantCulture))
            {
            case "CONFIGURATION":
                this.ParseConfigurationElement(content, filePath, autoReloadDefault);
                break;

            case "NLOG":
                this.ParseNLogElement(content, filePath, autoReloadDefault);
                break;
            }
        }
        private void ParseTopLevel(NLogXmlElement content, string baseDirectory)
        {
            content.AssertName("nlog", "configuration");

            switch (content.LocalName.ToUpper(CultureInfo.InvariantCulture))
            {
            case "CONFIGURATION":
                this.ParseConfigurationElement(content, baseDirectory);
                break;

            case "NLOG":
                this.ParseNLogElement(content, baseDirectory);
                break;
            }
        }
        private void ConfigureObjectFromAttributes(object targetObject, NLogXmlElement element, bool ignoreType)
        {
            foreach (var kvp in element.AttributeValues)
            {
                string childName  = kvp.Key;
                string childValue = kvp.Value;

                if (ignoreType && childName.Equals("type", StringComparison.OrdinalIgnoreCase))
                {
                    continue;
                }

                PropertyHelper.SetPropertyFromString(targetObject, childName, this.ExpandVariables(childValue));
            }
        }
        private void ParseIncludeElement(NLogXmlElement includeElement, string baseDirectory, bool autoReloadDefault)
        {
            includeElement.AssertName("include");

            string newFileName = includeElement.GetRequiredAttribute("file");

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

#if SILVERLIGHT
                newFileName = newFileName.Replace("\\", "/");
                if (Application.GetResourceStream(new Uri(newFileName, UriKind.Relative)) != null)
#else
                if (File.Exists(newFileName))
#endif
                {
                    InternalLogger.Debug("Including file '{0}'", newFileName);
                    this.ConfigureFromFile(newFileName, autoReloadDefault);
                }
                else
                {
                    throw new FileNotFoundException("Included file not found: " + newFileName);
                }
            }
            catch (Exception exception)
            {
                InternalLogger.Error(exception, "Error when including '{0}'.", newFileName);

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

                if (includeElement.GetOptionalBooleanAttribute("ignoreErrors", false))
                {
                    return;
                }

                throw new NLogConfigurationException("Error when including: " + newFileName, exception);
            }
        }
        /// <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;
                    }
                }
            }
        }
Beispiel #20
0
        /// <summary>
        /// Checks whether any error during XML configuration parsing has occured.
        /// If there are any and <c>ThrowConfigExceptions</c> or <c>ThrowExceptions</c>
        /// setting is enabled - throws <c>NLogConfigurationException</c>, otherwise
        /// just write an internal log at Warn level.
        /// </summary>
        /// <param name="rootContentElement">Root NLog configuration xml element</param>
        private void CheckParsingErrors(NLogXmlElement rootContentElement)
        {
            var parsingErrors = rootContentElement.GetParsingErrors().ToArray();

            if (parsingErrors.Any())
            {
                if (LogManager.ThrowConfigExceptions ?? LogManager.ThrowExceptions)
                {
                    string exceptionMessage = string.Join(Environment.NewLine, parsingErrors);
                    throw new NLogConfigurationException(exceptionMessage);
                }
                else
                {
                    foreach (var parsingError in parsingErrors)
                    {
                        InternalLogger.Log(LogLevel.Warn, parsingError);
                    }
                }
            }
        }
        private bool SetItemFromElement(object o, NLogXmlElement element)
        {
            if (element.Value != null)
            {
                return(false);
            }

            string name = element.LocalName;

            PropertyInfo propInfo;

            if (!PropertyHelper.TryGetPropertyInfo(o, name, out propInfo))
            {
                return(false);
            }

            object item = propInfo.GetValue(o, null);

            this.ConfigureObjectFromAttributes(item, element, true);
            this.ConfigureObjectFromElement(item, element);
            return(true);
        }
Beispiel #22
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;
                }
            }
        }
        /// <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
            {
                reader.MoveToContent();
                var content = new NLogXmlElement(reader);
                if (fileName != null)
                {
                    InternalLogger.Info("Configuring from an XML element in {0}...", fileName);
#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));
                }
                else
                {
                    this.ParseTopLevel(content, null);
                }
            }
            catch (Exception exception)
            {
                if (exception.MustBeRethrown())
                {
                    throw;
                }

                InternalLogger.Error("Error {0}...", exception);
                if (!ignoreErrors)
                {
                    throw new NLogConfigurationException("Exception occurred when loading configuration from " + fileName, exception);
                }
            }
        }
Beispiel #24
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;
                }
            }
        }
        private bool AddArrayItemFromElement(object o, NLogXmlElement element)
        {
            string name = element.LocalName;

            PropertyInfo propInfo;
            if (!PropertyHelper.TryGetPropertyInfo(o, name, out propInfo))
            {
                return false;
            }

            Type elementType = PropertyHelper.GetArrayItemType(propInfo);
            if (elementType != null)
            {
                IList propertyValue = (IList)propInfo.GetValue(o, null);
                object arrayItem = FactoryHelper.CreateInstance(elementType);
                this.ConfigureObjectFromAttributes(arrayItem, element, true);
                this.ConfigureObjectFromElement(arrayItem, element);
                propertyValue.Add(arrayItem);
                return true;
            }

            return false;
        }
        private void SetPropertyFromElement(object o, NLogXmlElement element)
        {
            if (this.AddArrayItemFromElement(o, element))
            {
                return;
            }

            if (this.SetLayoutFromElement(o, element))
            {
                return;
            }

            PropertyHelper.SetPropertyFromString(o, element.LocalName, this.ExpandSimpleVariables(element.Value), this.ConfigurationItemFactory);
        }
        /// <summary>
        /// Parse the root
        /// </summary>
        /// <param name="content"></param>
        /// <param name="filePath">path to config file.</param>
        /// <param name="autoReloadDefault">The default value for the autoReload option.</param>
        private void ParseTopLevel(NLogXmlElement content, string filePath, bool autoReloadDefault)
        {
            content.AssertName("nlog", "configuration");

            switch (content.LocalName.ToUpper(CultureInfo.InvariantCulture))
            {
                case "CONFIGURATION":
                    this.ParseConfigurationElement(content, filePath, autoReloadDefault);
                    break;

                case "NLOG":
                    this.ParseNLogElement(content, filePath, autoReloadDefault);
                    break;
            }
        }
        private bool SetLayoutFromElement(object o, NLogXmlElement layoutElement)
        {
            PropertyInfo targetPropertyInfo;
            string name = layoutElement.LocalName;

            // if property exists
            if (PropertyHelper.TryGetPropertyInfo(o, name, out targetPropertyInfo))
            {
                Layout layout = TryCreateLayoutInstance(layoutElement, targetPropertyInfo.PropertyType);

                // and is a Layout and 'type' attribute has been specified
                if (layout != null)
                {
                    this.ConfigureObjectFromAttributes(layout, layoutElement, true);
                    this.ConfigureObjectFromElement(layout, layoutElement);
                    targetPropertyInfo.SetValue(o, layout, null);
                    return true;
                }
            }

            return false;
        }
        private bool SetItemFromElement(object o, NLogXmlElement element)
        {
            if (element.Value != null)
                return false;

            string name = element.LocalName;

            PropertyInfo propInfo;
            if (!PropertyHelper.TryGetPropertyInfo(o, name, out propInfo))
            {
                return false;
            }

            object item = propInfo.GetValue(o, null);
            this.ConfigureObjectFromAttributes(item, element, true);
            this.ConfigureObjectFromElement(item, element);
            return true;
        }
        /// <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
            {
                reader.MoveToContent();
                var content = new NLogXmlElement(reader);
                if (fileName != null)
                {
                    InternalLogger.Info("Configuring from an XML element in {0}...", fileName);
#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));
                }
                else
                {
                    this.ParseTopLevel(content, null);
                }
            }
            catch (Exception exception)
            {
                if (exception.MustBeRethrown())
                {
                    throw;
                }

                InternalLogger.Error("Error {0}...", exception);
                if (!ignoreErrors)
                {
                    throw new NLogConfigurationException("Exception occurred when loading configuration from " + fileName, exception);
                }
            }
        }
 private void ParsePoolingElement(NLogXmlElement poolElement)
 {
     this.ConfigureObjectFromAttributes(this.PoolConfiguration, poolElement, false);
 }
        private void ParseTargetElement(Target target, NLogXmlElement targetElement)
        {
            var compound = target as CompoundTargetBase;
            var wrapper  = target as WrapperTargetBase;

            this.ConfigureObjectFromAttributes(target, targetElement, true);

            var children = targetElement.Children.ToList();

            foreach (var childElement in children)
            {
                string name = childElement.LocalName;

                if (compound != null)
                {
                    if (IsTargetRefElement(name))
                    {
                        string targetName = childElement.GetRequiredAttribute("name");
                        Target newTarget  = this.FindTargetByName(targetName);
                        if (newTarget == null)
                        {
                            throw new NLogConfigurationException("Referenced target '" + targetName + "' not found.");
                        }

                        compound.Targets.Add(newTarget);
                        continue;
                    }

                    if (IsTargetElement(name))
                    {
                        string type = StripOptionalNamespacePrefix(childElement.GetRequiredAttribute("type"));

                        Target newTarget = this.ConfigurationItemFactory.Targets.CreateInstance(type);
                        if (newTarget != null)
                        {
                            this.ParseTargetElement(newTarget, childElement);
                            if (newTarget.Name != null)
                            {
                                // if the new target has name, register it
                                AddTarget(newTarget.Name, newTarget);
                            }

                            compound.Targets.Add(newTarget);
                        }

                        continue;
                    }
                }

                if (wrapper != null)
                {
                    if (IsTargetRefElement(name))
                    {
                        string targetName = childElement.GetRequiredAttribute("name");
                        Target newTarget  = this.FindTargetByName(targetName);
                        if (newTarget == null)
                        {
                            throw new NLogConfigurationException("Referenced target '" + targetName + "' not found.");
                        }

                        wrapper.WrappedTarget = newTarget;
                        continue;
                    }

                    if (IsTargetElement(name))
                    {
                        string type = StripOptionalNamespacePrefix(childElement.GetRequiredAttribute("type"));

                        Target newTarget = this.ConfigurationItemFactory.Targets.CreateInstance(type);
                        if (newTarget != null)
                        {
                            this.ParseTargetElement(newTarget, childElement);
                            if (newTarget.Name != null)
                            {
                                // if the new target has name, register it
                                AddTarget(newTarget.Name, newTarget);
                            }

                            if (wrapper.WrappedTarget != null)
                            {
                                throw new NLogConfigurationException("Wrapped target already defined.");
                            }

                            wrapper.WrappedTarget = newTarget;
                        }

                        continue;
                    }
                }

                this.SetPropertyFromElement(target, childElement);
            }
        }
        private void ParseConfigurationElement(NLogXmlElement configurationElement, string baseDirectory)
        {
            InternalLogger.Trace("ParseConfigurationElement");
            configurationElement.AssertName("configuration");

            foreach (var el in configurationElement.Elements("nlog"))
            {
                this.ParseNLogElement(el, baseDirectory);
            }
        }
        /// <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(NLogXmlElement nlogElement, string filePath, bool autoReloadDefault)
        {
            InternalLogger.Trace("ParseNLogElement");
            nlogElement.AssertName("nlog");

            if (nlogElement.GetOptionalBooleanAttribute("useInvariantCulture", false))
            {
                this.DefaultCultureInfo = CultureInfo.InvariantCulture;
            }

            //check loglevel as first, as other properties could write (indirect) to the internal log.
            InternalLogger.LogLevel = LogLevel.FromString(nlogElement.GetOptionalAttribute("internalLogLevel", InternalLogger.LogLevel.Name));

#pragma warning disable 618
            this.ExceptionLoggingOldStyle = nlogElement.GetOptionalBooleanAttribute("exceptionLoggingOldStyle", false);
#pragma warning restore 618

            bool autoReload = nlogElement.GetOptionalBooleanAttribute("autoReload", autoReloadDefault);
            if (filePath != null)
            {
                this.fileMustAutoReloadLookup[GetFileLookupKey(filePath)] = autoReload;
            }

            logFactory.ThrowExceptions       = nlogElement.GetOptionalBooleanAttribute("throwExceptions", logFactory.ThrowExceptions);
            logFactory.ThrowConfigExceptions = nlogElement.GetOptionalBooleanAttribute("throwConfigExceptions", logFactory.ThrowConfigExceptions);
            InternalLogger.LogToConsole      = nlogElement.GetOptionalBooleanAttribute("internalLogToConsole", InternalLogger.LogToConsole);
            InternalLogger.LogToConsoleError = nlogElement.GetOptionalBooleanAttribute("internalLogToConsoleError", InternalLogger.LogToConsoleError);
            InternalLogger.LogFile           = nlogElement.GetOptionalAttribute("internalLogFile", InternalLogger.LogFile);

#if !SILVERLIGHT && !__IOS__ && !__ANDROID__
            InternalLogger.LogToTrace = nlogElement.GetOptionalBooleanAttribute("internalLogToTrace", InternalLogger.LogToTrace);
#endif
            InternalLogger.IncludeTimestamp = nlogElement.GetOptionalBooleanAttribute("internalLogIncludeTimestamp", InternalLogger.IncludeTimestamp);
            logFactory.GlobalThreshold      = LogLevel.FromString(nlogElement.GetOptionalAttribute("globalThreshold", logFactory.GlobalThreshold.Name));

            var children = nlogElement.Children.ToList();

            //first load the extensions, as the can be used in other elements (targets etc)
            var extensionsChilds = children.Where(child => child.LocalName.Equals("EXTENSIONS", StringComparison.InvariantCultureIgnoreCase)).ToList();
            foreach (var extensionsChild in extensionsChilds)
            {
                this.ParseExtensionsElement(extensionsChild, Path.GetDirectoryName(filePath));
            }

            //parse all other direct elements
            foreach (var child in children)
            {
                switch (child.LocalName.ToUpper(CultureInfo.InvariantCulture))
                {
                case "EXTENSIONS":
                    //already parsed
                    break;

                case "INCLUDE":
                    this.ParseIncludeElement(child, Path.GetDirectoryName(filePath), autoReloadDefault: autoReload);
                    break;

                case "APPENDERS":
                case "TARGETS":
                    this.ParseTargetsElement(child);
                    break;

                case "VARIABLE":
                    this.ParseVariableElement(child);
                    break;

                case "RULES":
                    this.ParseRulesElement(child, this.LoggingRules);
                    break;

                case "TIME":
                    this.ParseTimeElement(child);
                    break;

                case "POOLING":
                    this.ParsePoolingElement(child);
                    break;

                default:
                    InternalLogger.Warn("Skipping unknown node: {0}", child.LocalName);
                    break;
                }
            }
        }
        /// <summary>
        /// Parse {Rules} xml element
        /// </summary>
        /// <param name="rulesElement"></param>
        /// <param name="rulesCollection">Rules are added to this parameter.</param>
        private void ParseRulesElement(NLogXmlElement rulesElement, IList<LoggingRule> rulesCollection)
        {
            InternalLogger.Trace("ParseRulesElement");
            rulesElement.AssertName("rules");

            foreach (var loggerElement in rulesElement.Elements("logger"))
            {
                this.ParseLoggerElement(loggerElement, rulesCollection);
            }
        }
        /// <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(NLogXmlElement nlogElement, string filePath, bool autoReloadDefault)
        {
            InternalLogger.Trace("ParseNLogElement");
            nlogElement.AssertName("nlog");

            if (nlogElement.GetOptionalBooleanAttribute("useInvariantCulture", false))
            {
                this.DefaultCultureInfo = CultureInfo.InvariantCulture;
            }
#pragma warning disable 618
            this.ExceptionLoggingOldStyle = nlogElement.GetOptionalBooleanAttribute("exceptionLoggingOldStyle", false);
#pragma warning restore 618

            bool autoReload = nlogElement.GetOptionalBooleanAttribute("autoReload", autoReloadDefault);
            if (filePath != null)
                this.fileMustAutoReloadLookup[GetFileLookupKey(filePath)] = autoReload;
            
            LogManager.ThrowExceptions = nlogElement.GetOptionalBooleanAttribute("throwExceptions", LogManager.ThrowExceptions);
            InternalLogger.LogToConsole = nlogElement.GetOptionalBooleanAttribute("internalLogToConsole", InternalLogger.LogToConsole);
            InternalLogger.LogToConsoleError = nlogElement.GetOptionalBooleanAttribute("internalLogToConsoleError", InternalLogger.LogToConsoleError);
            InternalLogger.LogFile = nlogElement.GetOptionalAttribute("internalLogFile", InternalLogger.LogFile);
            InternalLogger.LogLevel = LogLevel.FromString(nlogElement.GetOptionalAttribute("internalLogLevel", InternalLogger.LogLevel.Name));
            LogManager.GlobalThreshold = LogLevel.FromString(nlogElement.GetOptionalAttribute("globalThreshold", LogManager.GlobalThreshold.Name));

            var children = nlogElement.Children;

            //first load the extensions, as the can be used in other elements (targets etc)
            var extensionsChilds = children.Where(child => child.LocalName.Equals("EXTENSIONS", StringComparison.InvariantCultureIgnoreCase));
            foreach (var extensionsChild in extensionsChilds)
            {
                this.ParseExtensionsElement(extensionsChild, Path.GetDirectoryName(filePath));
            }

            //parse all other direct elements
            foreach (var child in children)
            {
                switch (child.LocalName.ToUpper(CultureInfo.InvariantCulture))
                {
                    case "EXTENSIONS":
                        //already parsed
                        break;

                    case "INCLUDE":
                        this.ParseIncludeElement(child, Path.GetDirectoryName(filePath), autoReloadDefault: autoReload);
                        break;

                    case "APPENDERS":
                    case "TARGETS":
                        this.ParseTargetsElement(child);
                        break;

                    case "VARIABLE":
                        this.ParseVariableElement(child);
                        break;

                    case "RULES":
                        this.ParseRulesElement(child, this.LoggingRules);
                        break;

                    case "TIME":
                        this.ParseTimeElement(child);
                        break;

                    default:
                        InternalLogger.Warn("Skipping unknown node: {0}", child.LocalName);
                        break;
                }
            }
        }
        /// <summary>
        /// Parse {configuration} xml element.
        /// </summary>
        /// <param name="configurationElement"></param>
        /// <param name="filePath">path to config file.</param>
        /// <param name="autoReloadDefault">The default value for the autoReload option.</param>
        private void ParseConfigurationElement(NLogXmlElement configurationElement, string filePath, bool autoReloadDefault)
        {
            InternalLogger.Trace("ParseConfigurationElement");
            configurationElement.AssertName("configuration");

            foreach (var el in configurationElement.Elements("nlog"))
            {
                this.ParseNLogElement(el, filePath, autoReloadDefault);
            }
        }
        private void ConfigureObjectFromAttributes(object targetObject, NLogXmlElement element, bool ignoreType)
        {
            foreach (var kvp in element.AttributeValues)
            {
                string childName = kvp.Key;
                string childValue = kvp.Value;

                if (ignoreType && childName.Equals("type", StringComparison.OrdinalIgnoreCase))
                {
                    continue;
                }

                PropertyHelper.SetPropertyFromString(targetObject, childName, this.ExpandSimpleVariables(childValue), this.ConfigurationItemFactory);
            }
        }
        private void ParseTopLevel(NLogXmlElement content, string baseDirectory)
        {
            content.AssertName("nlog", "configuration");

            switch (content.LocalName.ToUpper(CultureInfo.InvariantCulture))
            {
                case "CONFIGURATION":
                    this.ParseConfigurationElement(content, baseDirectory);
                    break;

                case "NLOG":
                    this.ParseNLogElement(content, baseDirectory);
                    break;
            }
        }
Beispiel #40
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;
                    }
                }

            }
        }
        private Layout TryCreateLayoutInstance(NLogXmlElement element, Type type)
        {
            // Check if it is a Layout
            if (!typeof(Layout).IsAssignableFrom(type))
                return null;

            string layoutTypeName = StripOptionalNamespacePrefix(element.GetOptionalAttribute("type", null));

            // Check if the 'type' attribute has been specified
            if (layoutTypeName == null)
                return null;

            return this.ConfigurationItemFactory.Layouts.CreateInstance(this.ExpandSimpleVariables(layoutTypeName));
        }
        private Target WrapWithDefaultWrapper(Target t, NLogXmlElement defaultParameters)
        {
            string wrapperType = StripOptionalNamespacePrefix(defaultParameters.GetRequiredAttribute("type"));

            Target wrapperTargetInstance = this.ConfigurationItemFactory.Targets.CreateInstance(wrapperType);
            WrapperTargetBase wtb = wrapperTargetInstance as WrapperTargetBase;
            if (wtb == null)
            {
                throw new NLogConfigurationException("Target type specified on <default-wrapper /> is not a wrapper.");
            }

            this.ParseTargetElement(wrapperTargetInstance, defaultParameters);
            while (wtb.WrappedTarget != null)
            {
                wtb = wtb.WrappedTarget as WrapperTargetBase;
                if (wtb == null)
                {
                    throw new NLogConfigurationException("Child target type specified on <default-wrapper /> is not a wrapper.");
                }
            }

            wtb.WrappedTarget = t;
            wrapperTargetInstance.Name = t.Name;
            t.Name = t.Name + "_wrapped";

            InternalLogger.Debug("Wrapping target '{0}' with '{1}' and renaming to '{2}", wrapperTargetInstance.Name, wrapperTargetInstance.GetType().Name, t.Name);
            return wrapperTargetInstance;
        }
        private void ParseNLogElement(NLogXmlElement nlogElement, string baseDirectory)
        {
            InternalLogger.Trace("ParseNLogElement");
            nlogElement.AssertName("nlog");

            this.AutoReload = nlogElement.GetOptionalBooleanAttribute("autoReload", false);
            LogManager.ThrowExceptions = nlogElement.GetOptionalBooleanAttribute("throwExceptions", LogManager.ThrowExceptions);
            InternalLogger.LogToConsole = nlogElement.GetOptionalBooleanAttribute("internalLogToConsole", InternalLogger.LogToConsole);
#if !NET_CF
            InternalLogger.LogToConsoleError = nlogElement.GetOptionalBooleanAttribute("internalLogToConsoleError", InternalLogger.LogToConsoleError);
#endif
            InternalLogger.LogFile = nlogElement.GetOptionalAttribute("internalLogFile", InternalLogger.LogFile);
            InternalLogger.LogLevel = LogLevel.FromString(nlogElement.GetOptionalAttribute("internalLogLevel", InternalLogger.LogLevel.Name));
            LogManager.GlobalThreshold = LogLevel.FromString(nlogElement.GetOptionalAttribute("globalThreshold", LogManager.GlobalThreshold.Name));

            foreach (var el in nlogElement.Children)
            {
                switch (el.LocalName.ToUpper(CultureInfo.InvariantCulture))
                {
                    case "EXTENSIONS":
                        this.ParseExtensionsElement(el, baseDirectory);
                        break;

                    case "INCLUDE":
                        this.ParseIncludeElement(el, baseDirectory);
                        break;

                    case "APPENDERS":
                    case "TARGETS":
                        this.ParseTargetsElement(el);
                        break;

                    case "VARIABLE":
                        this.ParseVariableElement(el);
                        break;

                    case "RULES":
                        this.ParseRulesElement(el, this.LoggingRules);
                        break;

                    default:
                        InternalLogger.Warn("Skipping unknown node: {0}", el.LocalName);
                        break;
                }
            }
        }
 private void ConfigureObjectFromElement(object targetObject, NLogXmlElement element)
 {
     foreach (var child in element.Children)
     {
         this.SetPropertyFromElement(targetObject, child);
     }
 }
        private bool SetLayoutFromElement(object o, NLogXmlElement layoutElement)
        {
            PropertyInfo targetPropertyInfo;
            string name = layoutElement.LocalName;

            // if property exists
            if (PropertyHelper.TryGetPropertyInfo(o, name, out targetPropertyInfo))
            {
                // and is a Layout
                if (typeof(Layout).IsAssignableFrom(targetPropertyInfo.PropertyType))
                {
                    string layoutTypeName = StripOptionalNamespacePrefix(layoutElement.GetOptionalAttribute("type", null));

                    // and 'type' attribute has been specified
                    if (layoutTypeName != null)
                    {
                        // configure it from current element
                        Layout layout = this.ConfigurationItemFactory.Layouts.CreateInstance(this.ExpandSimpleVariables(layoutTypeName));
                        this.ConfigureObjectFromAttributes(layout, layoutElement, true);
                        this.ConfigureObjectFromElement(layout, layoutElement);
                        targetPropertyInfo.SetValue(o, layout, null);
                        return true;
                    }
                }
            }

            return false;
        }
        /// <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);
                }
            }
        }
Beispiel #47
0
 /// <summary>
 /// Checks whether any error during XML configuration parsing has occured.
 /// If there are any and <c>ThrowConfigExceptions</c> or <c>ThrowExceptions</c>
 /// setting is enabled - throws <c>NLogConfigurationException</c>, otherwise
 /// just write an internal log at Warn level.
 /// </summary>
 /// <param name="rootContentElement">Root NLog configuration xml element</param>
 private void CheckParsingErrors(NLogXmlElement rootContentElement)
 {
     var parsingErrors = rootContentElement.GetParsingErrors().ToArray();
     if(parsingErrors.Any())
     {
         if (LogManager.ThrowConfigExceptions ?? LogManager.ThrowExceptions)
         {
             string exceptionMessage = string.Join(Environment.NewLine, parsingErrors);
             throw new NLogConfigurationException(exceptionMessage);
         }
         else
         {
             foreach (var parsingError in parsingErrors)
             {
                 InternalLogger.Log(LogLevel.Warn, parsingError);
             }
         }
     }
 }
        private void ParseTargetElement(Target target, NLogXmlElement targetElement)
        {
            var compound = target as CompoundTargetBase;
            var wrapper = target as WrapperTargetBase;

            this.ConfigureObjectFromAttributes(target, targetElement, true);

            foreach (var childElement in targetElement.Children)
            {
                string name = childElement.LocalName;

                if (compound != null)
                {
                    if (IsTargetRefElement(name))
                    {
                        string targetName = childElement.GetRequiredAttribute("name");
                        Target newTarget = this.FindTargetByName(targetName);
                        if (newTarget == null)
                        {
                            throw new NLogConfigurationException("Referenced target '" + targetName + "' not found.");
                        }

                        compound.Targets.Add(newTarget);
                        continue;
                    }

                    if (IsTargetElement(name))
                    {
                        string type = StripOptionalNamespacePrefix(childElement.GetRequiredAttribute("type"));

                        Target newTarget = this.ConfigurationItemFactory.Targets.CreateInstance(type);
                        if (newTarget != null)
                        {
                            this.ParseTargetElement(newTarget, childElement);
                            if (newTarget.Name != null)
                            {
                                // if the new target has name, register it
                                AddTarget(newTarget.Name, newTarget);
                            }

                            compound.Targets.Add(newTarget);
                        }

                        continue;
                    }
                }

                if (wrapper != null)
                {
                    if (IsTargetRefElement(name))
                    {
                        string targetName = childElement.GetRequiredAttribute("name");
                        Target newTarget = this.FindTargetByName(targetName);
                        if (newTarget == null)
                        {
                            throw new NLogConfigurationException("Referenced target '" + targetName + "' not found.");
                        }

                        wrapper.WrappedTarget = newTarget;
                        continue;
                    }

                    if (IsTargetElement(name))
                    {
                        string type = StripOptionalNamespacePrefix(childElement.GetRequiredAttribute("type"));

                        Target newTarget = this.ConfigurationItemFactory.Targets.CreateInstance(type);
                        if (newTarget != null)
                        {
                            this.ParseTargetElement(newTarget, childElement);
                            if (newTarget.Name != null)
                            {
                                // if the new target has name, register it
                                AddTarget(newTarget.Name, newTarget);
                            }

                            if (wrapper.WrappedTarget != null)
                            {
                                throw new NLogConfigurationException("Wrapped target already defined.");
                            }

                            wrapper.WrappedTarget = newTarget;
                        }

                        continue;
                    }
                }

                this.SetPropertyFromElement(target, childElement);
            }
        }
Beispiel #49
0
        private void ConfigureObjectFromAttributes(object targetObject, NLogXmlElement element, bool ignoreType)
        {
            var attributeValues = element.AttributeValues.ToList();
            foreach (var kvp in attributeValues)
            {
                string childName = kvp.Key;
                string childValue = kvp.Value;

                if (ignoreType && childName.Equals("type", StringComparison.OrdinalIgnoreCase))
                {
                    continue;
                }
                try
                {
                    PropertyHelper.SetPropertyFromString(targetObject, childName, this.ExpandSimpleVariables(childValue), this.ConfigurationItemFactory);
                }
                catch (NLogConfigurationException)
                {
                    InternalLogger.Warn("Error when setting '{0}' on attibute '{1}'", childValue, childName);
                    throw;
                }

            }
        }
        private void ParseExtensionsElement(NLogXmlElement extensionsElement, string baseDirectory)
        {
            extensionsElement.AssertName("extensions");

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

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

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

                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.MustBeRethrown())
                        {
                            throw;
                        }

                        InternalLogger.Error("Error loading extensions: {0}", exception);
                        if (LogManager.ThrowExceptions)
                        {
                            throw new NLogConfigurationException("Error loading extensions: " + assemblyFile, exception);
                        }
                    }

                    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.MustBeRethrown())
                        {
                            throw;
                        }

                        InternalLogger.Error("Error loading extensions: {0}", exception);
                        if (LogManager.ThrowExceptions)
                        {
                            throw new NLogConfigurationException("Error loading extensions: " + assemblyName, exception);
                        }
                    }

                    continue;
                }
            }
        }
Beispiel #51
0
        private void SetPropertyFromElement(object o, NLogXmlElement element)
        {
            if (this.AddArrayItemFromElement(o, element))
            {
                return;
            }

            if (this.SetLayoutFromElement(o, element))
            {
                return;
            }

            if (this.SetItemFromElement(o, element))
            {
                return;
            }
            var value = this.ExpandSimpleVariables(element.Value);
            try
            {
               
                PropertyHelper.SetPropertyFromString(o, element.LocalName, value, this.ConfigurationItemFactory);
            }
            catch (NLogConfigurationException)
            {
                InternalLogger.Warn("Error when setting '{0}' from '<{1}>'", element.LocalName, value);
                throw;
            }
        }
        private void ParseIncludeElement(NLogXmlElement includeElement, string baseDirectory, bool autoReloadDefault)
        {
            includeElement.AssertName("include");

            string newFileName = includeElement.GetRequiredAttribute("file");

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

#if SILVERLIGHT
                newFileName = newFileName.Replace("\\", "/");
                if (Application.GetResourceStream(new Uri(newFileName, UriKind.Relative)) != null)
#else
                if (File.Exists(newFileName))
#endif
                {
                    InternalLogger.Debug("Including file '{0}'", newFileName);
                    this.ConfigureFromFile(newFileName, autoReloadDefault);
                }
                else
                {
                    throw new FileNotFoundException("Included file not found: " + newFileName);
                }
            }
            catch (Exception exception)
            {
                if (exception.MustBeRethrown())
                {
                    throw;
                }

                InternalLogger.Error("Error when including '{0}' {1}", newFileName, exception);

                if (includeElement.GetOptionalBooleanAttribute("ignoreErrors", false))
                {
                    return;
                }

                throw new NLogConfigurationException("Error when including: " + newFileName, exception);
            }
        }
        /// <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);
        }
        private void ParseTimeElement(NLogXmlElement timeElement)
        {
            timeElement.AssertName("time");

            string type = timeElement.GetRequiredAttribute("type");

            TimeSource newTimeSource = this.ConfigurationItemFactory.TimeSources.CreateInstance(type);

            this.ConfigureObjectFromAttributes(newTimeSource, timeElement, true);

            InternalLogger.Info("Selecting time source {0}", newTimeSource);
            TimeSource.Current = newTimeSource;
        }
        /// <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);
        }
        private void ParseFilters(LoggingRule rule, NLogXmlElement filtersElement)
        {
            filtersElement.AssertName("filters");

            foreach (var filterElement in filtersElement.Children)
            {
                string name = filterElement.LocalName;

                Filter filter = this.ConfigurationItemFactory.Filters.CreateInstance(name);
                this.ConfigureObjectFromAttributes(filter, filterElement, false);
                rule.Filters.Add(filter);
            }
        }
        private void ParseTargetsElement(NLogXmlElement targetsElement)
        {
            targetsElement.AssertName("targets", "appenders");

            bool           asyncWrap                         = targetsElement.GetOptionalBooleanAttribute("async", false);
            NLogXmlElement defaultWrapperElement             = null;
            var            typeNameToDefaultTargetParameters = new Dictionary <string, NLogXmlElement>();

            var children = targetsElement.Children.ToList();

            foreach (var targetElement in children)
            {
                string name             = targetElement.LocalName;
                string typeAttributeVal = StripOptionalNamespacePrefix(targetElement.GetOptionalAttribute("type", null));

                switch (name.ToUpper(CultureInfo.InvariantCulture))
                {
                case "DEFAULT-WRAPPER":
                    defaultWrapperElement = targetElement;
                    break;

                case "DEFAULT-TARGET-PARAMETERS":
                    if (typeAttributeVal == null)
                    {
                        throw new NLogConfigurationException("Missing 'type' attribute on <" + name + "/>.");
                    }

                    typeNameToDefaultTargetParameters[typeAttributeVal] = targetElement;
                    break;

                case "TARGET":
                case "APPENDER":
                case "WRAPPER":
                case "WRAPPER-TARGET":
                case "COMPOUND-TARGET":
                    if (typeAttributeVal == null)
                    {
                        throw new NLogConfigurationException("Missing 'type' attribute on <" + name + "/>.");
                    }

                    Target newTarget = this.ConfigurationItemFactory.Targets.CreateInstance(typeAttributeVal);

                    NLogXmlElement defaults;
                    if (typeNameToDefaultTargetParameters.TryGetValue(typeAttributeVal, out defaults))
                    {
                        this.ParseTargetElement(newTarget, defaults);
                    }

                    this.ParseTargetElement(newTarget, targetElement);

                    if (asyncWrap)
                    {
                        newTarget = WrapWithAsyncTargetWrapper(newTarget);
                    }

                    if (defaultWrapperElement != null)
                    {
                        newTarget = this.WrapWithDefaultWrapper(newTarget, defaultWrapperElement);
                    }

                    InternalLogger.Info("Adding target {0}", newTarget);
                    AddTarget(newTarget.Name, newTarget);
                    break;
                }
            }
        }
        private void ParseVariableElement(NLogXmlElement variableElement)
        {
            variableElement.AssertName("variable");

            string name = variableElement.GetRequiredAttribute("name");
            string value = this.ExpandSimpleVariables(variableElement.GetRequiredAttribute("value"));

            this.Variables[name] = value;
        }
        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)
                {
                    this.ConfigurationItemFactory.RegisterType(Type.GetType(type, true), prefix);
                }

                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.");

                        if (exception.MustBeRethrown())
                        {
                            throw new NLogConfigurationException("Error loading extensions: " + assemblyFile, exception);
                        }
                    }

                    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.");

                        if (exception.MustBeRethrown())
                        {
                            throw new NLogConfigurationException("Error loading extensions: " + assemblyName, exception);
                        }
                    }
                }
            }
        }
        private void ParseTargetsElement(NLogXmlElement targetsElement)
        {
            targetsElement.AssertName("targets", "appenders");

            bool asyncWrap = targetsElement.GetOptionalBooleanAttribute("async", false);
            NLogXmlElement defaultWrapperElement = null;
            var typeNameToDefaultTargetParameters = new Dictionary<string, NLogXmlElement>();

            foreach (var targetElement in targetsElement.Children)
            {
                string name = targetElement.LocalName;
                string typeAttributeVal = StripOptionalNamespacePrefix(targetElement.GetOptionalAttribute("type", null));

                switch (name.ToUpper(CultureInfo.InvariantCulture))
                {
                    case "DEFAULT-WRAPPER":
                        defaultWrapperElement = targetElement;
                        break;

                    case "DEFAULT-TARGET-PARAMETERS":
                        if (typeAttributeVal == null)
                        {
                            throw new NLogConfigurationException("Missing 'type' attribute on <" + name + "/>.");
                        }

                        typeNameToDefaultTargetParameters[typeAttributeVal] = targetElement;
                        break;

                    case "TARGET":
                    case "APPENDER":
                    case "WRAPPER":
                    case "WRAPPER-TARGET":
                    case "COMPOUND-TARGET":
                        if (typeAttributeVal == null)
                        {
                            throw new NLogConfigurationException("Missing 'type' attribute on <" + name + "/>.");
                        }

                        Target newTarget = this.ConfigurationItemFactory.Targets.CreateInstance(typeAttributeVal);

                        NLogXmlElement defaults;
                        if (typeNameToDefaultTargetParameters.TryGetValue(typeAttributeVal, out defaults))
                        {
                            this.ParseTargetElement(newTarget, defaults);
                        }

                        this.ParseTargetElement(newTarget, targetElement);

                        if (asyncWrap)
                        {
                            newTarget = WrapWithAsyncTargetWrapper(newTarget);
                        }

                        if (defaultWrapperElement != null)
                        {
                            newTarget = this.WrapWithDefaultWrapper(newTarget, defaultWrapperElement);
                        }

                        InternalLogger.Info("Adding target {0}", newTarget);
                        AddTarget(newTarget.Name, newTarget);
                        break;
                }
            }
        }