Beispiel #1
0
        /// <summary>
        /// Renders the specified MDC 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)
        {
            //don't use MappedDiagnosticsContext.Get to ensure we are not locking the Factory (indirect by LogManager.Configuration).
            var o = MappedDiagnosticsContext.GetObject(this.Item);

            builder.Append(o, logEvent, LoggingConfiguration);
        }
Beispiel #2
0
        /// <summary>
        /// Renders the specified MDC 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)
        {
            //don't use MappedDiagnosticsContext.Get to ensure we are not locking the Factory (indirect by LogManager.Configuration).
            var value          = MappedDiagnosticsContext.GetObject(Item);
            var formatProvider = GetFormatProvider(logEvent, null);

            builder.AppendFormattedValue(value, Format, formatProvider);
        }
        protected override void Write(LogEventInfo logEventInfo)
        {
            // Sanity check for LogEventInfo
            if (logEventInfo == null)
            {
                throw new ArgumentNullException(nameof(logEventInfo));
            }

            // Make sure we have a properly setup HttpEventCollectorSender
            if (_hecSender == null)
            {
                throw new NLogRuntimeException("SplunkHttpEventCollector SendEventToServer() called before InitializeTarget()");
            }

            // Build metaData
            var metaData = new HttpEventCollectorEventInfo.Metadata(null, logEventInfo.LoggerName, "_json", GetMachineName());

            // Build properties object and add standard values
            var properties = new Dictionary <String, object>
            {
                { "Source", logEventInfo.LoggerName },
                { "Host", GetMachineName() },
                { "CorrelationId", (String)MappedDiagnosticsContext.GetObject("CorrelationId") },
            };

            // add attached properties
            if (logEventInfo.HasProperties)
            {
                foreach (var key in logEventInfo.Properties.Keys)
                {
                    properties.Add(key.ToString(), logEventInfo.Properties[key]);
                }
            }

            // add parameters
            if (logEventInfo.Parameters != null && logEventInfo.Parameters.Length > 0)
            {
                for (int i = 0; i < logEventInfo.Parameters.Length; i++)
                {
                    properties.Add("{" + i + "}", logEventInfo.Parameters[i]);
                }
            }

            // Send the event to splunk
            _hecSender.Send(null, logEventInfo.Level.Name, logEventInfo.Message, logEventInfo.FormattedMessage, logEventInfo.Exception, properties, metaData);
            _hecSender.FlushSync();
        }
        private void AppendProperties(XmlWriter xtw)
        {
            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();
                }
            }
        }
Beispiel #5
0
        public void timer_cannot_inherit_mappedcontext()
        {
            object getObject = null;
            string getValue  = null;

            var   mre    = new ManualResetEvent(false);
            Timer thread = new Timer((s) =>
            {
                try
                {
                    getObject = MappedDiagnosticsContext.GetObject("DoNotExist");
                    getValue  = MappedDiagnosticsContext.Get("DoNotExistEither");
                }
                finally
                {
                    mre.Set();
                }
            });

            thread.Change(0, Timeout.Infinite);
            mre.WaitOne();
            Assert.Null(getObject);
            Assert.Empty(getValue);
        }
Beispiel #6
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
            }
        }
