예제 #1
0
 public IDisposable BeginScope <TState>(TState state)
 {
     if (state == null)
     {
         throw new ArgumentNullException(nameof(state));
     }
     //TODO not working with async
     return(NestedDiagnosticsContext.Push(state));
 }
예제 #2
0
        public void TargetWithContextNdcSerializeTest()
        {
            NestedDiagnosticsContext.Clear();
            NestedDiagnosticsContext.Push(new { a = "b" });

            CustomTargetWithContext target = new CustomTargetWithContext()
            {
                IncludeNdc = true, SkipAssert = true
            };

            WriteAndAssertSingleKey(target);
        }
예제 #3
0
        private void ProcessQueue()
        {
            try
            {
                do
                {
                    using (NestedDiagnosticsContext.Push(Guid.NewGuid().ToString()))
                    {
                        try
                        {
                            JobQueueItem job = null;

                            lock (Queue)
                            {
                                if (Queue.Count != 0)
                                {
                                    job = Queue.OrderBy(c => c.Source).First();
                                    logger.Trace("Popping {0} from the queue.", job);
                                    Queue.Remove(job);
                                }
                            }

                            if (job != null)
                            {
                                Execute(job);
                            }
                        }
                        catch (ThreadAbortException)
                        {
                            throw;
                        }
                        catch (Exception e)
                        {
                            logger.FatalException("An error has occurred while executing job.", e);
                        }
                    }
                } while (Queue.Count != 0);
            }
            catch (ThreadAbortException e)
            {
                logger.Warn(e.Message);
            }
            catch (Exception e)
            {
                logger.ErrorException("Error has occurred in queue processor thread", e);
            }
            finally
            {
                StopWatch.Stop();
                logger.Trace("Finished processing jobs in the queue.");
            }
        }
예제 #4
0
        public void NDCTop1TestTest()
        {
            LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
            <nlog>
                <targets><target name='debug' type='Debug' layout='${ndc:topframes=1} ${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", "ma b");
                    using (NestedDiagnosticsContext.Push("kota"))
                    {
                        LogManager.GetLogger("A").Debug("c");
                        AssertDebugLastMessage("debug", "kota c");
                        NestedDiagnosticsContext.Push("kopytko");
                        LogManager.GetLogger("A").Debug("d");
                        AssertDebugLastMessage("debug", "kopytko d");
                        Assert.Equal("kopytko", NestedDiagnosticsContext.Pop()); // manual pop
                        LogManager.GetLogger("A").Debug("c");
                        AssertDebugLastMessage("debug", "kota c");
                    }
                    LogManager.GetLogger("A").Debug("b");
                    AssertDebugLastMessage("debug", "ma b");
                }
                LogManager.GetLogger("A").Debug("a");
                AssertDebugLastMessage("debug", "ala a");
            }
            LogManager.GetLogger("A").Debug("0");
            AssertDebugLastMessage("debug", " 0");
            Assert.Equal(string.Empty, NestedDiagnosticsContext.Pop());
            Assert.Equal(string.Empty, NestedDiagnosticsContext.TopMessage);
            NestedDiagnosticsContext.Push("zzz");
            Assert.Equal("zzz", NestedDiagnosticsContext.TopMessage);
            NestedDiagnosticsContext.Clear();
            Assert.Equal(string.Empty, NestedDiagnosticsContext.Pop());
            Assert.Equal(string.Empty, NestedDiagnosticsContext.TopMessage);
        }
예제 #5
0
        public void NDCTest()
        {
            LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
            <nlog>
                <targets><target name='debug' type='Debug' layout='${ndc} ${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", "ala ma kota c");
                        using (NestedDiagnosticsContext.Push("kopytko"))
                        {
                            LogManager.GetLogger("A").Debug("d");
                            AssertDebugLastMessage("debug", "ala ma kota kopytko d");
                        }
                        LogManager.GetLogger("A").Debug("c");
                        AssertDebugLastMessage("debug", "ala 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");
        }
