private void AppendNdc(XmlWriter xtw)
        {
            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);
            }
        }
示例#2
0
        static void Main(string[] args)
        {
            Logger logger       = LogManager.GetLogger("RmqTarget");
            var    logEventInfo = new LogEventInfo(LogLevel.Debug, "RmqLogMessage", $"This is a test message, generated at {DateTime.UtcNow}.");

            logEventInfo.Properties["fieldA"] = "Field A";
            logEventInfo.Properties["fieldB"] = "Field B";
            logEventInfo.Properties["fields"] = new List <KeyValuePair <string, object> >
            {
                new KeyValuePair <string, object>("FieldC", "Field c")
            };

            // Provide global application properties
            GlobalDiagnosticsContext.Set("globalFieldA", "Global Field A");
            GlobalDiagnosticsContext.Set("globalFieldB", "Global Field B");

            // Provide context properties for the current thread
            NestedDiagnosticsLogicalContext.Push("Nested Field C");

            // Provide scope detail for the current thread
            MappedDiagnosticsLogicalContext.Set("mappedFieldA", "Mapped Field A");
            MappedDiagnosticsLogicalContext.Set("mappedFieldB", "Mapped Field B");

            logger.Log(logEventInfo);


            LogManager.Shutdown();
        }
示例#3
0
        public void Check()
        {
            using (var unitOfWork = _unitOfWorkFactory.GetUnitOfWork(true))
            {
                var repository = unitOfWork.SubmitResultRepository;
                var submit     = repository.DequeueUnchecked();
                if (submit == null)
                {
                    return;
                }

                using (NestedDiagnosticsLogicalContext.Push($"Submit-{submit.Id}"))
                {
                    this.logger.Info($"Dequeued submit");

                    var result = _service.Check(submit);

                    submit.PassedTests       = result.TestsPassedCount;
                    submit.TotalBytes        = result.PeakMemoryBytes;
                    submit.TotalMilliseconds = result.TimeConsumedMilliseconds;
                    submit.Status            = result.GetStatus();
                    submit.CompileOutput     = result.CompileResult.Output;
                    submit.RunDescription    = result.Description;
                    submit.RunOutput         = result.Output;

                    unitOfWork.Commit();
                }
            }
        }
示例#4
0
        public void NestedDiagnosticContextInformation_is_stored_in_the_same_sort_order_as_used_by_the_nested_diagnostic_layout_renderer()
        {
            var ndcSeparator  = "::";
            var ndlcSeparator = " ";

            ConfigureLogManager(ndcSeparator, ndlcSeparator);

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

            NestedDiagnosticsLogicalContext.Clear();
            NestedDiagnosticsContext.Push("baz1");
            NestedDiagnosticsContext.Push("baz2");
            NestedDiagnosticsContext.Push("baz3");

            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);
        }
示例#5
0
        private static void TransferScopeDataToLogEventProperties(LogEventInfo log)
        {
            var allScopes    = NestedDiagnosticsLogicalContext.GetAllObjects();
            var currentScope = allScopes?.FirstOrDefault() as Scope;

            if (currentScope == null)
            {
                return;
            }

            const string scopePropertyName = "Scope";

            log.Properties.Add(scopePropertyName, currentScope.ScopeName);
            log.Properties.Add(nameof(currentScope.ScopeTrace), currentScope.ScopeTrace);
            log.Properties.Add(nameof(currentScope.ScopeId), currentScope.ScopeId.ToString());
            log.Properties.Add(nameof(currentScope.ScopeIdTrace), currentScope.ScopeIdTrace);

            foreach (var property in currentScope.Properties)
            {
                var key = property.Key;
                if (log.Properties.ContainsKey(key))
                {
                    key = "log_scope_" + key;
                }

                // to omit multiple nesting
                if (!log.Properties.ContainsKey(key))
                {
                    log.Properties.Add(key, property.Value);
                }
            }
        }
