Пример #1
0
        internal static void Write(Type loggerType, TargetWithFilterChain targets, LogEventInfo logEvent, LogFactory factory)
        {
            InternalLogger.Trace("Writing event {0} {1} {2}", logEvent.LoggerName, logEvent.Level, logEvent.Message);

            if (targets == null)
            {
                return;
            }

            StackTraceUsage stu = targets.GetStackTraceUsage();

            if (stu != StackTraceUsage.None && !logEvent.HasStackTrace)
            {
                StackTrace stackTrace;
#if !SILVERLIGHT
                stackTrace = new StackTrace(StackTraceSkipMethods, stu == StackTraceUsage.WithSource);
#else
                stackTrace = new StackTrace();
#endif

                int firstUserFrame = FindCallingMethodOnStackTrace(stackTrace, loggerType);

                logEvent.SetStackTrace(stackTrace, firstUserFrame);
            }

            int originalThreadId = Thread.CurrentThread.ManagedThreadId;
            AsyncContinuation exceptionHandler = ex =>
            {
                if (ex != null)
                {
                    if (factory.ThrowExceptions && Thread.CurrentThread.ManagedThreadId == originalThreadId)
                    {
                        throw new NLogRuntimeException("Exception occurred in NLog", ex);
                    }
                }
            };

            for (var t = targets; t != null; t = t.NextInChain)
            {
                InternalLogger.Trace("Writing to logger {0}", t.Target.Name);
                if (!WriteToTargetWithFilterChain(t, logEvent, exceptionHandler))
                {
                    break;
                }
            }
        }
    internal static void Write([NotNull] Type loggerType, TargetWithFilterChain targets, LogEventInfo logEvent, LogFactory factory)
    {
        if (targets == null)
        {
            return;
        }
        StackTraceUsage stu = targets.GetStackTraceUsage();

        if (stu != StackTraceUsage.None && !logEvent.HasStackTrace)
        {
            var stackTrace           = new StackTrace(StackTraceSkipMethods, stu == StackTraceUsage.WithSource);
            var stackFrames          = stackTrace.GetFrames();
            int?firstUserFrame       = FindCallingMethodOnStackTrace(stackFrames, loggerType);
            int?firstLegacyUserFrame = firstUserFrame.HasValue ? SkipToUserStackFrameLegacy(stackFrames, firstUserFrame.Value) : (int?)null;
            logEvent.GetCallSiteInformationInternal().SetStackTrace(stackTrace, firstUserFrame ?? 0, firstLegacyUserFrame);
        }
        // ...
    }
Пример #3
0
        internal bool MustCaptureStackTrace(StackTraceUsage stackTraceUsage, LogEventInfo logEvent)
        {
            if (logEvent.HasStackTrace)
            {
                return(false);
            }

            if ((stackTraceUsage & StackTraceUsage.WithStackTrace) != StackTraceUsage.None)
            {
                return(true);
            }

            if ((stackTraceUsage & StackTraceUsage.WithCallSite) != StackTraceUsage.None && string.IsNullOrEmpty(logEvent.CallSiteInformation?.CallerMethodName) && string.IsNullOrEmpty(logEvent.CallSiteInformation?.CallerFilePath))
            {
                return(true);    // We don't have enough CallSiteInformation
            }
            return(false);
        }
Пример #4
0
        internal static void Write([NotNull] Type loggerType, [NotNull] TargetWithFilterChain targetsForLevel, LogEventInfo logEvent, LogFactory factory)
        {
#if CaptureCallSiteInfo
            StackTraceUsage stu = targetsForLevel.GetStackTraceUsage();
            if (stu != StackTraceUsage.None && !logEvent.HasStackTrace)
            {
                CaptureCallSiteInfo(factory, loggerType, logEvent, stu);
            }
#endif

            AsyncContinuation exceptionHandler = SingleCallContinuation.Completed;
            if (factory.ThrowExceptions)
            {
                int originalThreadId = AsyncHelpers.GetManagedThreadId();
                exceptionHandler = ex =>
                {
                    if (ex != null && AsyncHelpers.GetManagedThreadId() == originalThreadId)
                    {
                        throw new NLogRuntimeException("Exception occurred in NLog", ex);
                    }
                };
            }

            if (targetsForLevel.NextInChain == null && logEvent.CanLogEventDeferMessageFormat())
            {
                // Change MessageFormatter so it writes directly to StringBuilder without string-allocation
                logEvent.MessageFormatter = LogMessageTemplateFormatter.DefaultAutoSingleTarget.MessageFormatter;
            }

            IList <Filter> prevFilterChain  = null;
            FilterResult   prevFilterResult = FilterResult.Neutral;
            for (var t = targetsForLevel; t != null; t = t.NextInChain)
            {
                FilterResult result = ReferenceEquals(prevFilterChain, t.FilterChain) ?
                                      prevFilterResult : GetFilterResult(t.FilterChain, logEvent, t.DefaultResult);
                if (!WriteToTargetWithFilterChain(t.Target, result, logEvent, exceptionHandler))
                {
                    break;
                }

                prevFilterResult = result;  // Cache the result, and reuse it for the next target, if it comes from the same logging-rule
                prevFilterChain  = t.FilterChain;
            }
        }