예제 #6
0
        /// <summary>
        /// Renders the specified Nested Diagnostics Context item and appends it to the specified <see cref="StringBuilder" />.
        /// </summary>
        /// <param name="builder">The <see cref="StringBuilder"/> to append the rendered data to.</param>
        /// <param name="logEvent">Logging event.</param>
        protected override void Append(StringBuilder builder, LogEventInfo logEvent)
        {
            if (TopFrames == 1)
            {
                // Allows fast rendering of topframes=1
                var topFrame = NestedDiagnosticsContext.PeekObject();
                if (topFrame != null)
                {
                    AppendAsString(topFrame, GetFormatProvider(logEvent), builder);
                }
                return;
            }

            var messages = NestedDiagnosticsContext.GetAllObjects();

            if (messages.Length == 0)
            {
                return;
            }

            int startPos = 0;
            int endPos   = messages.Length;

            if (TopFrames != -1)
            {
                endPos = Math.Min(TopFrames, messages.Length);
            }
            else if (BottomFrames != -1)
            {
                startPos = messages.Length - Math.Min(BottomFrames, messages.Length);
            }

            var    formatProvider   = GetFormatProvider(logEvent);
            string currentSeparator = string.Empty;

            for (int i = endPos - 1; i >= startPos; --i)
            {
                builder.Append(currentSeparator);
                AppendAsString(messages[i], formatProvider, builder);
                currentSeparator = Separator;
            }
        }
예제 #7
0
        public void If_Ndc_And_Ndlc_is_present_they_are_combined_with_a_NdcSeparator()
        {
            // Arrange
            var ndcSeparator  = "::";
            var ndlcSeparator = " ";

            ConfigureLogManager(ndcSeparator, ndlcSeparator);

            // Act
            NestedDiagnosticsContext.Clear();
            NestedDiagnosticsContext.Push("foo");

            NestedDiagnosticsLogicalContext.Clear();
            NestedDiagnosticsLogicalContext.Push("bar");

            var logEvent = Log("A", LogLevel.Debug, null, null, "some message");

            // Assert
            var expected = GetExpectedNdcValue(logEvent, ndcSeparator, ndlcSeparator);
            var actual   = GetXmlDocument().GetElementsByTagName("log4j:NDC")[0].InnerText;

            Assert.Equal(expected, actual);
        }
예제 #8
0
        /// <summary>
        ///     Renders the specified Nested Diagnostics Context item and appends it to the specified <see cref="StringBuilder" />.
        /// </summary>
        /// <param name="builder">
        ///     The <see cref="StringBuilder" /> to append the rendered data to.
        /// </param>
        /// <param name="logEvent">Logging event.</param>
        protected override void Append(StringBuilder builder, LogEventInfo logEvent)
        {
            var messages = NestedDiagnosticsContext.GetAllMessages();
            var startPos = 0;
            var endPos   = messages.Length;

            if (TopFrames != -1)
            {
                endPos = Math.Min(TopFrames, messages.Length);
            }
            else if (BottomFrames != -1)
            {
                startPos = messages.Length - Math.Min(BottomFrames, messages.Length);
            }

            var totalLength     = 0;
            var separatorLength = 0;

            for (var i = endPos - 1; i >= startPos; --i)
            {
                totalLength    += separatorLength + messages[i].Length;
                separatorLength = Separator.Length;
            }

            var separator = string.Empty;

            var sb = new StringBuilder();

            for (var i = endPos - 1; i >= startPos; --i)
            {
                sb.Append(separator);
                sb.Append(messages[i]);
                separator = Separator;
            }

            builder.Append(sb);
        }
예제 #9
0
        /// <summary>
        /// Renders the specified Nested Diagnostics Context item and appends it to the specified <see cref="StringBuilder" />.
        /// </summary>
        /// <param name="builder">The <see cref="StringBuilder"/> to append the rendered data to.</param>
        /// <param name="logEvent">Logging event.</param>
        protected override void Append(StringBuilder builder, LogEventInfo logEvent)
        {
            string[] messages = NestedDiagnosticsContext.GetAllMessages();
            int      startPos = 0;
            int      endPos   = messages.Length;

            if (this.TopFrames != -1)
            {
                endPos = Math.Min(this.TopFrames, messages.Length);
            }
            else if (this.BottomFrames != -1)
            {
                startPos = messages.Length - Math.Min(this.BottomFrames, messages.Length);
            }

            int totalLength     = 0;
            int separatorLength = 0;

            for (int i = endPos - 1; i >= startPos; --i)
            {
                totalLength    += separatorLength + messages[i].Length;
                separatorLength = this.Separator.Length;
            }

            string separator = string.Empty;

            StringBuilder sb = new StringBuilder();

            for (int i = endPos - 1; i >= startPos; --i)
            {
                sb.Append(separator);
                sb.Append(messages[i]);
                separator = this.Separator;
            }

            builder.Append(sb.ToString());
        }