示例#6
0
        public void NDLCDeepTest()
        {
            LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
            <nlog>
                <targets><target name='debug' type='Debug' layout='${ndlc:topframes=1} ${message}' /></targets>
                <rules>
                    <logger name='*' minlevel='Debug' writeTo='debug' />
                </rules>
            </nlog>");

            NestedDiagnosticsLogicalContext.Clear();

            for (int i = 1; i <= 100; ++i)
            {
                NestedDiagnosticsLogicalContext.Push(i);
            }

            LogManager.GetLogger("A").Debug("0");
            AssertDebugLastMessage("debug", "100 0");

            NestedDiagnosticsLogicalContext.PopObject();
            LogManager.GetLogger("A").Debug("1");
            AssertDebugLastMessage("debug", "99 1");

            NestedDiagnosticsLogicalContext.Clear();
            LogManager.GetLogger("A").Debug("2");
            AssertDebugLastMessage("debug", " 2");
        }
示例#7
0
        public static IDisposable CreateDiagnosticLogicalContext <T>(T state)
        {
            try
            {
#if NETSTANDARD
                return(NestedDiagnosticsLogicalContext.Push(state)); // AsyncLocal has no requirement to be Serializable
#else
// TODO Add support for Net46 in NLog (AsyncLocal), then we only have to do this check for legacy Net451 (CallContext)
                if (state?.GetType().IsSerializable ?? true)
                {
                    return(NestedDiagnosticsLogicalContext.Push(state));
                }
                else
                {
                    return
                        (NestedDiagnosticsLogicalContext
                         .Push(state
                               .ToString())); // Support HostingLogScope, ActionLogScope, FormattedLogValues and others
                }
#endif
            }
            catch (Exception ex)
            {
                InternalLogger.Debug(ex, "Exception in BeginScope push NestedDiagnosticsLogicalContext");
                return(null);
            }
        }
示例#8
0
        /// <summary>
        /// Renders the specified Nested Logical 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 = NestedDiagnosticsLogicalContext.GetAllObjects();

            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);
            }

            string currentSeparator = string.Empty;

            for (int i = endPos - 1; i >= startPos; --i)
            {
                var stringValue = Internal.FormatHelper.ConvertToString(messages[i], logEvent.FormatProvider);
                builder.Append(currentSeparator);
                builder.Append(stringValue);
                currentSeparator = Separator;
            }
        }
示例#9
0
        /// <summary>
        /// Renders the timing details of the Nested Logical 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)
        {
            DateTime scopeBegin = CurrentScope ? NestedDiagnosticsLogicalContext.PeekTopScopeBeginTime() : NestedDiagnosticsLogicalContext.PeekBottomScopeBeginTime();

            if (scopeBegin != DateTime.MinValue)
            {
                if (ScopeBeginTime)
                {
                    var formatProvider = GetFormatProvider(logEvent, null);
                    scopeBegin = Time.TimeSource.Current.FromSystemTime(scopeBegin);
                    builder.Append(scopeBegin.ToString(Format, formatProvider));
                }
                else
                {
                    TimeSpan duration = scopeBegin != DateTime.MinValue ? DateTime.UtcNow - scopeBegin : TimeSpan.Zero;
                    if (duration < TimeSpan.Zero)
                    {
                        duration = TimeSpan.Zero;
                    }
#if !NET3_5
                    var formatProvider = GetFormatProvider(logEvent, null);
                    builder.Append(duration.ToString(Format, formatProvider));
#else
                    builder.Append(duration.ToString());
#endif
                }
            }
        }
示例#10
0
        public IDisposable ParseBeginScope <T>(T state)
        {
            if (_options.CaptureMessageProperties)
            {
                if (state is IList <KeyValuePair <string, object> > scopePropertyList)
                {
                    return(ScopeProperties.CaptureScopeProperties(scopePropertyList));
                }

                if (!(state is string))
                {
                    if (state is System.Collections.IEnumerable scopePropertyCollection)
                    {
                        return(ScopeProperties.CaptureScopeProperties(scopePropertyCollection, _scopeStateExtractors));
                    }
                    else
                    {
                        return(ScopeProperties.CaptureScopeProperty(state, _scopeStateExtractors));
                    }
                }
                else
                {
                    return(NestedDiagnosticsLogicalContext.Push(state));
                }
            }

            return(CreateDiagnosticLogicalContext(state));
        }
        /// <summary>
        /// Begin a scope. Use in config with ${ndlc}
        /// </summary>
        /// <param name="state">The state (message)</param>
        /// <returns></returns>
        public IDisposable BeginScope <TState>(TState state)
        {
            if (state == null)
            {
                throw new ArgumentNullException(nameof(state));
            }

            if (_options.CaptureMessageProperties)
            {
                if (state is IEnumerable <KeyValuePair <string, object> > messageProperties)
                {
                    ScopeProperties scope = new ScopeProperties();

                    foreach (var property in messageProperties)
                    {
                        if (string.IsNullOrEmpty(property.Key))
                        {
                            continue;
                        }

                        scope.AddProperty(property.Key, property.Value);
                    }

                    scope.AddDispose(NestedDiagnosticsLogicalContext.Push(state));
                    return(scope);
                }
            }

            return(NestedDiagnosticsLogicalContext.Push(state));
        }
