예제 #1
0
        public void NLogConfigurationExceptionShouldThrown_WhenVariableNodeIsWrittenToWrongPlace()
        {
            LogManager.ThrowConfigExceptions = true;
            const string configurationString_VariableNodeIsInnerTargets =
                @"<nlog>  
	                        <targets>
			                    <variable name='variableOne' value='${longdate:universalTime=True}Z | ${message}'/>
                                <target name='d1' type='Debug' layout='${variableOne}' />
	                        </targets>
                            <rules>
			                    <logger name='*' minlevel='Debug' writeTo='d1'/>
                            </rules>
                    </nlog>";


            const string configurationString_VariableNodeIsAfterTargets =
                @"<nlog>  
	                        <targets>
			                    <target name='d1' type='Debug' layout='${variableOne}' />
	                        </targets>
                            <variable name='variableOne' value='${longdate:universalTime=True}Z | ${message}'/>	
                            <rules>
			                    <logger name='*' minlevel='Debug' writeTo='d1'/>
                            </rules>
                    </nlog>";

            NLogConfigurationException nlogConfEx_ForInnerTargets = Assert.Throws <NLogConfigurationException>(
                () => CreateConfigurationFromString(configurationString_VariableNodeIsInnerTargets)
                );

            NLogConfigurationException nlogConfExForAfterTargets = Assert.Throws <NLogConfigurationException>(
                () => CreateConfigurationFromString(configurationString_VariableNodeIsAfterTargets)
                );
        }
예제 #2
0
        [InlineData(4194304)] // Is multiple of 64, but bigger than the max value of 4194240
        public void Configuration_ShouldThrowException_WhenMaxKilobytesIsInvalid(long?maxKilobytes)
        {
            string configrationText = $@"
            <nlog ThrowExceptions='true'>
                <targets>
                    <target type='EventLog' name='eventLog1' layout='${{message}}' maxKilobytes='{maxKilobytes}' />
                </targets>
                <rules>
                      <logger name='*' writeTo='eventLog1' />
                </rules>
            </nlog>";

            NLogConfigurationException ex = Assert.Throws <NLogConfigurationException>(() => XmlLoggingConfiguration.CreateFromXmlString(configrationText));

            Assert.Equal("MaxKilobytes must be a multiple of 64, and between 64 and 4194240", ex.InnerException.InnerException.Message);
        }
예제 #3
0
        public void ExceptionTests()
        {
            using (new InternalLoggerScope())
            {
                InternalLogger.LogLevel         = LogLevel.Trace;
                InternalLogger.LogToConsole     = true;
                InternalLogger.IncludeTimestamp = false;

                var ex1 = new Exception("e1");
                var ex2 = new Exception("e2", new Exception("inner"));
                var ex3 = new NLogConfigurationException("config error");
                var ex4 = new NLogConfigurationException("config error", ex2);
                var ex5 = new PathTooLongException();
                ex5.Data["key1"] = "value1";
                Exception ex6 = null;

                const string prefix   = " Exception: ";
                string       expected =
                    "Warn WWW" + prefix + ex1 + Environment.NewLine +
                    "Error EEE" + prefix + ex2 + Environment.NewLine +
                    "Fatal FFF" + prefix + ex3 + Environment.NewLine +
                    "Trace TTT" + prefix + ex4 + Environment.NewLine +
                    "Debug DDD" + prefix + ex5 + Environment.NewLine +
                    "Info III" + Environment.NewLine;

                StringWriter consoleOutWriter = new StringWriter()
                {
                    NewLine = Environment.NewLine
                };

                // Redirect the console output to a StringWriter.
                Console.SetOut(consoleOutWriter);

                // Named (based on LogLevel) public methods.

                InternalLogger.Warn(ex1, "WWW");
                InternalLogger.Error(ex2, "EEE");
                InternalLogger.Fatal(ex3, "FFF");
                InternalLogger.Trace(ex4, "TTT");
                InternalLogger.Debug(ex5, "DDD");
                InternalLogger.Info(ex6, "III");

                consoleOutWriter.Flush();
                var strings = consoleOutWriter.ToString();
                Assert.Equal(expected, strings);
            }
        }