예제 #10
0
        /// <summary>
        /// Renders the specified Nested Diagnostics Context item and appends it to the specified <see cref="StringBuilder" />.
        /// </summary>
        /// <param name="builder">The <see cref="StringBuilder"/> to append the rendered data to.</param>
        /// <param name="logEvent">Logging event.</param>
        protected override void Append(StringBuilder builder, LogEventInfo logEvent)
        {
            string[] messages = NestedDiagnosticsContext.GetAllMessages(logEvent.FormatProvider);
            int      startPos = 0;
            int      endPos   = messages.Length;

            if (this.TopFrames != -1)
            {
                endPos = Math.Min(this.TopFrames, messages.Length);
            }
            else if (this.BottomFrames != -1)
            {
                startPos = messages.Length - Math.Min(this.BottomFrames, messages.Length);
            }

            string separator = string.Empty;

            for (int i = endPos - 1; i >= startPos; --i)
            {
                builder.Append(separator);
                builder.Append(messages[i]);
                separator = this.Separator;
            }
        }
        public void NDCTest2_object()
        {
            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
                    {
                        NestedDiagnosticsContext.Clear();
                        Assert.Null(NestedDiagnosticsContext.TopObject);
                        Assert.Null(NestedDiagnosticsContext.PopObject());
                        AssertContents(NestedDiagnosticsContext.GetAllMessages());
                        using (NestedDiagnosticsContext.Push("foo"))
                        {
                            Assert.Equal("foo", NestedDiagnosticsContext.TopObject);
                            AssertContents(NestedDiagnosticsContext.GetAllObjects(), "foo");
                            using (NestedDiagnosticsContext.Push("bar"))
                            {
                                AssertContents(NestedDiagnosticsContext.GetAllObjects(), "bar", "foo");
                                Assert.Equal("bar", NestedDiagnosticsContext.TopObject);
                                NestedDiagnosticsContext.Push("baz");
                                AssertContents(NestedDiagnosticsContext.GetAllObjects(), "baz", "bar", "foo");
                                Assert.Equal("baz", NestedDiagnosticsContext.TopObject);
                                Assert.Equal("baz", NestedDiagnosticsContext.PopObject());

                                AssertContents(NestedDiagnosticsContext.GetAllObjects(), "bar", "foo");
                                Assert.Equal("bar", NestedDiagnosticsContext.TopObject);
                            }

                            AssertContents(NestedDiagnosticsContext.GetAllObjects(), "foo");
                            Assert.Equal("foo", NestedDiagnosticsContext.TopObject);
                        }

                        AssertContents(NestedDiagnosticsContext.GetAllMessages());
                        Assert.Null(NestedDiagnosticsContext.PopObject());
                    }
                    catch (Exception ex)
                    {
                        lock (exceptions)
                        {
                            exceptions.Add(ex);
                        }
                    }
                    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());
        }
 public void TestLogMessage()
 {
     NestedDiagnosticsContext.Push("TestNdc");
     Log.Error("This is a test message");
 }