示例#12
0
 public IDisposable BeginScope <TState>(TState state)
 {
     if (state == null)
     {
         throw new ArgumentNullException(nameof(state));
     }
     return(NestedDiagnosticsLogicalContext.Push(state));
 }
            private static IDisposable CreateScopeProperties(object scopeObject, IReadOnlyList <KeyValuePair <string, object> > propertyList)
            {
                if (propertyList?.Count > 0)
                {
                    return(new ScopeProperties(NestedDiagnosticsLogicalContext.Push(scopeObject), MappedDiagnosticsLogicalContext.SetScoped(propertyList)));
                }

                return(NestedDiagnosticsLogicalContext.Push(scopeObject));
            }
        public void MediumTrustWithExternalClass()
        {
            var fileWritePath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());

            try
            {
                int times = 25;

                {
                    // ClassUnderTest must extend MarshalByRefObject
                    AppDomain partialTrusted;
                    var       classUnderTest = MediumTrustContext.Create <ClassUnderTest>(fileWritePath, out partialTrusted);
#if NET4_0 || NET4_5
                    using (NestedDiagnosticsLogicalContext.Push("PartialTrust"))
#endif
                    {
                        classUnderTest.PartialTrustSuccess(times, fileWritePath);
                    }
                    AppDomain.Unload(partialTrusted);
                }

                // this also checks that thread-volatile layouts
                // such as ${threadid} are properly cached and not recalculated
                // in logging threads.

                var threadID = Thread.CurrentThread.ManagedThreadId.ToString();

                Assert.False(File.Exists(Path.Combine(fileWritePath, "Trace.txt")));

                AssertFileContents(Path.Combine(fileWritePath, "Debug.txt"),
                                   StringRepeat(times, "aaa " + threadID + "\n"), Encoding.UTF8);

                AssertFileContents(Path.Combine(fileWritePath, "Info.txt"),
                                   StringRepeat(times, "bbb " + threadID + "\n"), Encoding.UTF8);

                AssertFileContents(Path.Combine(fileWritePath, "Warn.txt"),
                                   StringRepeat(times, "ccc " + threadID + "\n"), Encoding.UTF8);

                AssertFileContents(Path.Combine(fileWritePath, "Error.txt"),
                                   StringRepeat(times, "ddd " + threadID + "\n"), Encoding.UTF8);

                AssertFileContents(Path.Combine(fileWritePath, "Fatal.txt"),
                                   StringRepeat(times, "eee " + threadID + "\n"), Encoding.UTF8);
            }
            finally
            {
                if (Directory.Exists(fileWritePath))
                {
                    Directory.Delete(fileWritePath, true);
                }

                // Clean up configuration change, breaks onetimeonlyexceptioninhandlertest
                LogManager.ThrowExceptions = true;
            }
        }
示例#15
0
        public void TargetWithContextNdlcSerializeTest()
        {
            NestedDiagnosticsLogicalContext.Clear();
            NestedDiagnosticsLogicalContext.Push(new { a = "b" });

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

            WriteAndAssertSingleKey(target);
        }