Пример #5
0
        internal bool TryCallSiteClassNameOptimization(StackTraceUsage stackTraceUsage, LogEventInfo logEvent)
        {
            if ((stackTraceUsage & (StackTraceUsage.WithCallSiteClassName | StackTraceUsage.WithStackTrace)) != StackTraceUsage.WithCallSiteClassName)
            {
                return(false);
            }

            if (string.IsNullOrEmpty(logEvent.CallSiteInformation?.CallerFilePath))
            {
                return(false);
            }

            if (logEvent.HasStackTrace)
            {
                return(false);
            }

            return(true);
        }
Пример #6
0
        internal void PrecalculateStackTraceUsage()
        {
            this.stackTraceUsage = StackTraceUsage.None;

            // find all objects which may need stack trace
            // and determine maximum
            foreach (var item in ObjectGraphScanner.FindReachableObjects <IUsesStackTrace>(this))
            {
                var stu = item.StackTraceUsage;

                if (stu > this.stackTraceUsage)
                {
                    this.stackTraceUsage = stu;

                    if (this.stackTraceUsage >= StackTraceUsage.Max)
                    {
                        break;
                    }
                }
            }
        }
        internal void SetRenderers(LayoutRenderer[] renderers, string text)
        {
            this.Renderers = new ReadOnlyCollection <LayoutRenderer>(renderers);

            if (this.Renderers.Count == 0)
            {
                //todo fixedText = null is also used if the text is fixed, but is a empty renderers not fixed?
                this.fixedText       = null;
                this.StackTraceUsage = StackTraceUsage.None;
            }
            else if (this.Renderers.Count == 1 && this.Renderers[0] is LiteralLayoutRenderer)
            {
                this.fixedText       = ((LiteralLayoutRenderer)this.Renderers[0]).Text;
                this.StackTraceUsage = StackTraceUsage.None;
            }
            else
            {
                this.fixedText       = null;
                this.StackTraceUsage = this.Renderers.OfType <IUsesStackTrace>().DefaultIfEmpty().Max(usage => usage == null ? StackTraceUsage.None : usage.StackTraceUsage);
            }

            this.layoutText = text;
        }
Пример #8
0
        internal void PrecalculateStackTraceUsage()
        {
            this.stackTraceUsage = StackTraceUsage.None;

            // find all objects which may need stack trace
            // and determine maximum
            foreach (var item in ObjectGraphScanner.FindReachableObjects<IUsesStackTrace>(this))
            {
                var stu = item.StackTraceUsage;

                if (stu > this.stackTraceUsage)
                {
                    this.stackTraceUsage = stu;

                    if (this.stackTraceUsage >= StackTraceUsage.Max)
                    {
                        break;
                    }
                }
            }
        }
Пример #9
0
 /// <summary>
 /// Initializes a new instance of the <see cref="TargetWithFilterChain" /> class.
 /// </summary>
 /// <param name="target">The target.</param>
 /// <param name="filterChain">The filter chain.</param>
 public TargetWithFilterChain(Target target, IList<Filter> filterChain)
 {
     this.Target = target;
     this.FilterChain = filterChain;
     this.stackTraceUsage = StackTraceUsage.None;
 }
Пример #10
0
        private static void CaptureCallSiteInfo(LogFactory factory, Type loggerType, LogEventInfo logEvent, StackTraceUsage stackTraceUsage)
        {
            try
            {
#if NETSTANDARD1_5
                var stackTrace = (StackTrace)Activator.CreateInstance(typeof(StackTrace), new object[] { stackTraceUsage == StackTraceUsage.WithSource });
#elif !SILVERLIGHT
                var stackTrace = new StackTrace(StackTraceSkipMethods, stackTraceUsage == StackTraceUsage.WithSource);
#else
                var stackTrace = new StackTrace();
#endif

                logEvent.GetCallSiteInformationInternal().SetStackTrace(stackTrace, null, loggerType);
            }
            catch (Exception ex)
            {
                if (factory.ThrowExceptions || ex.MustBeRethrownImmediately())
                {
                    throw;
                }

                InternalLogger.Error(ex, "Failed to capture CallSite for Logger {0}. Platform might not support ${{callsite}}", logEvent.LoggerName);
            }
        }