예제 #13
0
        /// <summary>
        /// Renders the XML logging event and appends it to the specified <see cref="StringBuilder" />.
        /// </summary>
        /// <param name="builder">The <see cref="StringBuilder"/> to append the rendered data to.</param>
        /// <param name="logEvent">Logging event.</param>
        protected override void Append(StringBuilder builder, LogEventInfo logEvent)
        {
            var settings = new XmlWriterSettings
            {
                Indent           = this.IndentXml,
                ConformanceLevel = ConformanceLevel.Fragment,
                IndentChars      = "  ",
            };

            var sb = new StringBuilder();

            using (XmlWriter xtw = XmlWriter.Create(sb, settings))
            {
                xtw.WriteStartElement("log4j", "event", dummyNamespace);
                xtw.WriteAttributeSafeString("xmlns", "nlog", null, dummyNLogNamespace);
                xtw.WriteAttributeSafeString("logger", logEvent.LoggerName);
                xtw.WriteAttributeSafeString("level", logEvent.Level.Name.ToUpper(CultureInfo.InvariantCulture));
                xtw.WriteAttributeSafeString("timestamp", Convert.ToString((long)(logEvent.TimeStamp.ToUniversalTime() - log4jDateBase).TotalMilliseconds, CultureInfo.InvariantCulture));
                xtw.WriteAttributeSafeString("thread", System.Threading.Thread.CurrentThread.ManagedThreadId.ToString(CultureInfo.InvariantCulture));

                xtw.WriteElementSafeString("log4j", "message", dummyNamespace, logEvent.FormattedMessage);
                if (logEvent.Exception != null)
                {
                    xtw.WriteElementSafeString("log4j", "throwable", dummyNamespace, logEvent.Exception.ToString());
                }

                if (this.IncludeNdc)
                {
                    xtw.WriteElementSafeString("log4j", "NDC", dummyNamespace, string.Join(this.NdcItemSeparator, NestedDiagnosticsContext.GetAllMessages()));
                }

                if (logEvent.Exception != null)
                {
                    xtw.WriteStartElement("log4j", "throwable", dummyNamespace);
                    xtw.WriteSafeCData(logEvent.Exception.ToString());
                    xtw.WriteEndElement();
                }

                if (this.IncludeCallSite || this.IncludeSourceInfo)
                {
                    System.Diagnostics.StackFrame frame = logEvent.UserStackFrame;
                    if (frame != null)
                    {
                        MethodBase methodBase = frame.GetMethod();
                        Type       type       = methodBase.DeclaringType;

                        xtw.WriteStartElement("log4j", "locationInfo", dummyNamespace);
                        if (type != null)
                        {
                            xtw.WriteAttributeSafeString("class", type.FullName);
                        }

                        xtw.WriteAttributeSafeString("method", methodBase.ToString());
#if !SILVERLIGHT
                        if (this.IncludeSourceInfo)
                        {
                            xtw.WriteAttributeSafeString("file", frame.GetFileName());
                            xtw.WriteAttributeSafeString("line", frame.GetFileLineNumber().ToString(CultureInfo.InvariantCulture));
                        }
#endif
                        xtw.WriteEndElement();

                        if (this.IncludeNLogData)
                        {
                            xtw.WriteElementSafeString("nlog", "eventSequenceNumber", dummyNLogNamespace, logEvent.SequenceID.ToString(CultureInfo.InvariantCulture));
                            xtw.WriteStartElement("nlog", "locationInfo", dummyNLogNamespace);
                            if (type != null)
                            {
                                xtw.WriteAttributeSafeString("assembly", type.Assembly.FullName);
                            }

                            xtw.WriteEndElement();

                            xtw.WriteStartElement("nlog", "properties", dummyNLogNamespace);
                            foreach (var contextProperty in logEvent.Properties)
                            {
                                xtw.WriteStartElement("nlog", "data", dummyNLogNamespace);
                                xtw.WriteAttributeSafeString("name", Convert.ToString(contextProperty.Key, CultureInfo.InvariantCulture));
                                xtw.WriteAttributeSafeString("value", Convert.ToString(contextProperty.Value, CultureInfo.InvariantCulture));
                                xtw.WriteEndElement();
                            }
                            xtw.WriteEndElement();
                        }
                    }
                }

                xtw.WriteStartElement("log4j", "properties", dummyNamespace);
                if (this.IncludeMdc)
                {
                    foreach (KeyValuePair <string, object> entry in MappedDiagnosticsContext.ThreadDictionary)
                    {
                        xtw.WriteStartElement("log4j", "data", dummyNamespace);
                        xtw.WriteAttributeSafeString("name", entry.Key);
                        xtw.WriteAttributeSafeString("value", String.Format(logEvent.FormatProvider, "{0}", entry.Value));
                        xtw.WriteEndElement();
                    }
                }

                foreach (NLogViewerParameterInfo parameter in this.Parameters)
                {
                    xtw.WriteStartElement("log4j", "data", dummyNamespace);
                    xtw.WriteAttributeSafeString("name", parameter.Name);
                    xtw.WriteAttributeSafeString("value", parameter.Layout.Render(logEvent));
                    xtw.WriteEndElement();
                }

                xtw.WriteStartElement("log4j", "data", dummyNamespace);
                xtw.WriteAttributeSafeString("name", "log4japp");
                xtw.WriteAttributeSafeString("value", this.AppInfo);
                xtw.WriteEndElement();

                xtw.WriteStartElement("log4j", "data", dummyNamespace);
                xtw.WriteAttributeSafeString("name", "log4jmachinename");

#if SILVERLIGHT
                xtw.WriteAttributeSafeString("value", "silverlight");
#else
                xtw.WriteAttributeSafeString("value", Environment.MachineName);
#endif
                xtw.WriteEndElement();
                xtw.WriteEndElement();

                xtw.WriteEndElement();
                xtw.Flush();

                // get rid of 'nlog' and 'log4j' namespace declarations
                sb.Replace(" xmlns:log4j=\"" + dummyNamespace + "\"", string.Empty);
                sb.Replace(" xmlns:nlog=\"" + dummyNLogNamespace + "\"", string.Empty);

                builder.Append(sb.ToString());
            }
        }