示例#16
0
 public static IDisposable CreateDiagnosticLogicalContext <T>(T state)
 {
     try
     {
         return(NestedDiagnosticsLogicalContext.Push(state)); // AsyncLocal has no requirement to be Serializable
     }
     catch (Exception ex)
     {
         InternalLogger.Debug(ex, "Exception in BeginScope push NestedDiagnosticsLogicalContext");
         return(null);
     }
 }
        /// <summary>
        /// Begin a scope. Use in config with ${ndlc}
        /// </summary>
        /// <param name="state">The state (message)</param>
        /// <returns></returns>
        public IDisposable BeginScope <TState>(TState state)
        {
            if (state == null)
            {
                throw new ArgumentNullException(nameof(state));
            }

            if (_options.CaptureMessageProperties && state is IEnumerable <KeyValuePair <string, object> > messageProperties)
            {
                return(ScopeProperties.CreateFromState(state, messageProperties));
            }

            return(NestedDiagnosticsLogicalContext.Push(state));
        }
示例#18
0
        private static void RunAppDomainTestMethod(string fileWritePath, int times, bool autoShutdown)
        {
            // ClassUnderTest must extend MarshalByRefObject
            AppDomain partialTrusted;
            var       classUnderTest = MediumTrustContext.Create <ClassUnderTest>(fileWritePath, out partialTrusted);

#if NET4_0 || NET4_5
            MappedDiagnosticsLogicalContext.Set("Winner", new { Hero = "Zero" });
            using (NestedDiagnosticsLogicalContext.Push(new { Hello = "World" }))
#endif
            {
                classUnderTest.PartialTrustSuccess(times, fileWritePath, autoShutdown);
            }
            AppDomain.Unload(partialTrusted);
        }
            public static IDisposable CaptureScopeProperty <TState>(TState scopeProperty, ExtractorDictionary stateExractor)
            {
                if (!TryLookupExtractor(stateExractor, scopeProperty.GetType(), out var keyValueExtractor))
                {
                    return(NestedDiagnosticsLogicalContext.Push(scopeProperty));
                }

                var propertyValue = TryParseKeyValueProperty(keyValueExtractor, scopeProperty);

                if (!propertyValue.HasValue)
                {
                    return(NestedDiagnosticsLogicalContext.Push(scopeProperty));
                }

                return(new ScopeProperties(NestedDiagnosticsLogicalContext.Push(scopeProperty), MappedDiagnosticsLogicalContext.SetScoped(propertyValue.Value.Key, propertyValue.Value.Value)));
            }