예제 #4
0
        public void ConfigurationShouldThrowException_WhenMaxMessageLengthIsNegativeOrZero(int maxMessageLength)
        {
            string configrationText = string.Format(@"
            <nlog ThrowExceptions='true'>
                <targets>
                    <target type='EventLog' name='eventLog1' layout='${{message}}' maxmessagelength='{0}' />
                </targets>
                <rules>
                      <logger name='*' writeTo='eventLog1'>
                      </logger>
                    </rules>
            </nlog>", maxMessageLength);

            NLogConfigurationException ex = Assert.Throws <NLogConfigurationException>(() => CreateConfigurationFromString(configrationText));

            Assert.Equal("MaxMessageLength cannot be zero or negative.", ex.InnerException.InnerException.Message);
        }
예제 #5
0
 private static void SetDefaultPropertyValue(ConfigurationItemFactory configurationItemFactory, LayoutRenderer layoutRenderer, string value, bool?throwConfigExceptions)
 {
     // what we've just read is not a parameterName, but a value
     // assign it to a default property (denoted by empty string)
     if (PropertyHelper.TryGetPropertyInfo(layoutRenderer, string.Empty, out var propertyInfo))
     {
         PropertyHelper.SetPropertyFromString(layoutRenderer, propertyInfo.Name, value, configurationItemFactory);
     }
     else
     {
         var configException = new NLogConfigurationException($"{layoutRenderer.GetType()} has no default property to assign value {value}");
         if (throwConfigExceptions ?? configException.MustBeRethrown())
         {
             throw configException;
         }
     }
 }
예제 #6
0
        private static LayoutRenderer GetLayoutRenderer(ConfigurationItemFactory configurationItemFactory, string name, bool?throwConfigExceptions)
        {
            LayoutRenderer layoutRenderer;

            try
            {
                layoutRenderer = configurationItemFactory.LayoutRenderers.CreateInstance(name);
            }
            catch (Exception ex)
            {
                var configException = new NLogConfigurationException(ex, $"Error parsing layout {name}");
                if (throwConfigExceptions ?? configException.MustBeRethrown())
                {
                    throw configException;
                }
                // replace with empty values
                layoutRenderer = new LiteralLayoutRenderer(string.Empty);
            }
            return(layoutRenderer);
        }
예제 #7
0
        public void ExceptionTests()
        {
            using (new InternalLoggerScope())
            {
                InternalLogger.LogLevel         = LogLevel.Trace;
                InternalLogger.IncludeTimestamp = false;

                var ex1 = new Exception("e1");
                var ex2 = new Exception("e2", new Exception("inner"));
                var ex3 = new NLogConfigurationException("config error");
                var ex4 = new NLogConfigurationException("config error", ex2);
                var ex5 = new PathTooLongException();
                ex5.Data["key1"] = "value1";
                Exception ex6 = null;

                const string prefix = " Exception: ";

                {
                    string expected =
                        "Warn WWW1" + prefix + ex1 + Environment.NewLine +
                        "Error EEE1" + prefix + ex2 + Environment.NewLine +
                        "Fatal FFF1" + prefix + ex3 + Environment.NewLine +
                        "Trace TTT1" + prefix + ex4 + Environment.NewLine +
                        "Debug DDD1" + prefix + ex5 + Environment.NewLine +
                        "Info III1" + Environment.NewLine;

                    StringWriter consoleOutWriter = new StringWriter()
                    {
                        NewLine = Environment.NewLine
                    };

                    // Redirect the console output to a StringWriter.
                    InternalLogger.LogWriter = consoleOutWriter;

                    // Named (based on LogLevel) public methods.

                    InternalLogger.Warn(ex1, "WWW1");
                    InternalLogger.Error(ex2, "EEE1");
                    InternalLogger.Fatal(ex3, "FFF1");
                    InternalLogger.Trace(ex4, "TTT1");
                    InternalLogger.Debug(ex5, "DDD1");
                    InternalLogger.Info(ex6, "III1");

                    consoleOutWriter.Flush();
                    var strings = consoleOutWriter.ToString();

                    Assert.Equal(expected, strings);
                }
                {
                    string expected =
                        "Warn WWW2" + prefix + ex1 + Environment.NewLine +
                        "Error EEE2" + prefix + ex2 + Environment.NewLine +
                        "Fatal FFF2" + prefix + ex3 + Environment.NewLine +
                        "Trace TTT2" + prefix + ex4 + Environment.NewLine +
                        "Debug DDD2" + prefix + ex5 + Environment.NewLine +
                        "Info III2" + Environment.NewLine;

                    StringWriter consoleOutWriter = new StringWriter()
                    {
                        NewLine = Environment.NewLine
                    };

                    // Redirect the console output to a StringWriter.
                    InternalLogger.LogWriter = consoleOutWriter;

                    // Named (based on LogLevel) public methods.

                    InternalLogger.Warn(ex1, () => "WWW2");
                    InternalLogger.Error(ex2, () => "EEE2");
                    InternalLogger.Fatal(ex3, () => "FFF2");
                    InternalLogger.Trace(ex4, () => "TTT2");
                    InternalLogger.Debug(ex5, () => "DDD2");
                    InternalLogger.Info(ex6, () => "III2");

                    consoleOutWriter.Flush();
                    var strings = consoleOutWriter.ToString();
                    Assert.Equal(expected, strings);
                }
                {
                    string expected =
                        "Warn WWW3" + prefix + ex1 + Environment.NewLine +
                        "Error EEE3" + prefix + ex2 + Environment.NewLine +
                        "Fatal FFF3" + prefix + ex3 + Environment.NewLine +
                        "Trace TTT3" + prefix + ex4 + Environment.NewLine +
                        "Debug DDD3" + prefix + ex5 + Environment.NewLine +
                        "Info III3" + Environment.NewLine;

                    StringWriter consoleOutWriter = new StringWriter()
                    {
                        NewLine = Environment.NewLine
                    };

                    // Redirect the console output to a StringWriter.
                    InternalLogger.LogWriter = consoleOutWriter;

                    // Named (based on LogLevel) public methods.

                    InternalLogger.Log(ex1, LogLevel.Warn, "WWW3");
                    InternalLogger.Log(ex2, LogLevel.Error, "EEE3");
                    InternalLogger.Log(ex3, LogLevel.Fatal, "FFF3");
                    InternalLogger.Log(ex4, LogLevel.Trace, "TTT3");
                    InternalLogger.Log(ex5, LogLevel.Debug, "DDD3");
                    InternalLogger.Log(ex6, LogLevel.Info, "III3");

                    consoleOutWriter.Flush();
                    var strings = consoleOutWriter.ToString();
                    Assert.Equal(expected, strings);
                }
                {
                    string expected =
                        "Warn WWW4" + prefix + ex1 + Environment.NewLine +
                        "Error EEE4" + prefix + ex2 + Environment.NewLine +
                        "Fatal FFF4" + prefix + ex3 + Environment.NewLine +
                        "Trace TTT4" + prefix + ex4 + Environment.NewLine +
                        "Debug DDD4" + prefix + ex5 + Environment.NewLine +
                        "Info III4" + Environment.NewLine;

                    StringWriter consoleOutWriter = new StringWriter()
                    {
                        NewLine = Environment.NewLine
                    };

                    // Redirect the console output to a StringWriter.
                    InternalLogger.LogWriter = consoleOutWriter;

                    // Named (based on LogLevel) public methods.

                    InternalLogger.Log(ex1, LogLevel.Warn, () => "WWW4");
                    InternalLogger.Log(ex2, LogLevel.Error, () => "EEE4");
                    InternalLogger.Log(ex3, LogLevel.Fatal, () => "FFF4");
                    InternalLogger.Log(ex4, LogLevel.Trace, () => "TTT4");
                    InternalLogger.Log(ex5, LogLevel.Debug, () => "DDD4");
                    InternalLogger.Log(ex6, LogLevel.Info, () => "III4");

                    var strings = consoleOutWriter.ToString();
                    Assert.Equal(expected, strings);
                }
            }
        }
예제 #8
0
        public void ExceptionTests()
        {
            using (new InternalLoggerScope())
            {
                InternalLogger.LogLevel = LogLevel.Trace;
                InternalLogger.LogToConsole = true;
                InternalLogger.IncludeTimestamp = false;

                var ex1 = new Exception("e1");
                var ex2 = new Exception("e2", new Exception("inner"));
                var ex3 = new NLogConfigurationException("config error");
                var ex4 = new NLogConfigurationException("config error", ex2);
                var ex5 = new PathTooLongException();
                ex5.Data["key1"] = "value1";
                Exception ex6 = null;

                const string prefix = " Exception: ";
                string expected =
                    "Warn WWW" + prefix + ex1 + Environment.NewLine +
                    "Error EEE" + prefix + ex2 + Environment.NewLine +
                    "Fatal FFF" + prefix + ex3 + Environment.NewLine +
                    "Trace TTT" + prefix + ex4 + Environment.NewLine +
                    "Debug DDD" + prefix + ex5 + Environment.NewLine +
                    "Info III" + Environment.NewLine;

                StringWriter consoleOutWriter = new StringWriter()
                {
                    NewLine = Environment.NewLine
                };

                // Redirect the console output to a StringWriter.
                Console.SetOut(consoleOutWriter);

                // Named (based on LogLevel) public methods.

                InternalLogger.Warn(ex1, "WWW");
                InternalLogger.Error(ex2, "EEE");
                InternalLogger.Fatal(ex3, "FFF");
                InternalLogger.Trace(ex4, "TTT");
                InternalLogger.Debug(ex5, "DDD");
                InternalLogger.Info(ex6, "III");

                consoleOutWriter.Flush();
                var strings = consoleOutWriter.ToString();
                Assert.Equal(expected, strings);
            }

        }
예제 #9
0
        private static LayoutRenderer ParseLayoutRenderer(ConfigurationItemFactory configurationItemFactory, SimpleStringReader stringReader, bool?throwConfigExceptions)
        {
            int ch = stringReader.Read();

            Debug.Assert(ch == '{', "'{' expected in layout specification");

            string name           = ParseLayoutRendererName(stringReader);
            var    layoutRenderer = GetLayoutRenderer(configurationItemFactory, name, throwConfigExceptions);

            Dictionary <Type, LayoutRenderer> wrappers        = null;
            List <LayoutRenderer>             orderedWrappers = null;

            ch = stringReader.Read();
            while (ch != -1 && ch != '}')
            {
                string parameterName = ParseParameterName(stringReader).Trim();
                if (stringReader.Peek() == '=')
                {
                    stringReader.Read(); // skip the '='
                    LayoutRenderer parameterTarget = layoutRenderer;

                    if (!PropertyHelper.TryGetPropertyInfo(layoutRenderer, parameterName, out var propertyInfo))
                    {
                        if (configurationItemFactory.AmbientProperties.TryGetDefinition(parameterName, out var wrapperType))
                        {
                            wrappers        = wrappers ?? new Dictionary <Type, LayoutRenderer>();
                            orderedWrappers = orderedWrappers ?? new List <LayoutRenderer>();
                            if (!wrappers.TryGetValue(wrapperType, out var wrapperRenderer))
                            {
                                wrapperRenderer       = configurationItemFactory.AmbientProperties.CreateInstance(parameterName);
                                wrappers[wrapperType] = wrapperRenderer;
                                orderedWrappers.Add(wrapperRenderer);
                            }

                            if (!PropertyHelper.TryGetPropertyInfo(wrapperRenderer, parameterName, out propertyInfo))
                            {
                                propertyInfo = null;
                            }
                            else
                            {
                                parameterTarget = wrapperRenderer;
                            }
                        }
                    }

                    if (propertyInfo == null)
                    {
                        var value = ParseParameterValue(stringReader);
                        if (!string.IsNullOrEmpty(parameterName) || !StringHelpers.IsNullOrWhiteSpace(value))
                        {
                            var configException = new NLogConfigurationException($"Unknown property '{parameterName}={value}` for ${{{name}}} ({layoutRenderer?.GetType()})");
                            if (throwConfigExceptions ?? configException.MustBeRethrown())
                            {
                                throw configException;
                            }
                        }
                    }
                    else
                    {
                        if (typeof(Layout).IsAssignableFrom(propertyInfo.PropertyType))
                        {
                            LayoutRenderer[] renderers = CompileLayout(configurationItemFactory, stringReader, throwConfigExceptions, true, out var txt);

                            var nestedLayout = new SimpleLayout(renderers, txt, configurationItemFactory);
                            propertyInfo.SetValue(parameterTarget, nestedLayout, null);
                        }
                        else if (typeof(ConditionExpression).IsAssignableFrom(propertyInfo.PropertyType))
                        {
                            var conditionExpression = ConditionParser.ParseExpression(stringReader, configurationItemFactory);
                            propertyInfo.SetValue(parameterTarget, conditionExpression, null);
                        }
                        else
                        {
                            string value = ParseParameterValue(stringReader);
                            PropertyHelper.SetPropertyFromString(parameterTarget, parameterName, value, configurationItemFactory);
                        }
                    }
                }
                else
                {
                    SetDefaultPropertyValue(configurationItemFactory, layoutRenderer, parameterName, throwConfigExceptions);
                }

                ch = stringReader.Read();
            }

            if (orderedWrappers != null)
            {
                layoutRenderer = ApplyWrappers(configurationItemFactory, layoutRenderer, orderedWrappers);
            }

            return(layoutRenderer);
        }