예제 #14
0
        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);
                        }
                    }
                }
            }
        }
예제 #15
0
        /// <summary>
        /// Renders the XML logging event and appends it to the specified <see cref="StringBuilder" />.
        /// </summary>
        /// <param name="builder">The <see cref="StringBuilder"/> to append the rendered data to.</param>
        /// <param name="logEvent">Logging event.</param>
        protected override void Append(StringBuilder builder, LogEventInfo logEvent)
        {
            StringBuilder sb = new StringBuilder();

            using (XmlWriter xtw = XmlWriter.Create(sb, this.xmlWriterSettings))
            {
                xtw.WriteStartElement("log4j", "event", dummyNamespace);
                xtw.WriteAttributeSafeString("xmlns", "nlog", null, dummyNLogNamespace);
                xtw.WriteAttributeSafeString("logger", logEvent.LoggerName);
                xtw.WriteAttributeSafeString("level", logEvent.Level.Name.ToUpper(CultureInfo.InvariantCulture));
                xtw.WriteAttributeSafeString("timestamp", Convert.ToString((long)(logEvent.TimeStamp.ToUniversalTime() - log4jDateBase).TotalMilliseconds, CultureInfo.InvariantCulture));
                xtw.WriteAttributeSafeString("thread", System.Threading.Thread.CurrentThread.ManagedThreadId.ToString(CultureInfo.InvariantCulture));

                xtw.WriteElementSafeString("log4j", "message", dummyNamespace, logEvent.FormattedMessage);
                if (logEvent.Exception != null)
                {
                    xtw.WriteElementSafeString("log4j", "throwable", dummyNamespace, logEvent.Exception.ToString());
                }

                if (this.IncludeNdc)
                {
                    xtw.WriteElementSafeString("log4j", "NDC", dummyNamespace, string.Join(this.NdcItemSeparator, NestedDiagnosticsContext.GetAllMessages()));
                }

                if (logEvent.Exception != null)
                {
                    xtw.WriteStartElement("log4j", "throwable", dummyNamespace);
                    xtw.WriteSafeCData(logEvent.Exception.ToString());
                    xtw.WriteEndElement();
                }

                if (this.IncludeCallSite || this.IncludeSourceInfo)
                {
                    System.Diagnostics.StackFrame frame = logEvent.UserStackFrame;
                    if (frame != null)
                    {
                        MethodBase methodBase = frame.GetMethod();
                        Type       type       = methodBase.DeclaringType;

                        xtw.WriteStartElement("log4j", "locationInfo", dummyNamespace);
                        if (type != null)
                        {
                            xtw.WriteAttributeSafeString("class", type.FullName);
                        }

                        xtw.WriteAttributeSafeString("method", methodBase.ToString());
#if !SILVERLIGHT
                        if (this.IncludeSourceInfo)
                        {
                            xtw.WriteAttributeSafeString("file", frame.GetFileName());
                            xtw.WriteAttributeSafeString("line", frame.GetFileLineNumber().ToString(CultureInfo.InvariantCulture));
                        }
#endif
                        xtw.WriteEndElement();

                        if (this.IncludeNLogData)
                        {
                            xtw.WriteElementSafeString("nlog", "eventSequenceNumber", dummyNLogNamespace, logEvent.SequenceID.ToString(CultureInfo.InvariantCulture));
                            xtw.WriteStartElement("nlog", "locationInfo", dummyNLogNamespace);
                            if (type != null)
                            {
                                xtw.WriteAttributeSafeString("assembly", type.Assembly.FullName);
                            }
                            xtw.WriteEndElement();

                            xtw.WriteStartElement("nlog", "properties", dummyNLogNamespace);
                            AppendProperties("nlog", xtw, logEvent);
                            xtw.WriteEndElement();
                        }
                    }
                }

                xtw.WriteStartElement("log4j", "properties", dummyNamespace);
                if (this.IncludeMdc)
                {
                    foreach (string key in MappedDiagnosticsContext.GetNames())
                    {
                        string propertyValue = XmlHelper.XmlConvertToString(MappedDiagnosticsContext.GetObject(key));
                        if (propertyValue == null)
                        {
                            continue;
                        }

                        xtw.WriteStartElement("log4j", "data", dummyNamespace);
                        xtw.WriteAttributeSafeString("name", key);
                        xtw.WriteAttributeSafeString("value", propertyValue);
                        xtw.WriteEndElement();
                    }
                }

#if !SILVERLIGHT
                if (this.IncludeMdlc)
                {
                    foreach (string key in MappedDiagnosticsLogicalContext.GetNames())
                    {
                        string propertyValue = XmlHelper.XmlConvertToString(MappedDiagnosticsLogicalContext.GetObject(key));
                        if (propertyValue == null)
                        {
                            continue;
                        }

                        xtw.WriteStartElement("log4j", "data", dummyNamespace);
                        xtw.WriteAttributeSafeString("name", key);
                        xtw.WriteAttributeSafeString("value", propertyValue);
                        xtw.WriteEndElement();
                    }
                }
#endif

                if (this.IncludeAllProperties)
                {
                    AppendProperties("log4j", xtw, logEvent);
                }

                if (this.Parameters.Count > 0)
                {
                    foreach (NLogViewerParameterInfo parameter in this.Parameters)
                    {
                        xtw.WriteStartElement("log4j", "data", dummyNamespace);
                        xtw.WriteAttributeSafeString("name", parameter.Name);
                        xtw.WriteAttributeSafeString("value", parameter.Layout.Render(logEvent));
                        xtw.WriteEndElement();
                    }
                }

                xtw.WriteStartElement("log4j", "data", dummyNamespace);
                xtw.WriteAttributeSafeString("name", "log4japp");
                xtw.WriteAttributeSafeString("value", this.AppInfo);
                xtw.WriteEndElement();

                xtw.WriteStartElement("log4j", "data", dummyNamespace);
                xtw.WriteAttributeSafeString("name", "log4jmachinename");
                xtw.WriteAttributeSafeString("value", this.machineName);
                xtw.WriteEndElement();

                xtw.WriteEndElement();

                xtw.WriteEndElement();
                xtw.Flush();

                // get rid of 'nlog' and 'log4j' namespace declarations
                sb.Replace(dummyNamespaceRemover, string.Empty);
                sb.Replace(dummyNLogNamespaceRemover, string.Empty);
                builder.Append(sb.ToString());  // StringBuilder.Replace is not good when reusing the StringBuilder
            }
        }
