示例#1
0
文件: TimeTests.cs 项目: ywscr/NLog
        public void TimeTest()
        {
            LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
            <nlog>
                <targets><target name='debug' type='Debug' layout='${time}' /></targets>
                <rules>
                    <logger name='*' minlevel='Debug' writeTo='debug' />
                </rules>
            </nlog>");

            LogManager.GetLogger("d").Debug("zzz");
            string date = GetDebugLastMessage("debug");

            Assert.Equal(13, date.Length);
            Assert.Equal(':', date[2]);
            Assert.Equal(':', date[5]);
            Assert.Equal('.', date[8]);
        }
示例#2
0
        public void ShowFileNameOnlyAsyncTest()
        {
            LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
            <nlog>
                <targets><target name='debug' type='Debug' layout='${callsite-filename:includeSourcePath=False}|${message}' /></targets>
                <rules>
                    <logger name='*' minlevel='Debug' writeTo='debug' />
                </rules>
            </nlog>");

            AsyncMethod().Wait();

            var lastMessage      = GetDebugLastMessage("debug");
            var lastMessageArray = lastMessage.Split('|');

            Assert.Equal("CallSiteFileNameLayoutTests.cs", lastMessageArray[0]);
            Assert.Equal("msg", lastMessageArray[1]);
        }
        public void TraceWriteNonDefaultLevelTest()
        {
            LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
                <nlog>
                    <targets><target name='debug' type='Debug' layout='${logger} ${level} ${message}' /></targets>
                    <rules>
                        <logger name='*' minlevel='Trace' writeTo='debug' />
                    </rules>
                </nlog>");

            Trace.Listeners.Clear();
            Trace.Listeners.Add(new NLogTraceListener {
                Name = "Logger1", DefaultLogLevel = LogLevel.Trace
            });

            Trace.Write("Hello");
            AssertDebugLastMessage("debug", "Logger1 Trace Hello");
        }
        public void AutoLoggerNameTest()
        {
            LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
                <nlog>
                    <targets><target name='debug' type='Debug' layout='${logger} ${level} ${message}' /></targets>
                    <rules>
                        <logger name='*' minlevel='Debug' writeTo='debug' />
                    </rules>
                </nlog>");

            Trace.Listeners.Clear();
            Trace.Listeners.Add(new NLogTraceListener {
                Name = "Logger1", AutoLoggerName = true
            });

            Trace.Write("Hello");
            AssertDebugLastMessage("debug", GetType().FullName + " Debug Hello");
        }
示例#5
0
        public void Flush_DoNotThrowExceptionsAndTimeout_DoesNotThrow()
        {
            using (new NoThrowNLogExceptions())
            {
                LogManager.ThrowExceptions = true;

                LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
                <nlog throwExceptions='false'>
                    <targets><target type='MethodCall' name='test' methodName='Throws' className='NLog.UnitTests.LogFactoryTests, NLog.UnitTests.netfx40' /></targets>
                    <rules>
                        <logger name='*' minlevel='Debug' writeto='test'></logger>
                    </rules>
                </nlog>");

                ILogger logger = LogManager.GetCurrentClassLogger();
                logger.Factory.Flush(_ => { }, TimeSpan.FromMilliseconds(1));
            }
        }
        public void RenderStackTrace_raw()
        {
            LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
            <nlog>
                <targets><target name='debug' type='Debug' layout='${message} ${stacktrace:format=Raw}' /></targets>
                <rules>
                    <logger name='*' minlevel='Debug' writeTo='debug' />
                </rules>
            </nlog>");

            RenderMe("I am:");

            AssertDebugLastMessageContains("debug", "RenderStackTrace_raw at offset ");
            AssertDebugLastMessageContains("debug", "RenderMe at offset ");
#if !MONO
            AssertDebugLastMessageContains("debug", "StackTraceRendererTests.cs");
#endif
        }
        public void HostNameTest()
        {
            LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
            <nlog>
                <targets><target name='debug' type='Debug' layout='${hostname} ${message}' /></targets>
                <rules>
                    <logger name='*' minlevel='Debug' writeTo='debug' />
                </rules>
            </nlog>");

            // Get the actual hostname that the code would use
            string h = Environment.GetEnvironmentVariable("HOSTNAME")
                       ?? System.Net.Dns.GetHostName()
                       ?? Environment.GetEnvironmentVariable("COMPUTERNAME");

            LogManager.GetLogger("A").Debug("a log message");
            AssertDebugLastMessage("debug", h + " a log message");
        }