Пример #11
0
 internal static StackTraceUsage Max(StackTraceUsage u1, StackTraceUsage u2)
 {
     return (StackTraceUsage)Math.Max((int)u1, (int)u2);
 }
Пример #12
0
 /// <summary>
 /// Initializes a new instance of the <see cref="TargetWithFilterChain" /> class.
 /// </summary>
 /// <param name="target">The target.</param>
 /// <param name="filterChain">The filter chain.</param>
 public TargetWithFilterChain(Target target, IList <Filter> filterChain)
 {
     this.Target          = target;
     this.FilterChain     = filterChain;
     this.stackTraceUsage = StackTraceUsage.None;
 }
Пример #13
0
 /// <summary>
 ///     Initializes a new instance of the <see cref="TargetWithFilterChain" /> class.
 /// </summary>
 /// <param name="target">The target.</param>
 /// <param name="filterChain">The filter chain.</param>
 public TargetWithFilterChain(Target target, IList <Filter> filterChain)
 {
     Target          = target;
     FilterChain     = filterChain;
     stackTraceUsage = StackTraceUsage.None;
 }
Пример #14
0
 /// <summary>
 ///     Initializes a new instance of the <see cref="TargetWithFilterChain" /> class.
 /// </summary>
 /// <param name="target">The target.</param>
 /// <param name="filterChain">The filter chain.</param>
 public TargetWithFilterChain(Target target, IList<Filter> filterChain)
 {
     Target = target;
     FilterChain = filterChain;
     stackTraceUsage = StackTraceUsage.None;
 }
Пример #15
0
        internal static void Write([NotNull] Type loggerType, TargetWithFilterChain targets, LogEventInfo logEvent, LogFactory factory)
        {
            if (targets == null)
            {
                return;
            }

            StackTraceUsage stu = targets.GetStackTraceUsage();

            if (stu != StackTraceUsage.None && !logEvent.HasStackTrace)
            {
                StackTrace stackTrace;
#if NETSTANDARD1_5
                stackTrace = (StackTrace)Activator.CreateInstance(typeof(StackTrace), new object[] { stu == StackTraceUsage.WithSource });
#elif NETSTANDARD1_0
                stackTrace = null;
#elif !SILVERLIGHT
                stackTrace = new StackTrace(StackTraceSkipMethods, stu == StackTraceUsage.WithSource);
#else
                stackTrace = new StackTrace();
#endif
                if (stackTrace != null)
                {
                    var stackFrames          = stackTrace.GetFrames();
                    int?firstUserFrame       = FindCallingMethodOnStackTrace(stackFrames, loggerType);
                    int?firstLegacyUserFrame = firstUserFrame.HasValue ? SkipToUserStackFrameLegacy(stackFrames, firstUserFrame.Value) : (int?)null;
                    logEvent.GetCallSiteInformationInternal().SetStackTrace(stackTrace, firstUserFrame ?? 0, firstLegacyUserFrame);
                }
            }

            AsyncContinuation exceptionHandler = (ex) => { };
            if (factory.ThrowExceptions)
            {
                int originalThreadId = AsyncHelpers.GetManagedThreadId();
                exceptionHandler = ex =>
                {
                    if (ex != null)
                    {
                        if (AsyncHelpers.GetManagedThreadId() == originalThreadId)
                        {
                            throw new NLogRuntimeException("Exception occurred in NLog", ex);
                        }
                    }
                };
            }

            if (targets.NextInChain == null &&
                logEvent.Parameters != null &&
                logEvent.Parameters.Length > 0 &&
                logEvent.Message?.Length < 256 &&
                ReferenceEquals(logEvent.MessageFormatter, LogMessageTemplateFormatter.DefaultAuto.MessageFormatter))
            {
                logEvent.MessageFormatter = LogMessageTemplateFormatter.DefaultAutoSingleTarget.MessageFormatter;
            }

            for (var t = targets; t != null; t = t.NextInChain)
            {
                if (!WriteToTargetWithFilterChain(t, logEvent, exceptionHandler))
                {
                    break;
                }
            }
        }
