public void ReplaceTestWithComplexRegEx() { MappedDiagnosticsContext.Clear(); var configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog throwExceptions='true'> <variable name=""searchExp"" value=""(?<!\\d[ -]*)(?\:(?<digits>\\d)[ -]*)\{8,16\}(?=(\\d[ -]*)\{3\}(\\d)(?![ -]\\d))"" /> <variable name=""message1"" value=""${replace:inner=${message}:searchFor=${searchExp}:replaceWith=X:replaceGroupName=digits:regex=true:ignorecase=true}"" /> <targets> <target name=""d1"" type=""Debug"" layout=""${message1}"" /> </targets> <rules> <logger name=""*"" minlevel=""Trace"" writeTo=""d1"" /> </rules> </nlog>"); var d1 = configuration.FindTargetByName("d1") as DebugTarget; Assert.NotNull(d1); var layout = d1.Layout as SimpleLayout; Assert.NotNull(layout); var testCases = new List <Tuple <string, string> > { Tuple.Create("1234", "1234"), Tuple.Create("1234-5678-1234-5678", "XXXX-XXXX-XXXX-5678"), }; foreach (var testCase in testCases) { var result = layout.Render(new LogEventInfo(LogLevel.Info, "Test", testCase.Item1)); Assert.Equal(testCase.Item2, result); } }
public void LayoutParserEscapeCodesForRegExTestV2() { MappedDiagnosticsContext.Clear(); var configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog throwExceptions='true'> <variable name=""searchExp"" value=""(?<!\\d[ -]*)(?\:(?<digits>\\d)[ -]*)\{8,16\}(?=(\\d[ -]*)\{3\}(\\d)(?![ -]\\d))"" /> <variable name=""message1"" value=""${replace:inner=${message}:searchFor=${searchExp}:replaceWith=\u003a\u003a:regex=true:ignorecase=true}"" /> <targets> <target name=""d1"" type=""Debug"" layout=""${message1}"" /> </targets> <rules> <logger name=""*"" minlevel=""Trace"" writeTo=""d1"" /> </rules> </nlog>"); var d1 = configuration.FindTargetByName("d1") as DebugTarget; Assert.NotNull(d1); var layout = d1.Layout as SimpleLayout; Assert.NotNull(layout); var c = layout.Renderers.Count; Assert.Equal(1, c); var l1 = layout.Renderers[0] as ReplaceLayoutRendererWrapper; Assert.NotNull(l1); Assert.True(l1.Regex); Assert.True(l1.IgnoreCase); Assert.Equal(@"::", l1.ReplaceWith); Assert.Equal(@"(?<!\d[ -]*)(?:(?<digits>\d)[ -]*){8,16}(?=(\d[ -]*){3}(\d)(?![ -]\d))", l1.SearchFor); }
public void XmlLayoutLog4j() { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog throwExceptions='true'> <targets> <target name='debug' type='debug'> <layout type='xmllayout' elementName='log4j:event' propertiesElementName='log4j:data' propertiesElementKeyAttribute='name' propertiesElementValueAttribute='value' includeAllProperties='true' includeMdc='true' includeMdlc='true' > <attribute name='logger' layout='${logger}' includeEmptyValue='true' /> <attribute name='level' layout='${uppercase:${level}}' includeEmptyValue='true' /> <element name='log4j:message' value='${message}' /> <element name='log4j:throwable' value='${exception:format=tostring}' /> <element name='log4j:locationInfo'> <attribute name='class' layout='${callsite:methodName=false}' includeEmptyValue='true' /> </element> </layout> </target> </targets> <rules> <logger name='*' minlevel='debug' appendto='debug' /> </rules> </nlog>"); MappedDiagnosticsContext.Clear(); MappedDiagnosticsContext.Set("foo1", "bar1"); MappedDiagnosticsContext.Set("foo2", "bar2"); MappedDiagnosticsLogicalContext.Clear(); MappedDiagnosticsLogicalContext.Set("foo3", "bar3"); var logger = LogManager.GetLogger("hello"); var logEventInfo = LogEventInfo.Create(LogLevel.Debug, "A", null, null, "some message"); logEventInfo.Properties["nlogPropertyKey"] = "<nlog\r\nPropertyValue>"; logger.Log(logEventInfo); var target = LogManager.Configuration.FindTargetByName <NLog.Targets.DebugTarget>("debug"); Assert.Equal(@"<log4j:event logger=""A"" level=""DEBUG""><log4j:message>some message</log4j:message><log4j:locationInfo class=""NLog.UnitTests.Layouts.XmlLayoutTests""/><log4j:data name=""foo1"" value=""bar1""/><log4j:data name=""foo2"" value=""bar2""/><log4j:data name=""foo3"" value=""bar3""/><log4j:data name=""nlogPropertyKey"" value=""<nlog PropertyValue>""/></log4j:event>", target.LastMessage); }
public void ReplaceTestWithSimpleRegExFromConfig() { MappedDiagnosticsContext.Clear(); var configuration = CreateConfigurationFromString(@" <nlog throwExceptions='true'> <targets> <target name='d1' type='Debug' layout='${replace:inner=${message}:searchFor=\\r\\n|\\s:replaceWith= :regex=true}' /> </targets> <rules> <logger name=""*"" minlevel=""Trace"" writeTo=""d1"" /> </rules> </nlog>"); var d1 = configuration.FindTargetByName("d1") as DebugTarget; Assert.NotNull(d1); var layout = d1.Layout as SimpleLayout; Assert.NotNull(layout); var result = layout.Render(new LogEventInfo(LogLevel.Info, "Test", "\r\nfoo\rbar\nbar\tbar bar \n bar")); Assert.Equal(" foo bar bar bar bar bar", result); }
public void MDCTest() { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${mdc:item=myitem} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); MappedDiagnosticsContext.Clear(); MappedDiagnosticsContext.Set("myitem", "myvalue"); LogManager.GetLogger("A").Debug("a"); AssertDebugLastMessage("debug", "myvalue a"); MappedDiagnosticsContext.Set("myitem", "value2"); LogManager.GetLogger("A").Debug("b"); AssertDebugLastMessage("debug", "value2 b"); MappedDiagnosticsContext.Remove("myitem"); LogManager.GetLogger("A").Debug("c"); AssertDebugLastMessage("debug", " c"); }
public void IncludeMdcJsonProperties() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog throwExceptions='true'> <targets> <target name='asyncDebug' type='AsyncWrapper' timeToSleepBetweenBatches='0'> <target name='debug' type='Debug' > <layout type=""JsonLayout"" IncludeMdc='true' ExcludeProperties='Excluded1,Excluded2'> </layout> </target> </target> </targets> <rules> <logger name='*' minlevel='Debug' writeTo='asyncDebug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); var logEventInfo = CreateLogEventWithExcluded(); MappedDiagnosticsContext.Clear(); foreach (var prop in logEventInfo.Properties) { if (prop.Key.ToString() != "Excluded1" && prop.Key.ToString() != "Excluded2") { MappedDiagnosticsContext.Set(prop.Key.ToString(), prop.Value); } } logEventInfo.Properties.Clear(); logger.Debug(logEventInfo); LogManager.Flush(); AssertDebugLastMessage("debug", ExpectedIncludeAllPropertiesWithExcludes); }
public void BasicAuthEmailTest() { try { var mmt = new MockMailTarget { From = "*****@*****.**", To = "*****@*****.**", SmtpServer = "server1", SmtpAuthentication = SmtpAuthenticationMode.Basic, SmtpUserName = "******", SmtpPassword = "******", }; mmt.Initialize(null); var exceptions = new List <Exception>(); MappedDiagnosticsContext.Set("username", "u1"); MappedDiagnosticsContext.Set("password", "p1"); mmt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "log message 1").WithContinuation(exceptions.Add)); Assert.Null(exceptions[0]); Assert.Single(mmt.CreatedMocks); var mock = mmt.CreatedMocks[0]; var credential = mock.Credentials as NetworkCredential; Assert.NotNull(credential); Assert.Equal("u1", credential.UserName); Assert.Equal("p1", credential.Password); Assert.Equal(string.Empty, credential.Domain); } finally { MappedDiagnosticsContext.Clear(); } }
public void Log4JXmlTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog throwExceptions='true'> <targets> <target name='debug' type='Debug' layout='${log4jxmlevent:includeCallSite=true:includeSourceInfo=true:includeMdc=true:includeMdlc=true:includeMdlc=true:IncludeAllProperties=true:ndcItemSeparator=\:\::includenlogdata=true}' /> </targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); MappedDiagnosticsContext.Clear(); NestedDiagnosticsContext.Clear(); MappedDiagnosticsContext.Set("foo1", "bar1"); MappedDiagnosticsContext.Set("foo2", "bar2"); MappedDiagnosticsLogicalContext.Clear(); MappedDiagnosticsLogicalContext.Set("foo3", "bar3"); NestedDiagnosticsContext.Push("baz1"); NestedDiagnosticsContext.Push("baz2"); NestedDiagnosticsContext.Push("baz3"); ILogger logger = LogManager.GetLogger("A"); var logEventInfo = LogEventInfo.Create(LogLevel.Debug, "A", new Exception("Hello Exception", new Exception("Goodbye Exception")), null, "some message"); logEventInfo.Properties["nlogPropertyKey"] = "nlogPropertyValue"; logger.Log(logEventInfo); string result = GetDebugLastMessage("debug"); string wrappedResult = "<log4j:dummyRoot xmlns:log4j='http://log4j' xmlns:nlog='http://nlog'>" + result + "</log4j:dummyRoot>"; Assert.NotEqual("", result); // make sure the XML can be read back and verify some fields StringReader stringReader = new StringReader(wrappedResult); using (XmlReader reader = XmlReader.Create(stringReader)) { while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element && reader.Prefix == "log4j") { switch (reader.LocalName) { case "dummyRoot": break; case "event": Assert.Equal("DEBUG", reader.GetAttribute("level")); Assert.Equal("A", reader.GetAttribute("logger")); var epochStart = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); long timestamp = Convert.ToInt64(reader.GetAttribute("timestamp")); var time = epochStart.AddMilliseconds(timestamp); var now = DateTime.UtcNow; Assert.True(now.Ticks - time.Ticks < TimeSpan.FromSeconds(3).Ticks); Assert.Equal(Thread.CurrentThread.ManagedThreadId.ToString(), reader.GetAttribute("thread")); break; case "message": reader.Read(); Assert.Equal("some message", reader.Value); break; case "NDC": reader.Read(); Assert.Equal("baz3::baz2::baz1", reader.Value); break; case "locationInfo": Assert.Equal(MethodBase.GetCurrentMethod().DeclaringType.FullName, reader.GetAttribute("class")); Assert.Equal(MethodBase.GetCurrentMethod().ToString(), reader.GetAttribute("method")); break; case "properties": break; case "throwable": reader.Read(); Assert.Contains("Hello Exception", reader.Value); Assert.Contains("Goodbye Exception", reader.Value); break; case "data": string name = reader.GetAttribute("name"); string value = reader.GetAttribute("value"); switch (name) { case "log4japp": Assert.Equal(AppDomain.CurrentDomain.FriendlyName + "(" + Process.GetCurrentProcess().Id + ")", value); break; case "log4jmachinename": Assert.Equal(Environment.MachineName, value); break; case "foo1": Assert.Equal("bar1", value); break; case "foo2": Assert.Equal("bar2", value); break; case "foo3": Assert.Equal("bar3", value); break; case "nlogPropertyKey": Assert.Equal("nlogPropertyValue", value); break; default: Assert.True(false, "Unknown <log4j:data>: " + name); break; } break; default: throw new NotSupportedException("Unknown element: " + reader.LocalName); } continue; } if (reader.NodeType == XmlNodeType.Element && reader.Prefix == "nlog") { switch (reader.LocalName) { case "eventSequenceNumber": break; case "locationInfo": Assert.Equal(this.GetType().Assembly.FullName, reader.GetAttribute("assembly")); break; case "properties": break; case "data": var name = reader.GetAttribute("name"); var value = reader.GetAttribute("value"); Assert.Equal("nlogPropertyKey", name); Assert.Equal("nlogPropertyValue", value); break; default: throw new NotSupportedException("Unknown element: " + reader.LocalName); } } } } }
public void MDCTest1() { List <Exception> exceptions = new List <Exception>(); ManualResetEvent mre = new ManualResetEvent(false); int counter = 100; int remaining = counter; for (int i = 0; i < counter; ++i) { ThreadPool.QueueUserWorkItem( s => { try { MappedDiagnosticsContext.Clear(); Assert.False(MappedDiagnosticsContext.Contains("foo")); Assert.Equal(string.Empty, MappedDiagnosticsContext.Get("foo")); Assert.False(MappedDiagnosticsContext.Contains("foo2")); Assert.Equal(string.Empty, MappedDiagnosticsContext.Get("foo2")); Assert.Equal(0, MappedDiagnosticsContext.GetNames().Count); MappedDiagnosticsContext.Set("foo", "bar"); MappedDiagnosticsContext.Set("foo2", "bar2"); Assert.True(MappedDiagnosticsContext.Contains("foo")); Assert.Equal("bar", MappedDiagnosticsContext.Get("foo")); Assert.Equal(2, MappedDiagnosticsContext.GetNames().Count); MappedDiagnosticsContext.Remove("foo"); Assert.False(MappedDiagnosticsContext.Contains("foo")); Assert.Equal(string.Empty, MappedDiagnosticsContext.Get("foo")); Assert.True(MappedDiagnosticsContext.Contains("foo2")); Assert.Equal("bar2", MappedDiagnosticsContext.Get("foo2")); Assert.Equal(1, MappedDiagnosticsContext.GetNames().Count); Assert.True(MappedDiagnosticsContext.GetNames().Contains("foo2")); Assert.Null(MappedDiagnosticsContext.GetObject("foo3")); MappedDiagnosticsContext.Set("foo3", new { One = 1 }); } catch (Exception exception) { lock (exceptions) { exceptions.Add(exception); } } finally { if (Interlocked.Decrement(ref remaining) == 0) { mre.Set(); } } }); } mre.WaitOne(); StringBuilder exceptionsMessage = new StringBuilder(); foreach (var ex in exceptions) { if (exceptionsMessage.Length > 0) { exceptionsMessage.Append("\r\n"); } exceptionsMessage.Append(ex.ToString()); } Assert.True(exceptions.Count == 0, exceptionsMessage.ToString()); }