示例#20
0
        public void NDLCTop1TestTest()
        {
            LogManager.Configuration = CreateConfigurationFromString(@"
            <nlog>
                <targets><target name='debug' type='Debug' layout='${ndlc:topframes=1} ${message}' /></targets>
                <rules>
                    <logger name='*' minlevel='Debug' writeTo='debug' />
                </rules>
            </nlog>");

            NestedDiagnosticsLogicalContext.Clear();
            LogManager.GetLogger("A").Debug("0");
            AssertDebugLastMessage("debug", " 0");
            using (NestedDiagnosticsLogicalContext.Push("ala"))
            {
                LogManager.GetLogger("A").Debug("a");
                AssertDebugLastMessage("debug", "ala a");
                using (NestedDiagnosticsLogicalContext.Push("ma"))
                {
                    LogManager.GetLogger("A").Debug("b");
                    AssertDebugLastMessage("debug", "ma b");
                    using (NestedDiagnosticsLogicalContext.Push("kota"))
                    {
                        LogManager.GetLogger("A").Debug("c");
                        AssertDebugLastMessage("debug", "kota c");
                        NestedDiagnosticsLogicalContext.Push("kopytko");
                        LogManager.GetLogger("A").Debug("d");
                        AssertDebugLastMessage("debug", "kopytko d");
                        Assert.Equal("kopytko", NestedDiagnosticsLogicalContext.PopObject()); // 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, NestedDiagnosticsLogicalContext.Pop());
            NestedDiagnosticsLogicalContext.Push("zzz");
            NestedDiagnosticsLogicalContext.Push("yyy");
            Assert.Equal("yyy", NestedDiagnosticsLogicalContext.Pop());
            NestedDiagnosticsLogicalContext.Clear();
            Assert.Equal(string.Empty, NestedDiagnosticsLogicalContext.Pop());
        }
示例#21
0
        public void NDLCTop1TestTest()
        {
            LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
            <nlog>
                <targets><target name='debug' type='Debug' layout='${ndlc:topframes=1} ${message}' /></targets>
                <rules>
                    <logger name='*' minlevel='Debug' writeTo='debug' />
                </rules>
            </nlog>");

            NestedDiagnosticsLogicalContext.Clear();
            LogManager.GetLogger("A").Debug("0");
            AssertDebugLastMessage("debug", " 0");
            using (NestedDiagnosticsLogicalContext.Push("ala"))
            {
                LogManager.GetLogger("A").Debug("a");
                AssertDebugLastMessage("debug", "ala a");
                using (NestedDiagnosticsLogicalContext.Push("ma"))
                {
                    LogManager.GetLogger("A").Debug("b");
                    AssertDebugLastMessage("debug", "ma b");
                    using (NestedDiagnosticsLogicalContext.Push("kota"))
                    {
                        LogManager.GetLogger("A").Debug("c");
                        AssertDebugLastMessage("debug", "kota c");
                        NestedDiagnosticsLogicalContext.Push("kopytko");
                        LogManager.GetLogger("A").Debug("d");
                        AssertDebugLastMessage("debug", "kopytko d");
                        Assert.Equal("kopytko", NestedDiagnosticsLogicalContext.PopObject()); // 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.Null(NestedDiagnosticsLogicalContext.Pop()); //inconsistent with NDC - should be string.empty, but for backwardsscomp. Fix in NLog 5
            NestedDiagnosticsLogicalContext.Push("zzz");
            NestedDiagnosticsLogicalContext.Push("yyy");
            Assert.Equal("yyy", NestedDiagnosticsLogicalContext.Pop());
            NestedDiagnosticsLogicalContext.Clear();
            Assert.Null(NestedDiagnosticsLogicalContext.Pop()); //inconsistent with NDC - should be string.empty, but for backwardsscomp. Fix in NLog 5
        }
            public static IDisposable CreateFromState <TState>(TState state, IEnumerable <KeyValuePair <string, object> > messageProperties)
            {
                ScopeProperties scope = new ScopeProperties();

                foreach (var property in messageProperties)
                {
                    if (String.IsNullOrEmpty(property.Key))
                    {
                        continue;
                    }

                    scope.AddProperty(property.Key, property.Value);
                }

                scope.AddDispose(NestedDiagnosticsLogicalContext.Push(state));
                return(scope);
            }
示例#23
0
        public void NdlcGetAllMessages()
        {
            object value = 5;

            NestedDiagnosticsLogicalContext.Clear();
            var popper = NestedDiagnosticsLogicalContext.Push(value);

            string expected = "5";

            string[] actual = NestedDiagnosticsLogicalContext.GetAllMessages();
            Assert.Single(actual);
            Assert.Equal(expected, actual[0]);

            popper.Dispose();
            actual = NestedDiagnosticsLogicalContext.GetAllMessages();
            Assert.Empty(actual);
        }
        public void FallbackGroupTargetAsyncTest()
        {
            using (new NoThrowNLogExceptions())
            {
                var myTarget1 = new MyTarget {
                    FailCounter = int.MaxValue
                };                                                           // Always failing.
                var myTarget1Async = new AsyncTargetWrapper(myTarget1)
                {
                    TimeToSleepBetweenBatches = 0
                };                                                                                        // Always failing.
                var myTarget2 = new MyTarget()
                {
                    Layout = "${ndlc}"
                };

                var wrapper = CreateAndInitializeFallbackGroupTarget(true, myTarget1Async, myTarget2);

                var exceptions = new List <Exception>();

                // no exceptions
                for (var i = 0; i < 10; ++i)
                {
                    using (NestedDiagnosticsLogicalContext.Push("Hello World"))
                    {
                        wrapper.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add));
                    }
                }

                ManualResetEvent resetEvent = new ManualResetEvent(false);
                myTarget1Async.Flush((ex) => { Assert.Null(ex); resetEvent.Set(); });
                resetEvent.WaitOne(1000);

                Assert.Equal(10, exceptions.Count);
                for (var i = 0; i < 10; ++i)
                {
                    Assert.Null(exceptions[i]);
                }

                Assert.Equal(10, myTarget2.WriteCount);

                AssertNoFlushException(wrapper);
            }
        }
示例#25
0
        public void LegacyNdlcClearShouldNotAffectProperties1()
        {
            // Arrange
            ScopeContext.Clear();
            var    expectedValue = "World";
            var    success       = false;
            object propertyValue;

            // Act
            using (ScopeContext.PushProperty("Hello", expectedValue))
            {
                NestedDiagnosticsLogicalContext.Clear();    // Should not clear anything (skip legacy mode)
                success = ScopeContext.TryGetProperty("Hello", out propertyValue);
            }

            // Assert
            Assert.True(success);
            Assert.Equal(expectedValue, propertyValue);
        }
示例#26
0
        public void NDLCTest()
        {
            LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
            <nlog>
                <targets><target name='debug' type='Debug' layout='${ndlc} ${message}' /></targets>
                <rules>
                    <logger name='*' minlevel='Debug' writeTo='debug' />
                </rules>
            </nlog>");

            NestedDiagnosticsLogicalContext.Clear();
            LogManager.GetLogger("A").Debug("0");
            AssertDebugLastMessage("debug", " 0");
            using (NestedDiagnosticsLogicalContext.Push("ala"))
            {
                LogManager.GetLogger("A").Debug("a");
                AssertDebugLastMessage("debug", "ala a");
                using (NestedDiagnosticsLogicalContext.Push("ma"))
                {
                    LogManager.GetLogger("A").Debug("b");
                    AssertDebugLastMessage("debug", "ala ma b");
                    using (NestedDiagnosticsLogicalContext.Push("kota"))
                    {
                        LogManager.GetLogger("A").Debug("c");
                        AssertDebugLastMessage("debug", "ala ma kota c");
                        using (NestedDiagnosticsLogicalContext.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");
        }
示例#27
0
        /// <summary>
        /// Renders the specified Nested Logical 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 = NestedDiagnosticsLogicalContext.PeekObject();
                if (topFrame != null)
                {
                    AppendAsString(topFrame, GetFormatProvider(logEvent), builder);
                }
                return;
            }

            var messages = NestedDiagnosticsLogicalContext.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;
            }
        }
示例#28
0
        public void NDLCAsyncLogging()
        {
            LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
            <nlog>
                <targets><target name='debug' type='Debug' layout='${ndlc:separator=\:} ${message}' /></targets>
                <rules>
                    <logger name='*' minlevel='Debug' writeTo='debug' />
                </rules>
            </nlog>");

            System.Threading.Tasks.Task task;
            using (NestedDiagnosticsLogicalContext.Push("ala"))
            {
                LogManager.GetLogger("A").Debug("a");
                AssertDebugLastMessage("debug", "ala a");
                task = System.Threading.Tasks.Task.Run(async() => { await System.Threading.Tasks.Task.Delay(50); LogManager.GetLogger("B").Debug("b"); });
            }
            task.Wait();
            AssertDebugLastMessage("debug", "ala b");
        }
        public IDisposable ParseBeginScope <T>(T state)
        {
            if (_options.CaptureMessageProperties)
            {
                if (state is IReadOnlyList <KeyValuePair <string, object> > scopePropertyList)
                {
                    return(ScopeProperties.CaptureScopeProperties(scopePropertyList, _options.IncludeActivtyIdsWithBeginScope));
                }

                if (!(state is string))
                {
                    if (state is IEnumerable scopePropertyCollection)
                    {
                        return(ScopeProperties.CaptureScopeProperties(scopePropertyCollection, _scopeStateExtractors));
                    }

                    return(ScopeProperties.CaptureScopeProperty(state, _scopeStateExtractors));
                }
            }

            return(NestedDiagnosticsLogicalContext.Push(state));
        }
示例#30
0
        public Scope(ILogger logger, string scopeName, IDictionary <string, object> properties)
        {
            if (string.IsNullOrWhiteSpace(scopeName))
            {
                throw new ArgumentNullException(nameof(scopeName));
            }

            _logger = logger ?? throw new ArgumentNullException(nameof(logger));

            _parentScope = GetParentScope();

            ScopeName    = scopeName;
            ScopeId      = Guid.NewGuid();
            ScopeIdTrace = GetScopeTrace();
            ScopeTrace   = GetScopeNameTrace();

            _properties = ConstructScopeProperties(properties);

            _disposable = NestedDiagnosticsLogicalContext.Push(this);

            _logger.Extended(LogLevel.Trace, "Start logical scope", null);
        }