Пример #16
0
        internal void SetRenderers(LayoutRenderer[] renderers, string text)
        {
            this.Renderers = new ReadOnlyCollection<LayoutRenderer>(renderers);

            if (this.Renderers.Count == 0)
            {
                //todo fixedText = null is also used if the text is fixed, but is a empty renderers not fixed?
                this.fixedText = null;
                this.StackTraceUsage = StackTraceUsage.None;
            }
            else if (this.Renderers.Count == 1 && this.Renderers[0] is LiteralLayoutRenderer)
            {
                this.fixedText = ((LiteralLayoutRenderer)this.Renderers[0]).Text;
                this.StackTraceUsage = StackTraceUsage.None;
            }
            else
            {
                this.fixedText = null;
                this.StackTraceUsage = this.Renderers.OfType<IUsesStackTrace>().DefaultIfEmpty().Max(usage => usage == null ? StackTraceUsage.None : usage.StackTraceUsage);
            }

            this.layoutText = text;
        }
Пример #17
0
        internal static void Write([NotNull] Type loggerType, TargetWithFilterChain targets, LogEventInfo logEvent, LogFactory factory)
        {
            if (targets == null)
            {
                return;
            }

            StackTraceUsage stu = targets.GetStackTraceUsage();

            if (stu != StackTraceUsage.None && !logEvent.HasStackTrace)
            {
                StackTrace stackTrace;
#if !SILVERLIGHT
                stackTrace = new StackTrace(StackTraceSkipMethods, stu == StackTraceUsage.WithSource);
#else
                stackTrace = new StackTrace();
#endif

                int firstUserFrame = FindCallingMethodOnStackTrace(stackTrace, loggerType);

                logEvent.SetStackTrace(stackTrace, firstUserFrame);
            }

            ExceptionHandlerContinuation handler;
            int numberOfTargets = 0;

            for (var t = targets; t != null; t = t.NextInChain)
            {
                FilterResult result = GetFilterResult(t.FilterChain, logEvent);

                if ((result == FilterResult.Ignore) || (result == FilterResult.IgnoreFinal))
                {
                    if (InternalLogger.IsDebugEnabled)
                    {
                        InternalLogger.Debug(
                            "{0}.{1} Rejecting message because of a filter.",
                            logEvent.LoggerName,
                            logEvent.Level);
                    }

                    if (result == FilterResult.IgnoreFinal)
                    {
                        break;
                    }
                }
                else
                {
                    numberOfTargets += 1;
                }
            }

            if (factory.Configuration.PoolingEnabled())
            {
                handler = factory.Configuration.PoolFactory.Get <ExceptionHandlerPool, ExceptionHandlerContinuation>().Get(Thread.CurrentThread.ManagedThreadId, factory.ThrowExceptions);
            }
            else
            {
                handler = new ExceptionHandlerContinuation(Thread.CurrentThread.ManagedThreadId, factory.ThrowExceptions);
            }

            bool clone = numberOfTargets > 1;

            // Clone a message for each target, so that each target can put it back into the pool when its done with it.

            for (var t = targets; t != null; t = t.NextInChain)
            {
                if (!WriteToTargetWithFilterChain(t, logEvent, handler.Delegate, clone))
                {
                    break;
                }
            }


            // No targets at all wanted this log event, so put it back into the pool
            if (numberOfTargets == 0 || clone)
            {
                logEvent.PutBack();
            }
        }
Пример #18
0
 internal static StackTraceUsage Max(StackTraceUsage u1, StackTraceUsage u2)
 {
     return((StackTraceUsage)Math.Max((int)u1, (int)u2));
 }
Пример #19
0
        private static void CaptureCallSiteInfo(LogFactory factory, Type loggerType, LogEventInfo logEvent, StackTraceUsage stackTraceUsage)
        {
            try
            {
#if NETSTANDARD1_5
                var stackTrace = (StackTrace)Activator.CreateInstance(typeof(StackTrace), new object[] { stackTraceUsage == StackTraceUsage.WithSource });
#elif !SILVERLIGHT
                var stackTrace = new StackTrace(StackTraceSkipMethods, stackTraceUsage == StackTraceUsage.WithSource);
#else
                var stackTrace = new StackTrace();
#endif
                var stackFrames          = stackTrace.GetFrames();
                int?firstUserFrame       = FindCallingMethodOnStackTrace(stackFrames, loggerType);
                int?firstLegacyUserFrame = firstUserFrame.HasValue ? SkipToUserStackFrameLegacy(stackFrames, firstUserFrame.Value) : (int?)null;
                logEvent.GetCallSiteInformationInternal().SetStackTrace(stackTrace, firstUserFrame ?? 0, firstLegacyUserFrame);
            }
            catch (Exception ex)
            {
                if (factory.ThrowExceptions || ex.MustBeRethrownImmediately())
                {
                    throw;
                }

                InternalLogger.Error(ex, "Failed to capture CallSite for Logger {0}. Platform might not support ${{callsite}}", logEvent.LoggerName);
            }
        }