示例#8
0
        public void Bug3990StackOverflowWhenUsingNLogViewerTarget()
        {
            // this would fail because of stack overflow in the
            // constructor of NLogViewerTarget
            var config = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
  <targets>
    <target name='viewer' type='NLogViewer' address='udp://127.0.0.1:9999' />
  </targets>
  <rules>
    <logger name='*' minlevel='Debug' writeTo='viewer' />
  </rules>
</nlog>");

            var target = config.LoggingRules[0].Targets[0] as NLogViewerTarget;

            Assert.NotNull(target);
        }
示例#9
0
        public void ThreadNameTest()
        {
            LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
            <nlog>
                <targets><target name='debug' type='Debug' layout='${threadname} ${message}' /></targets>
                <rules>
                    <logger name='*' minlevel='Debug' writeTo='debug' />
                </rules>
            </nlog>");

            if (System.Threading.Thread.CurrentThread.Name == null)
            {
                System.Threading.Thread.CurrentThread.Name = "mythreadname";
            }

            LogManager.GetLogger("A").Debug("a");
            AssertDebugLastMessage("debug", System.Threading.Thread.CurrentThread.Name + " a");
        }
示例#10
0
        public void UnusedTargetsShouldBeLoggedToInternalLogger_PermitWrapped()
        {
            string tempFileName = Path.GetTempFileName();

            try
            {
                XmlLoggingConfiguration.CreateFromXmlString("<nlog internalLogFile='" + tempFileName + @"' internalLogLevel='Warn'>
                    <extensions>
                        <add assembly='NLog.UnitTests'/> 
                    </extensions>
                    <targets>
                        <target name='d1' type='Debug' />
                        <target name='d2' type='MockWrapper'>
                            <target name='d3' type='Debug' />
                        </target>
                        <target name='d4' type='Debug' />
                        <target name='d5' type='Debug' />
                    </targets>

                    <rules>
                           <logger name='*' level='Debug' writeTo='d1' />
                           <logger name='*' level='Debug' writeTo='d1,d2,d4' />
                    </rules>
                </nlog>");


                AssertFileNotContains(tempFileName, "Unused target detected. Add a rule for this target to the configuration. TargetName: d2", Encoding.UTF8);

                AssertFileNotContains(tempFileName, "Unused target detected. Add a rule for this target to the configuration. TargetName: d3", Encoding.UTF8);

                AssertFileNotContains(tempFileName, "Unused target detected. Add a rule for this target to the configuration. TargetName: d4", Encoding.UTF8);

                AssertFileContains(tempFileName, "Unused target detected. Add a rule for this target to the configuration. TargetName: d5", Encoding.UTF8);
            }

            finally
            {
                NLog.Common.InternalLogger.Reset();
                if (File.Exists(tempFileName))
                {
                    File.Delete(tempFileName);
                }
            }
        }
示例#11
0
        public void NoHeadersTest()
        {
            string tempFile = string.Empty;

            try
            {
                tempFile = Path.GetTempFileName();
                LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
            <nlog>
                <targets>
                  <target name='f' type='File' fileName='" + tempFile + @"'>
                    <layout type='CSVLayout' withHeader='false'>
                      <delimiter>Comma</delimiter>
                      <column name='level' layout='${level}' />
                      <column name='message' layout='${message}' />
                      <column name='counter' layout='${counter}' />
                    </layout>
                  </target>
                </targets>
                <rules>
                    <logger name='*' minlevel='Debug' writeTo='f' />
                </rules>
            </nlog>");

                ILogger logger = LogManager.GetLogger("A");
                logger.Debug("msg");
                logger.Info("msg2");
                logger.Warn("Message with, a comma");

                using (StreamReader sr = File.OpenText(tempFile))
                {
                    Assert.Equal("Debug,msg,1", sr.ReadLine());
                    Assert.Equal("Info,msg2,2", sr.ReadLine());
                    Assert.Equal("Warn,\"Message with, a comma\",3", sr.ReadLine());
                }
            }
            finally
            {
                if (File.Exists(tempFile))
                {
                    File.Delete(tempFile);
                }
            }
        }
示例#12
0
        public void ExtensionWithPrefixTest()
        {
            var configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog throwExceptions='true'>
    <extensions>
        <add prefix='myprefix' assemblyFile='" + GetExtensionAssemblyFullPath() + @"' />
    </extensions>

    <targets>
        <target name='t' type='myprefix.MyTarget' />
        <target name='d1' type='Debug' layout='${myprefix.foo}' />
        <target name='d2' type='Debug'>
            <layout type='myprefix.FooLayout' x='1'>
            </layout>
        </target>
    </targets>

    <rules>
      <logger name='*' writeTo='t'>
        <filters>
           <myprefix.whenFoo x='44' action='Ignore' />
        </filters>
      </logger>
    </rules>
</nlog>");

            Target myTarget = configuration.FindTargetByName("t");

            Assert.Equal("MyExtensionNamespace.MyTarget", myTarget.GetType().FullName);

            var d1Target = (DebugTarget)configuration.FindTargetByName("d1");
            var layout   = d1Target.Layout as SimpleLayout;

            Assert.NotNull(layout);
            Assert.Single(layout.Renderers);
            Assert.Equal("MyExtensionNamespace.FooLayoutRenderer", layout.Renderers[0].GetType().FullName);

            var d2Target = (DebugTarget)configuration.FindTargetByName("d2");

            Assert.Equal("MyExtensionNamespace.FooLayout", d2Target.Layout.GetType().FullName);

            Assert.Equal(1, configuration.LoggingRules[0].Filters.Count);
            Assert.Equal("MyExtensionNamespace.WhenFooFilter", configuration.LoggingRules[0].Filters[0].GetType().FullName);
        }
示例#13
0
        internal static void ConsoleRaceCondtionIgnoreInnerTest(string configXml)
        {
            LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(configXml);

            //   Console.Out.Writeline / Console.Error.Writeline could throw 'IndexOutOfRangeException', which is a bug.
            // See https://stackoverflow.com/questions/33915790/console-out-and-console-error-race-condition-error-in-a-windows-service-written
            // and https://connect.microsoft.com/VisualStudio/feedback/details/2057284/console-out-probable-i-o-race-condition-issue-in-multi-threaded-windows-service
            //
            // Full error:
            //   Error during session close: System.IndexOutOfRangeException: Probable I/ O race condition detected while copying memory.
            //   The I/ O package is not thread safe by default.In multithreaded applications,
            //   a stream must be accessed in a thread-safe way, such as a thread - safe wrapper returned by TextReader's or
            //   TextWriter's Synchronized methods.This also applies to classes like StreamWriter and StreamReader.

            var oldOut   = Console.Out;
            var oldError = Console.Error;

            try
            {
                Console.SetOut(StreamWriter.Null);
                Console.SetError(StreamWriter.Null);


                LogManager.ThrowExceptions = true;
                var logger = LogManager.GetCurrentClassLogger();


                Parallel.For(0, 10, new ParallelOptions()
                {
                    MaxDegreeOfParallelism = 10
                }, (_) =>
                {
                    for (int i = 0; i < 100; i++)
                    {
                        logger.Trace("test message to the out and error stream");
                    }
                });
            }
            finally
            {
                Console.SetOut(oldOut);
                Console.SetError(oldError);
            }
        }
示例#14
0
        [InlineData(16384)]   // Acceptable value
        public void ConfigurationMaxKilobytes_ShouldBeAsSpecified_WhenMaxKilobytesIsValid(long?maxKilobytes)
        {
            var expectedMaxKilobytes = maxKilobytes;

            string configrationText            = $@"
            <nlog ThrowExceptions='true'>
                <targets>
                    <target type='EventLog' name='eventLog1' layout='${{message}}' maxKilobytes='{maxKilobytes}' />
                </targets>
                <rules>
                      <logger name='*' writeTo='eventLog1' />
                </rules>
            </nlog>";
            LoggingConfiguration configuration = XmlLoggingConfiguration.CreateFromXmlString(configrationText);

            var eventLog1 = configuration.FindTargetByName <EventLogTarget>("eventLog1");

            Assert.Equal(expectedMaxKilobytes, eventLog1.MaxKilobytes);
        }
示例#15
0
        public void SingleLevelTest()
        {
            LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@"
            <nlog>
                <targets>
                    <target name='d1' type='Debug' />
                </targets>

                <rules>
                    <logger name='*' level='Warn' writeTo='d1' />
                </rules>
            </nlog>");

            Assert.Equal(1, c.LoggingRules.Count);
            var rule = c.LoggingRules[0];

            Assert.Single(rule.Levels);
            Assert.Contains(LogLevel.Warn, rule.Levels);
        }
示例#16
0
            static LoggingConfiguration InitNLogConfig()
            {
                // https://github.com/NLog/NLog/wiki/Getting-started-with-ASP.NET-Core-5
                var xmlConfigStr =
                    "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" +
                    "<nlog xmlns=\"http://www.nlog-project.org/schemas/NLog.xsd\"" +
                    "      xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"" +
                    "      autoReload=\"true\"" +
                    "      internalLogLevel=\"info\"" +
                    "      internalLogFile=\"logs" + Path.DirectorySeparatorChar + "internal-nlog.txt\">" +
                    // enable asp.net core layout renderers
                    "  <extensions>" +
                    "    <add assembly=\"NLog.Web.AspNetCore\"/>" +
                    "  </extensions>" +
                    // the targets to write to
                    "  <targets>" +
                    // write logs to file
                    "    <target xsi:type=\"File\" name=\"allfile\" fileName=\"logs" + Path.DirectorySeparatorChar + "nlog-all-${shortdate}.log\"" +
                    "            layout=\"${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}\"/>" +
                    // another file log, only own logs. Uses some ASP.NET core renderers
                    "    <target xsi:type=\"File\" name=\"ownFile-web\" fileName=\"logs" + Path.DirectorySeparatorChar + "nlog-own-${shortdate}.log\"" +
                    "            layout=\"${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}\"/>" +
                    // Console Target for hosting lifetime messages to improve Docker / Visual Studio startup detection
                    "    <target xsi:type=\"Console\" name=\"lifetimeConsole\" layout=\"${level:truncate=4:tolower=true}\\: ${logger}[0]${newline}      ${message}${exception:format=tostring}\" />" +
                    "  </targets>" +
                    // rules to map from logger name to target
                    "  <rules>" +
                    // All logs, including from Microsoft
                    "    <logger name=\"*\" minlevel=\"Trace\" writeTo=\"allfile\"/>" +
                    // Output hosting lifetime messages to console target for faster startup detection
                    "    <logger name=\"Microsoft.Hosting.Lifetime\" minlevel=\"Info\" writeTo=\"lifetimeConsole, ownFile-web\" final=\"true\" />" +
                    // Skip non-critical Microsoft logs and so log only own logs
                    "    <logger name=\"Microsoft.*\" maxLevel=\"Info\" final=\"true\"/>" +
                    "    <logger name=\"System.Net.Http.*\" maxlevel=\"Info\" final=\"true\" />" +
                    // BlackHole without writeTo
                    "    <logger name=\"*\" minlevel=\"Trace\" writeTo=\"ownFile-web\"/>" +
                    "  </rules>" +
                    "</nlog>";

                var xmlConfig = XmlLoggingConfiguration.CreateFromXmlString(xmlConfigStr);

                return(xmlConfig);
            }
        public void ArrayElementParameterTest()
        {
            LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@"
            <nlog>
                <targets>
                    <target type='MethodCall' name='mct'>
                        <parameter>
                            <name>p1</name>
                            <layout>${message}</layout>
                        </parameter>
                        <parameter>
                            <name>p2</name>
                            <layout type='CsvLayout'>
                                <column name='x' layout='${message}' />
                                <column name='y' layout='${level}' />
                            </layout>
                        </parameter>
                        <parameter>
                            <name>p3</name>
                            <layout>${logger}</layout>
                        </parameter>
                    </target>
                </targets>
            </nlog>");

            var t = c.FindTargetByName("mct") as MethodCallTarget;

            Assert.NotNull(t);
            Assert.Equal(3, t.Parameters.Count);
            Assert.Equal("p1", t.Parameters[0].Name);
            Assert.Equal("'${message}'", t.Parameters[0].Layout.ToString());

            Assert.Equal("p2", t.Parameters[1].Name);
            CsvLayout csvLayout = t.Parameters[1].Layout as CsvLayout;

            Assert.NotNull(csvLayout);
            Assert.Equal(2, csvLayout.Columns.Count);
            Assert.Equal("x", csvLayout.Columns[0].Name);
            Assert.Equal("y", csvLayout.Columns[1].Name);

            Assert.Equal("p3", t.Parameters[2].Name);
            Assert.Equal("'${logger}'", t.Parameters[2].Layout.ToString());
        }
示例#18
0
        void FuncLayoutRendererRegisterTest1WithXML()
        {
            LayoutRenderer.Register("the-answer", (info) => 42);

            LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog throwExceptions='true'>
            
                <targets>
                    <target name='debug' type='Debug' layout= 'TheAnswer=${the-answer:Format=D3}' /></targets>
                <rules>
                    <logger name='*' minlevel='Debug' writeTo='debug' />
                </rules>
            </nlog>");

            var logger = LogManager.GetCurrentClassLogger();

            logger.Debug("test1");
            AssertDebugLastMessage("debug", "TheAnswer=042");
        }
        public void CompoundTest()
        {
            LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@"
            <nlog>
                <targets>
                    <compound-target name='rr' type='RoundRobinGroup'>
                        <target name='d1' type='Debug' layout='${message}1' />
                        <target name='d2' type='Debug' layout='${message}2' />
                        <target name='d3' type='Debug' layout='${message}3' />
                        <target name='d4' type='Debug' layout='${message}4' />
                    </compound-target>
                </targets>
            </nlog>");

            Assert.NotNull(c.FindTargetByName("rr"));
            Assert.NotNull(c.FindTargetByName("d1"));
            Assert.NotNull(c.FindTargetByName("d2"));
            Assert.NotNull(c.FindTargetByName("d3"));
            Assert.NotNull(c.FindTargetByName("d4"));

            Assert.IsType <RoundRobinGroupTarget>(c.FindTargetByName("rr"));
            Assert.IsType <DebugTarget>(c.FindTargetByName("d1"));
            Assert.IsType <DebugTarget>(c.FindTargetByName("d2"));
            Assert.IsType <DebugTarget>(c.FindTargetByName("d3"));
            Assert.IsType <DebugTarget>(c.FindTargetByName("d4"));

            RoundRobinGroupTarget rr = c.FindTargetByName("rr") as RoundRobinGroupTarget;
            DebugTarget           d1 = c.FindTargetByName("d1") as DebugTarget;
            DebugTarget           d2 = c.FindTargetByName("d2") as DebugTarget;
            DebugTarget           d3 = c.FindTargetByName("d3") as DebugTarget;
            DebugTarget           d4 = c.FindTargetByName("d4") as DebugTarget;

            Assert.Equal(4, rr.Targets.Count);
            Assert.Same(d1, rr.Targets[0]);
            Assert.Same(d2, rr.Targets[1]);
            Assert.Same(d3, rr.Targets[2]);
            Assert.Same(d4, rr.Targets[3]);

            Assert.Equal("${message}1", ((SimpleLayout)d1.Layout).Text);
            Assert.Equal("${message}2", ((SimpleLayout)d2.Layout).Text);
            Assert.Equal("${message}3", ((SimpleLayout)d3.Layout).Text);
            Assert.Equal("${message}4", ((SimpleLayout)d4.Layout).Text);
        }
示例#20
0
        public void ExceptionWithStackTraceTest()
        {
            LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
            <nlog>
                <targets>
                    <target name='debug1' type='Debug' layout='${exception}' />
                    <target name='debug2' type='Debug' layout='${exception:format=stacktrace}' />
                    <target name='debug3' type='Debug' layout='${exception:format=type}' />
                    <target name='debug4' type='Debug' layout='${exception:format=shorttype}' />
                    <target name='debug5' type='Debug' layout='${exception:format=tostring}' />
                    <target name='debug6' type='Debug' layout='${exception:format=message}' />
                    <target name='debug7' type='Debug' layout='${exception:format=method}' />
                    <target name='debug8' type='Debug' layout='${exception:format=message,shorttype:separator=*}' />
                    <target name='debug9' type='Debug' layout='${exception:format=data}' />
                </targets>
                <rules>
                    <logger minlevel='Info' writeTo='debug1,debug2,debug3,debug4,debug5,debug6,debug7,debug8,debug9' />
                </rules>
            </nlog>");

            const string exceptionMessage   = "Test exception";
            const string exceptionDataKey   = "testkey";
            const string exceptionDataValue = "testvalue";
            Exception    ex = GetExceptionWithStackTrace(exceptionMessage);

            ex.Data.Add(exceptionDataKey, exceptionDataValue);
            logger.Error(ex, "msg");
            AssertDebugLastMessage("debug1", exceptionMessage);
            AssertDebugLastMessage("debug2", ex.StackTrace);
            AssertDebugLastMessage("debug3", typeof(CustomArgumentException).FullName);
            AssertDebugLastMessage("debug4", typeof(CustomArgumentException).Name);
            AssertDebugLastMessage("debug5", ex.ToString());
            AssertDebugLastMessage("debug6", exceptionMessage);
            AssertDebugLastMessage("debug9", string.Format(ExceptionDataFormat, exceptionDataKey, exceptionDataValue));

            // each version of the framework produces slightly different information for MethodInfo, so we just
            // make sure it's not empty
            var debug7Target = (DebugTarget)LogManager.Configuration.FindTargetByName("debug7");

            Assert.False(string.IsNullOrEmpty(debug7Target.LastMessage));

            AssertDebugLastMessage("debug8", exceptionMessage + "*" + typeof(CustomArgumentException).Name);
        }
示例#21
0
        public void PerformanceCounterLayoutRendererTest()
        {
            LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
            <nlog>
                <targets><target name='debug' type='Debug' layout='${performancecounter:category=Process:counter=Working Set:format=F0:MachineName=}' /></targets>
                <rules>
                    <logger name='*' minlevel='Debug' writeTo='debug' />
                </rules>
            </nlog>");

            ILogger logger = LogManager.GetLogger("A");

            logger.Debug("a");
            Assert.NotEqual(0, long.Parse(GetDebugLastMessage("debug")));
            logger.Debug("b");
            logger.Debug("c");
            logger.Debug("d");
            Assert.NotEqual(0, long.Parse(GetDebugLastMessage("debug")));
        }
示例#22
0
        [InlineData("1:0:0:0", 86400)] //1 day
        public void SetTimeSpanFromXmlTest(string interval, int seconds)
        {
            var config = XmlLoggingConfiguration.CreateFromXmlString($@"
            <nlog throwExceptions='true'>
                <targets>
                    <wrapper-target name='limiting' type='LimitingWrapper' messagelimit='5'  interval='{interval}'>
                        <target name='debug' type='Debug' layout='${{message}}' />
                    </wrapper-target>
                </targets>
                <rules>
                    <logger name='*' level='Debug' writeTo='limiting' />
                </rules>
            </nlog>");

            var target = config.FindTargetByName <LimitingTargetWrapper>("limiting");

            Assert.NotNull(target);
            Assert.Equal(TimeSpan.FromSeconds(seconds), target.Interval);
        }
示例#23
0
        public void LineNumberOnlyAsyncTest()
        {
            LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
        <nlog>
            <targets><target name='debug' type='Debug' layout='${callsite-linenumber}' /></targets>
            <rules>
                <logger name='*' minlevel='Debug' writeTo='debug' />
            </rules>
        </nlog>");

            ILogger       logger         = LogManager.GetLogger("A");
            Func <string> getLastMessage = () => GetDebugLastMessage("debug");

            logger.Debug("msg");
            var lastMessage = getLastMessage();

            Assert.NotEqual(0, int.Parse(lastMessage));
            WriteMessages(logger, getLastMessage).Wait();
        }
示例#24
0
        public void WebserviceTest_restapi_xml()
        {
            var configuration = XmlLoggingConfiguration.CreateFromXmlString($@"
                <nlog throwExceptions='true'>
                    <targets>
                        <target type='WebService'
                                name='ws'
                                url='{getWsAddress(1)}{"api/logdoc/xml"}'
                                protocol='XmlPost'
                                XmlRoot='ComplexType'
                                encoding='UTF-8'
                               >
                            <parameter name='param1' ParameterType='System.String' layout='${{message}}'/> 
                            <parameter name='param2' ParameterType='System.String' layout='${{level}}'/>
                            <parameter name='param3' ParameterType='System.Boolean' layout='True'/>
                            <parameter name='param4' ParameterType='System.DateTime' layout='${{date:universalTime=true:format=o}}'/>
                        </target>
                    </targets>
                    <rules>
                      <logger name='*' writeTo='ws'>
                       
                      </logger>
                    </rules>
                </nlog>");


            LogManager.Configuration = configuration;
            var logger = LogManager.GetCurrentClassLogger();

            var txt     = "message 1 with a XML POST<hello><again\\>\""; // Lets tease the Xml-Serializer, and see it can handle xml-tags
            var count   = 101;
            var context = new LogDocController.TestContext(1, count, true, null, txt, "info", true, DateTime.UtcNow);

            StartOwinDocTest(context, () =>
            {
                for (int i = 0; i < count; i++)
                {
                    logger.Info(txt + "\b");    // Lets tease the Xml-Serializer, and see it can remove invalid chars
                }
            });

            Assert.Equal <int>(0, context.CountdownEvent.CurrentCount);
        }
示例#25
0
        public void Xml_configuration_with_innerLayouts_returns_defined_variables()
        {
            var configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog throwExceptions='true'>
    <variable name='myJson'  >
        <layout type='JsonLayout'>
            <attribute name='short date' layout='${shortdate}' />
            <attribute name='message' layout='${message}' />
        </layout>
    </variable>
</nlog>");

            // Act & Assert
            var jsonLayout = Assert.IsType <JsonLayout>(configuration.Variables["myJson"]);

            Assert.Equal(2, jsonLayout.Attributes.Count);
            Assert.Equal("short date", jsonLayout.Attributes[0].Name);
            Assert.NotNull(jsonLayout.Attributes[0].Layout);
        }
示例#26
0
        public void ParseNLogInternalLoggerPathTest()
        {
            using (new InternalLoggerScope(true))
            {
                var xml    = "<nlog internalLogFile='${CurrentDir}test.txt'></nlog>";
                var config = XmlLoggingConfiguration.CreateFromXmlString(xml);
                Assert.Contains(System.IO.Directory.GetCurrentDirectory(), InternalLogger.LogFile);
            }

            using (new InternalLoggerScope(true))
            {
                var xml    = "<nlog internalLogFile='${BaseDir}test.txt'></nlog>";
                var config = XmlLoggingConfiguration.CreateFromXmlString(xml);
                Assert.Contains(AppDomain.CurrentDomain.BaseDirectory, InternalLogger.LogFile);
            }

            using (new InternalLoggerScope(true))
            {
                var xml    = "<nlog internalLogFile='${TempDir}test.txt'></nlog>";
                var config = XmlLoggingConfiguration.CreateFromXmlString(xml);
                Assert.Contains(System.IO.Path.GetTempPath(), InternalLogger.LogFile);
            }

#if !NETSTANDARD1_3
            using (new InternalLoggerScope(true))
            {
                var xml    = "<nlog internalLogFile='${ProcessDir}test.txt'></nlog>";
                var config = XmlLoggingConfiguration.CreateFromXmlString(xml);
                Assert.Contains(Path.GetDirectoryName(System.Diagnostics.Process.GetCurrentProcess()?.MainModule?.FileName), InternalLogger.LogFile);
            }
#endif

            using (new InternalLoggerScope(true))
            {
                var userName = Environment.GetEnvironmentVariable("USERNAME") ?? string.Empty;
                var xml      = "<nlog internalLogFile='%USERNAME%_test.txt'></nlog>";
                var config   = XmlLoggingConfiguration.CreateFromXmlString(xml);
                if (!string.IsNullOrEmpty(userName))
                {
                    Assert.Contains(userName, InternalLogger.LogFile);
                }
            }
        }
示例#27
0
        public void NDCTopTestTest()
        {
            LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
            <nlog>
                <targets><target name='debug' type='Debug' layout='${ndc:topframes=2} ${message}' /></targets>
                <rules>
                    <logger name='*' minlevel='Debug' writeTo='debug' />
                </rules>
            </nlog>");

            NestedDiagnosticsContext.Clear();
            LogManager.GetLogger("A").Debug("0");
            AssertDebugLastMessage("debug", " 0");
            using (NestedDiagnosticsContext.Push("ala"))
            {
                LogManager.GetLogger("A").Debug("a");
                AssertDebugLastMessage("debug", "ala a");
                using (NestedDiagnosticsContext.Push("ma"))
                {
                    LogManager.GetLogger("A").Debug("b");
                    AssertDebugLastMessage("debug", "ala ma b");
                    using (NestedDiagnosticsContext.Push("kota"))
                    {
                        LogManager.GetLogger("A").Debug("c");
                        AssertDebugLastMessage("debug", "ma kota c");
                        using (NestedDiagnosticsContext.Push("kopytko"))
                        {
                            LogManager.GetLogger("A").Debug("d");
                            AssertDebugLastMessage("debug", "kota kopytko d");
                        }
                        LogManager.GetLogger("A").Debug("c");
                        AssertDebugLastMessage("debug", "ma kota c");
                    }
                    LogManager.GetLogger("A").Debug("b");
                    AssertDebugLastMessage("debug", "ala ma b");
                }
                LogManager.GetLogger("A").Debug("a");
                AssertDebugLastMessage("debug", "ala a");
            }
            LogManager.GetLogger("A").Debug("0");
            AssertDebugLastMessage("debug", " 0");
        }
        public void DifferentConfigurations_UseDifferentDefaultCulture()
        {
            var currentCulture = CultureInfo.CurrentCulture;

            try
            {
                // set the current thread culture to be definitely different from the InvariantCulture
                Thread.CurrentThread.CurrentCulture = GetCultureInfo("de-DE");

                var configurationTemplate = @"<nlog useInvariantCulture='{0}'>
<targets>
    <target name='debug' type='Debug' layout='${{message}}' />
</targets>
<rules>
    <logger name='*' writeTo='debug'/>
</rules>
</nlog>";


                // configuration with current culture
                var configuration1 = XmlLoggingConfiguration.CreateFromXmlString(string.Format(configurationTemplate, false));
                Assert.Null(configuration1.DefaultCultureInfo);

                // configuration with invariant culture
                var configuration2 = XmlLoggingConfiguration.CreateFromXmlString(string.Format(configurationTemplate, true));
                Assert.Equal(CultureInfo.InvariantCulture, configuration2.DefaultCultureInfo);

                Assert.NotEqual(configuration1.DefaultCultureInfo, configuration2.DefaultCultureInfo);

                var          testNumber   = 3.14;
                var          testDate     = DateTime.Now;
                const string formatString = "{0},{1:d}";

                AssertMessageFormattedWithCulture(configuration1, CultureInfo.CurrentCulture, formatString, testNumber, testDate);
                AssertMessageFormattedWithCulture(configuration2, CultureInfo.InvariantCulture, formatString, testNumber, testDate);
            }
            finally
            {
                // restore current thread culture
                Thread.CurrentThread.CurrentCulture = currentCulture;
            }
        }
示例#29
0
        public void WebserviceTest_soap11_custom_soapaction()
        {
            var configuration = XmlLoggingConfiguration.CreateFromXmlString($@"
                <nlog throwExceptions='true'>
                    <targets>
                        <target type='WebService'
                                name='ws'
                                url='{getWsAddress(1)}{"api/logdoc/soap11"}'
                                protocol='Soap11'
                                namespace='http://tempuri.org/'
                                methodName ='Ping'
                                preAuthenticate='false'
                                encoding ='UTF-8'
                               >
                            <header name='SOAPAction' layout='http://tempuri.org/custom-namespace/Ping'/>
                            <parameter name='param1' ParameterType='System.String' layout='${{message}}'/> 
                            <parameter name='param2' ParameterType='System.String' layout='${{level}}'/>
                        </target>
                    </targets>
                    <rules>
                      <logger name='*' writeTo='ws' />
                    </rules>
                </nlog>");

            LogManager.Configuration = configuration;
            var logger = LogManager.GetCurrentClassLogger();

            var txt             = "test.message"; // Lets tease the Xml-Serializer, and see it can handle xml-tags
            var count           = 1;
            var expectedHeaders = new Dictionary <string, string>
            {
                { "SOAPAction", "http://tempuri.org/custom-namespace/Ping" }
            };
            var context = new LogDocController.TestContext(1, count, true, expectedHeaders, null, null, true, DateTime.UtcNow);

            StartOwinDocTest(context, () =>
            {
                logger.Info(txt);
            });

            Assert.Equal <int>(0, context.CountdownEvent.CurrentCount);
        }
        private void InternalLoggingConfigTest(LogLevel logLevel, bool logToConsole, bool logToConsoleError, LogLevel globalThreshold, bool throwExceptions, bool?throwConfigExceptions, string file, bool logToTrace, bool autoShutdown)
        {
            var logLevelString                  = logLevel.ToString();
            var internalLogToConsoleString      = logToConsole.ToString().ToLower();
            var internalLogToConsoleErrorString = logToConsoleError.ToString().ToLower();
            var globalThresholdString           = globalThreshold.ToString();
            var throwExceptionsString           = throwExceptions.ToString().ToLower();
            var throwConfigExceptionsString     = throwConfigExceptions == null ? "" : throwConfigExceptions.ToString().ToLower();
            var logToTraceString                = logToTrace.ToString().ToLower();
            var autoShutdownString              = autoShutdown.ToString().ToLower();

            using (new InternalLoggerScope(true))
            {
                XmlLoggingConfiguration.CreateFromXmlString($@"
<nlog internalLogFile='{file}' internalLogLevel='{logLevelString}' internalLogToConsole='{
                        internalLogToConsoleString
                    }' internalLogToConsoleError='{internalLogToConsoleErrorString}' globalThreshold='{
                        globalThresholdString
                    }' throwExceptions='{throwExceptionsString}' throwConfigExceptions='{
                        throwConfigExceptionsString
                    }' internalLogToTrace='{logToTraceString}' autoShutdown='{autoShutdownString}'>
</nlog>");

                Assert.Same(logLevel, InternalLogger.LogLevel);

                Assert.Equal(file, InternalLogger.LogFile);

                Assert.Equal(logToConsole, InternalLogger.LogToConsole);

                Assert.Equal(logToConsoleError, InternalLogger.LogToConsoleError);

                Assert.Same(globalThreshold, LogManager.GlobalThreshold);

                Assert.Equal(throwExceptions, LogManager.ThrowExceptions);

                Assert.Equal(throwConfigExceptions, LogManager.ThrowConfigExceptions);

                Assert.Equal(logToTrace, InternalLogger.LogToTrace);

                Assert.Equal(autoShutdown, LogManager.AutoShutdown);
            }
        }