예제 #16
0
        /// <summary>
        /// Renders the XML logging event and appends it to the specified <see cref="StringBuilder" />.
        /// </summary>
        /// <param name="builder">The <see cref="StringBuilder"/> to append the rendered data to.</param>
        /// <param name="logEvent">Logging event.</param>
        protected override void Append(StringBuilder builder, LogEventInfo logEvent)
        {
            StringBuilder sb = new StringBuilder();

            using (XmlWriter xtw = XmlWriter.Create(sb, _xmlWriterSettings))
            {
                xtw.WriteStartElement("log4j", "event", dummyNamespace);
                xtw.WriteAttributeSafeString("xmlns", "nlog", null, dummyNLogNamespace);
                xtw.WriteAttributeSafeString("logger", LoggerName != null ? LoggerName.Render(logEvent) : logEvent.LoggerName);
                xtw.WriteAttributeSafeString("level", logEvent.Level.Name.ToUpperInvariant());
                xtw.WriteAttributeSafeString("timestamp", Convert.ToString((long)(logEvent.TimeStamp.ToUniversalTime() - log4jDateBase).TotalMilliseconds, CultureInfo.InvariantCulture));
                xtw.WriteAttributeSafeString("thread", System.Threading.Thread.CurrentThread.ManagedThreadId.ToString(CultureInfo.InvariantCulture));

                xtw.WriteElementSafeString("log4j", "message", dummyNamespace, logEvent.FormattedMessage);
                if (logEvent.Exception != null)
                {
                    // TODO Why twice the exception details?
                    xtw.WriteElementSafeString("log4j", "throwable", dummyNamespace, logEvent.Exception.ToString());
                }

                string ndcContent = null;
                if (IncludeNdc)
                {
                    ndcContent = string.Join(NdcItemSeparator, NestedDiagnosticsContext.GetAllMessages());
                }
#if !SILVERLIGHT
                if (IncludeNdlc)
                {
                    if (ndcContent != null)
                    {
                        //extra separator
                        ndcContent += NdcItemSeparator;
                    }
                    ndcContent += string.Join(NdlcItemSeparator, NestedDiagnosticsLogicalContext.GetAllMessages());
                }
#endif

                if (ndcContent != null)
                {
                    //NDLC and NDC should be in the same element
                    xtw.WriteElementSafeString("log4j", "NDC", dummyNamespace, ndcContent);
                }

                if (logEvent.Exception != null)
                {
                    // TODO Why twice the exception details?
                    xtw.WriteStartElement("log4j", "throwable", dummyNamespace);
                    xtw.WriteSafeCData(logEvent.Exception.ToString());
                    xtw.WriteEndElement();
                }

                if (IncludeCallSite || IncludeSourceInfo)
                {
                    if (logEvent.CallSiteInformation != null)
                    {
                        MethodBase methodBase       = logEvent.CallSiteInformation.GetCallerStackFrameMethod(0);
                        string     callerClassName  = logEvent.CallSiteInformation.GetCallerClassName(methodBase, true, true, true);
                        string     callerMemberName = logEvent.CallSiteInformation.GetCallerMemberName(methodBase, true, true, true);

                        xtw.WriteStartElement("log4j", "locationInfo", dummyNamespace);
                        if (!string.IsNullOrEmpty(callerClassName))
                        {
                            xtw.WriteAttributeSafeString("class", callerClassName);
                        }

                        xtw.WriteAttributeSafeString("method", callerMemberName);
#if !SILVERLIGHT
                        if (IncludeSourceInfo)
                        {
                            xtw.WriteAttributeSafeString("file", logEvent.CallSiteInformation.GetCallerFilePath(0));
                            xtw.WriteAttributeSafeString("line", logEvent.CallSiteInformation.GetCallerLineNumber(0).ToString(CultureInfo.InvariantCulture));
                        }
#endif
                        xtw.WriteEndElement();

                        if (IncludeNLogData)
                        {
                            xtw.WriteElementSafeString("nlog", "eventSequenceNumber", dummyNLogNamespace, logEvent.SequenceID.ToString(CultureInfo.InvariantCulture));
                            xtw.WriteStartElement("nlog", "locationInfo", dummyNLogNamespace);
                            var type = methodBase?.DeclaringType;
                            if (type != null)
                            {
                                xtw.WriteAttributeSafeString("assembly", type.GetAssembly().FullName);
                            }
                            xtw.WriteEndElement();

                            xtw.WriteStartElement("nlog", "properties", dummyNLogNamespace);
                            AppendProperties("nlog", xtw, logEvent);
                            xtw.WriteEndElement();
                        }
                    }
                }

                xtw.WriteStartElement("log4j", "properties", dummyNamespace);
                if (IncludeMdc)
                {
                    foreach (string key in MappedDiagnosticsContext.GetNames())
                    {
                        string propertyValue = XmlHelper.XmlConvertToString(MappedDiagnosticsContext.GetObject(key));
                        if (propertyValue == null)
                        {
                            continue;
                        }

                        xtw.WriteStartElement("log4j", "data", dummyNamespace);
                        xtw.WriteAttributeSafeString("name", key);
                        xtw.WriteAttributeSafeString("value", propertyValue);
                        xtw.WriteEndElement();
                    }
                }

#if !SILVERLIGHT
                if (IncludeMdlc)
                {
                    foreach (string key in MappedDiagnosticsLogicalContext.GetNames())
                    {
                        string propertyValue = XmlHelper.XmlConvertToString(MappedDiagnosticsLogicalContext.GetObject(key));
                        if (propertyValue == null)
                        {
                            continue;
                        }

                        xtw.WriteStartElement("log4j", "data", dummyNamespace);
                        xtw.WriteAttributeSafeString("name", key);
                        xtw.WriteAttributeSafeString("value", propertyValue);
                        xtw.WriteEndElement();
                    }
                }
#endif

                if (IncludeAllProperties)
                {
                    AppendProperties("log4j", xtw, logEvent);
                }

                if (Parameters.Count > 0)
                {
                    foreach (NLogViewerParameterInfo parameter in Parameters)
                    {
                        xtw.WriteStartElement("log4j", "data", dummyNamespace);
                        xtw.WriteAttributeSafeString("name", parameter.Name);
                        xtw.WriteAttributeSafeString("value", parameter.Layout.Render(logEvent));
                        xtw.WriteEndElement();
                    }
                }

                xtw.WriteStartElement("log4j", "data", dummyNamespace);
                xtw.WriteAttributeSafeString("name", "log4japp");
                xtw.WriteAttributeSafeString("value", AppInfo);
                xtw.WriteEndElement();

                xtw.WriteStartElement("log4j", "data", dummyNamespace);
                xtw.WriteAttributeSafeString("name", "log4jmachinename");
                xtw.WriteAttributeSafeString("value", _machineName);
                xtw.WriteEndElement();

                xtw.WriteEndElement();

                xtw.WriteEndElement();
                xtw.Flush();

                // get rid of 'nlog' and 'log4j' namespace declarations
                sb.Replace(dummyNamespaceRemover, string.Empty);
                sb.Replace(dummyNLogNamespaceRemover, string.Empty);
                builder.Append(sb.ToString());  // StringBuilder.Replace is not good when reusing the StringBuilder
            }
        }