Beispiel #7
0
        private void RenderJsonFormattedMessage(LogEventInfo logEvent, StringBuilder sb)
        {
            //Memory profiling pointed out that using a foreach-loop was allocating
            //an Enumerator. Switching to a for-loop avoids the memory allocation.
            for (int i = 0; i < this.Attributes.Count; i++)
            {
                var    attrib = this.Attributes[i];
                string text   = attrib.LayoutWrapper.Render(logEvent);
                if (!string.IsNullOrEmpty(text))
                {
                    AppendJsonAttributeValue(attrib.Name, attrib.Encode, text, sb);
                }
            }

            if (this.IncludeMdc)
            {
                foreach (string key in MappedDiagnosticsContext.GetNames())
                {
                    if (string.IsNullOrEmpty(key))
                    {
                        continue;
                    }
                    object propertyValue = MappedDiagnosticsContext.GetObject(key);
                    AppendJsonPropertyValue(key, propertyValue, sb);
                }
            }

#if NET4_0 || NET4_5
            if (this.IncludeMdlc)
            {
                foreach (string key in MappedDiagnosticsLogicalContext.GetNames())
                {
                    if (string.IsNullOrEmpty(key))
                    {
                        continue;
                    }
                    object propertyValue = MappedDiagnosticsLogicalContext.GetObject(key);
                    AppendJsonPropertyValue(key, propertyValue, sb);
                }
            }
#endif

            if (this.IncludeAllProperties && logEvent.HasProperties)
            {
                foreach (var prop in logEvent.Properties)
                {
                    //Determine property name
                    string propName = Internal.XmlHelper.XmlConvertToString(prop.Key ?? string.Empty);
                    if (string.IsNullOrEmpty(propName))
                    {
                        continue;
                    }

                    //Skips properties in the ExcludeProperties list
                    if (this.ExcludeProperties.Contains(propName))
                    {
                        continue;
                    }

                    AppendJsonPropertyValue(propName, prop.Value, sb);
                }
            }

            CompleteJsonMessage(sb);
        }
        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());
        }
        /// <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
            }
        }
Beispiel #10
0
        private void RenderJsonFormattedMessage(LogEventInfo logEvent, StringBuilder sb)
        {
            int orgLength = sb.Length;

            //Memory profiling pointed out that using a foreach-loop was allocating
            //an Enumerator. Switching to a for-loop avoids the memory allocation.
            for (int i = 0; i < this.Attributes.Count; i++)
            {
                var attrib             = this.Attributes[i];
                int beforeAttribLength = sb.Length;
                if (!RenderAppendJsonPropertyValue(attrib, logEvent, false, sb, sb.Length == orgLength))
                {
                    sb.Length = beforeAttribLength;
                }
            }

            if (this.IncludeMdc)
            {
                foreach (string key in MappedDiagnosticsContext.GetNames())
                {
                    if (string.IsNullOrEmpty(key))
                    {
                        continue;
                    }
                    object propertyValue = MappedDiagnosticsContext.GetObject(key);
                    AppendJsonPropertyValue(key, propertyValue, sb, sb.Length == orgLength);
                }
            }

#if !SILVERLIGHT
            if (this.IncludeMdlc)
            {
                foreach (string key in MappedDiagnosticsLogicalContext.GetNames())
                {
                    if (string.IsNullOrEmpty(key))
                    {
                        continue;
                    }
                    object propertyValue = MappedDiagnosticsLogicalContext.GetObject(key);
                    AppendJsonPropertyValue(key, propertyValue, sb, sb.Length == orgLength);
                }
            }
#endif

            if (this.IncludeAllProperties && logEvent.HasProperties)
            {
                foreach (var prop in logEvent.Properties)
                {
                    //Determine property name
                    string propName = Internal.XmlHelper.XmlConvertToString(prop.Key ?? string.Empty);
                    if (string.IsNullOrEmpty(propName))
                    {
                        continue;
                    }

                    //Skips properties in the ExcludeProperties list
                    if (this.ExcludeProperties.Contains(propName))
                    {
                        continue;
                    }

                    AppendJsonPropertyValue(propName, prop.Value, sb, sb.Length == orgLength);
                }
            }

            if (sb.Length > orgLength)
            {
                CompleteJsonMessage(sb);
            }
        }
Beispiel #11
0
 private object GetValue()
 {
     //don't use MappedDiagnosticsContext.Get to ensure we are not locking the Factory (indirect by LogManager.Configuration).
     return(MappedDiagnosticsContext.GetObject(Item));
 }
        /// <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 (string key in MappedDiagnosticsContext.GetNames())
                    {
                        xtw.WriteStartElement("log4j", "data", dummyNamespace);
                        xtw.WriteAttributeSafeString("name", key);
                        xtw.WriteAttributeSafeString("value", String.Format(logEvent.FormatProvider, "{0}", MappedDiagnosticsContext.GetObject(key)));
                        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());
            }
        }