예제 #17
0
        public void NDCTest1()
        {
            List <Exception> exceptions = new List <Exception>();
            ManualResetEvent mre        = new ManualResetEvent(false);
            int counter   = 500;
            int remaining = counter;

            for (int i = 0; i < counter; ++i)
            {
                ThreadPool.QueueUserWorkItem(
                    s =>
                {
                    try
                    {
                        NestedDiagnosticsContext.Clear();
                        Assert.AreEqual(string.Empty, NestedDiagnosticsContext.TopMessage);
                        Assert.AreEqual(string.Empty, NestedDiagnosticsContext.Pop());
                        AssertContents(NestedDiagnosticsContext.GetAllMessages());
                        using (NestedDiagnosticsContext.Push("foo"))
                        {
                            Assert.AreEqual("foo", NestedDiagnosticsContext.TopMessage);
                            AssertContents(NestedDiagnosticsContext.GetAllMessages(), "foo");
                            using (NestedDiagnosticsContext.Push("bar"))
                            {
                                AssertContents(NestedDiagnosticsContext.GetAllMessages(), "bar", "foo");
                                Assert.AreEqual("bar", NestedDiagnosticsContext.TopMessage);
                                NestedDiagnosticsContext.Push("baz");
                                AssertContents(NestedDiagnosticsContext.GetAllMessages(), "baz", "bar", "foo");
                                Assert.AreEqual("baz", NestedDiagnosticsContext.TopMessage);
                                Assert.AreEqual("baz", NestedDiagnosticsContext.Pop());

                                AssertContents(NestedDiagnosticsContext.GetAllMessages(), "bar", "foo");
                                Assert.AreEqual("bar", NestedDiagnosticsContext.TopMessage);
                            }

                            AssertContents(NestedDiagnosticsContext.GetAllMessages(), "foo");
                            Assert.AreEqual("foo", NestedDiagnosticsContext.TopMessage);
                        }

                        AssertContents(NestedDiagnosticsContext.GetAllMessages());
                        Assert.AreEqual(string.Empty, NestedDiagnosticsContext.Pop());
                    }
                    catch (Exception ex)
                    {
                        lock (exceptions)
                        {
                            exceptions.Add(ex);
                        }
                    }
                    finally
                    {
                        if (Interlocked.Decrement(ref remaining) == 0)
                        {
                            mre.Set();
                        }
                    }
                });
            }

            mre.WaitOne();
            Assert.AreEqual(0, exceptions.Count);
        }
예제 #18
0
 /// <summary>
 ///   Pushes the specified text on current thread NDC.
 /// </summary>
 /// <param name = "message">The message to be pushed.</param>
 /// <returns>An instance of the object that implements IDisposable that returns the stack to the previous level when IDisposable.Dispose() is called. To be used with C# using() statement.</returns>
 public IDisposable Push(string message)
 {
     return(NestedDiagnosticsContext.Push(message));
 }
예제 #19
0
 /// <summary>
 ///   Pops the top message off the NDC stack.
 /// </summary>
 /// <returns>The top message which is no longer on the stack.</returns>
 public string Pop()
 {
     return(NestedDiagnosticsContext.Pop());
 }
예제 #20
0
 /// <summary>
 ///   Clears current thread NDC stack.
 /// </summary>
 public void Clear()
 {
     NestedDiagnosticsContext.Clear();
 }
예제 #21
0
 public IDisposable BeginScopeImpl([NotNull] object state)
 {
     return(NestedDiagnosticsContext.Push(state.ToString()));
 }