Exemple #1
0
        internal LoggerConfiguration GetConfigurationForLogger(string name, LoggingConfiguration configuration)
        {
            TargetWithFilterChain[] targetsByLevel     = new TargetWithFilterChain[LogLevel.MaxLevel.Ordinal + 1];
            TargetWithFilterChain[] lastTargetsByLevel = new TargetWithFilterChain[LogLevel.MaxLevel.Ordinal + 1];
            bool[] suppressedLevels = new bool[LogLevel.MaxLevel.Ordinal + 1];

            if (configuration != null && this.IsLoggingEnabled())
            {
                this.GetTargetsByLevelForLogger(name, configuration.LoggingRules, targetsByLevel, lastTargetsByLevel, suppressedLevels);
            }

            InternalLogger.Debug("Targets for {0} by level:", name);
            for (int i = 0; i <= LogLevel.MaxLevel.Ordinal; ++i)
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendFormat(CultureInfo.InvariantCulture, "{0} =>", LogLevel.FromOrdinal(i));
                for (TargetWithFilterChain afc = targetsByLevel[i]; afc != null; afc = afc.NextInChain)
                {
                    sb.AppendFormat(CultureInfo.InvariantCulture, " {0}", afc.Target.Name);
                    if (afc.FilterChain.Count > 0)
                    {
                        sb.AppendFormat(CultureInfo.InvariantCulture, " ({0} filters)", afc.FilterChain.Count);
                    }
                }

                InternalLogger.Debug(sb.ToString());
            }

#pragma warning disable 618
            return(new LoggerConfiguration(targetsByLevel, configuration != null && configuration.ExceptionLoggingOldStyle));

#pragma warning restore 618
        }
Exemple #2
0
        private static bool WriteToTargetWithFilterChain(TargetWithFilterChain targetListHead, LogEventInfo logEvent, AsyncContinuation onException)
        {
            Target       target = targetListHead.Target;
            FilterResult result = GetFilterResult(targetListHead.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)
                {
                    return(false);
                }

                return(true);
            }

            target.WriteAsyncLogEvent(logEvent.WithContinuation(onException));
            if (result == FilterResult.LogFinal)
            {
                return(false);
            }

            return(true);
        }
Exemple #3
0
        internal LoggerConfiguration GetConfigurationForLogger(string name, LoggingConfiguration config)
        {
            TargetWithFilterChain[] targetsByLevel     = new TargetWithFilterChain[LogLevel.MaxLevel.Ordinal + 1];
            TargetWithFilterChain[] lastTargetsByLevel = new TargetWithFilterChain[LogLevel.MaxLevel.Ordinal + 1];

            if (config != null && IsLoggingEnabled())
            {
                GetTargetsByLevelForLogger(name, config.LoggingRules, targetsByLevel, lastTargetsByLevel);
            }

            InternalLogger.Debug("Targets for {0} by level:", name);
            for (int i = 0; i <= LogLevel.MaxLevel.Ordinal; ++i)
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendFormat(CultureInfo.InvariantCulture, "{0} =>", LogLevel.FromOrdinal(i));
                for (TargetWithFilterChain afc = targetsByLevel[i]; afc != null; afc = afc.Next)
                {
                    sb.AppendFormat(CultureInfo.InvariantCulture, " {0}", afc.Target.Name);
                    if (afc.FilterChain.Count > 0)
                    {
                        sb.AppendFormat(CultureInfo.InvariantCulture, " ({0} filters)", afc.FilterChain.Count);
                    }
                }
                InternalLogger.Debug(sb.ToString());
            }

            return(new LoggerConfiguration(targetsByLevel));
        }
Exemple #4
0
        internal static void Write([NotNull] Type loggerType, TargetWithFilterChain targets, LogEventInfo logEvent, LogFactory factory)
        {
            if (targets == null)
            {
                return;
            }

#if !NETSTANDARD1_0 || NETSTANDARD1_5
            StackTraceUsage stu = targets.GetStackTraceUsage();
            if (stu != StackTraceUsage.None && !logEvent.HasStackTrace)
            {
#if NETSTANDARD1_5
                var stackTrace = (StackTrace)Activator.CreateInstance(typeof(StackTrace), new object[] { stu == StackTraceUsage.WithSource });
#elif !SILVERLIGHT
                var stackTrace = new StackTrace(StackTraceSkipMethods, stu == 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);
            }
#endif

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

            if (targets.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 = targets; t != null; t = t.NextInChain)
            {
                FilterResult result = ReferenceEquals(prevFilterChain, t.FilterChain) ?
                                      prevFilterResult : GetFilterResult(t.FilterChain, logEvent);
                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;
            }
        }
Exemple #5
0
        /// <summary>
        /// Creates a logger that discards all log messages.
        /// </summary>
        /// <returns>Null logger instance.</returns>
        public Logger CreateNullLogger()
        {
            TargetWithFilterChain[] targetsByLevel = new TargetWithFilterChain[LogLevel.MaxLevel.Ordinal + 1];
            Logger newLogger = new Logger();

            newLogger.Initialize(string.Empty, new LoggerConfiguration(targetsByLevel, false), this, this.Configuration);
            return(newLogger);
        }
Exemple #6
0
        /// <summary>
        /// Creates a logger that discards all log messages.
        /// </summary>
        /// <returns></returns>
        public Logger CreateNullLogger()
        {
            TargetWithFilterChain[] targetsByLevel = new TargetWithFilterChain[LogLevel.MaxLevel.Ordinal + 1];
            Logger newLogger = new Logger();

            newLogger.Initialize("", new LoggerConfiguration(targetsByLevel), this);
            return(newLogger);
        }
Exemple #7
0
        /// <summary>
        /// Initializes a new instance of <see cref="NullLogger"/>.
        /// </summary>
        /// <param name="factory">The factory class to be used for the creation of this logger.</param>
        public NullLogger(LogFactory factory)
        {
            if (factory == null)
            {
                throw new ArgumentNullException(nameof(factory));
            }

            TargetWithFilterChain[] targetsByLevel = new TargetWithFilterChain[LogLevel.MaxLevel.Ordinal + 1];
            Initialize(string.Empty, new LoggerConfiguration(targetsByLevel, false), factory);
        }
Exemple #8
0
        internal static void Write([NotNull] Type loggerType, TargetWithFilterChain targets, LogEventInfo logEvent, LogFactory factory)
        {
            if (targets == null)
            {
                return;
            }

#if !NETSTANDARD1_0 || NETSTANDARD1_5
            StackTraceUsage stu = targets.GetStackTraceUsage();
            if (stu != StackTraceUsage.None && !logEvent.HasStackTrace)
            {
#if NETSTANDARD1_5
                var stackTrace = (StackTrace)Activator.CreateInstance(typeof(StackTrace), new object[] { stu == StackTraceUsage.WithSource });
#elif !SILVERLIGHT
                var stackTrace = new StackTrace(StackTraceSkipMethods, stu == 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);
            }
#endif

            AsyncContinuation exceptionHandler = (ex) => { };
            if (factory.ThrowExceptions)
            {
                int originalThreadId = AsyncHelpers.GetManagedThreadId();
                exceptionHandler = ex =>
                {
                    if (ex != null && 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;
                }
            }
        }
Exemple #9
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 WINDOWS_UWP
                stackTrace = null;
#elif NETSTANDARD1_5
                stackTrace = (StackTrace)Activator.CreateInstance(typeof(StackTrace), new object[] { stu == StackTraceUsage.WithSource });
#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);
                        }
                    }
                };
            }

            for (var t = targets; t != null; t = t.NextInChain)
            {
                if (!WriteToTargetWithFilterChain(t, logEvent, exceptionHandler))
                {
                    break;
                }
            }
        }
Exemple #10
0
        private void GetTargetsByLevelForLogger(string name, IEnumerable <LoggingRule> rules, TargetWithFilterChain[] targetsByLevel, TargetWithFilterChain[] lastTargetsByLevel, bool[] suppressedLevels)
        {
            //no "System.InvalidOperationException: Collection was modified"
            var loggingRules = new List <LoggingRule>(rules);

            foreach (LoggingRule rule in loggingRules)
            {
                if (!rule.NameMatches(name))
                {
                    continue;
                }

                for (int i = 0; i <= LogLevel.MaxLevel.Ordinal; ++i)
                {
                    if (i < this.GlobalThreshold.Ordinal || suppressedLevels[i] || !rule.IsLoggingEnabledForLevel(LogLevel.FromOrdinal(i)))
                    {
                        continue;
                    }

                    if (rule.Final)
                    {
                        suppressedLevels[i] = true;
                    }

                    foreach (Target target in rule.Targets.ToList())
                    {
                        var awf = new TargetWithFilterChain(target, rule.Filters);
                        if (lastTargetsByLevel[i] != null)
                        {
                            lastTargetsByLevel[i].NextInChain = awf;
                        }
                        else
                        {
                            targetsByLevel[i] = awf;
                        }

                        lastTargetsByLevel[i] = awf;
                    }
                }

                // Recursively analyze the child rules.
                this.GetTargetsByLevelForLogger(name, rule.ChildRules, targetsByLevel, lastTargetsByLevel, suppressedLevels);
            }

            for (int i = 0; i <= LogLevel.MaxLevel.Ordinal; ++i)
            {
                TargetWithFilterChain tfc = targetsByLevel[i];
                if (tfc != null)
                {
                    tfc.PrecalculateStackTraceUsage();
                }
            }
        }
Exemple #11
0
        internal static void Write([NotNull] Type loggerType, [NotNull] TargetWithFilterChain targetsForLevel, LogEventInfo logEvent, LogFactory logFactory)
        {
            logEvent.SetMessageFormatter(logFactory.ActiveMessageFormatter, targetsForLevel.NextInChain == null ? logFactory.SingleTargetMessageFormatter : null);

#if CaptureCallSiteInfo
            StackTraceUsage stu = targetsForLevel.GetStackTraceUsage();
            if (stu != StackTraceUsage.None)
            {
                bool attemptCallSiteOptimization = targetsForLevel.TryCallSiteClassNameOptimization(stu, logEvent);
                if (attemptCallSiteOptimization && targetsForLevel.TryLookupCallSiteClassName(logEvent, out string callSiteClassName))
                {
                    logEvent.CallSiteInformation.CallerClassName = callSiteClassName;
                }
                else if (attemptCallSiteOptimization || targetsForLevel.MustCaptureStackTrace(stu, logEvent))
                {
                    CaptureCallSiteInfo(logFactory, loggerType, logEvent, stu);

                    if (attemptCallSiteOptimization)
                    {
                        targetsForLevel.TryRememberCallSiteClassName(logEvent);
                    }
                }
            }
#endif

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

            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;
            }
        }
Exemple #12
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 !SILVERLIGHT
                stackTrace = new StackTrace(StackTraceSkipMethods, stu == StackTraceUsage.WithSource);
#else
                stackTrace = new StackTrace();
#endif

                int firstUserFrame = FindCallingMethodOnStackTrace(stackTrace, loggerType);

                logEvent.SetStackTrace(stackTrace, firstUserFrame);
            }

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

            for (var t = targets; t != null; t = t.NextInChain)
            {
                if (!WriteToTargetWithFilterChain(t, logEvent, exceptionHandler))
                {
                    break;
                }
            }
        }
Exemple #13
0
        internal void GetTargetsByLevelForLogger(string name, IList <LoggingRule> rules, TargetWithFilterChain[] targetsByLevel, TargetWithFilterChain[] lastTargetsByLevel)
        {
            foreach (LoggingRule rule in rules)
            {
                if (!rule.NameMatches(name))
                {
                    continue;
                }

                for (int i = 0; i <= LogLevel.MaxLevel.Ordinal; ++i)
                {
                    if (i < this.GlobalThreshold.Ordinal || !rule.IsLoggingEnabledForLevel(LogLevel.FromOrdinal(i)))
                    {
                        continue;
                    }

                    foreach (Target target in rule.Targets)
                    {
                        var awf = new TargetWithFilterChain(target, rule.Filters);
                        if (lastTargetsByLevel[i] != null)
                        {
                            lastTargetsByLevel[i].NextInChain = awf;
                        }
                        else
                        {
                            targetsByLevel[i] = awf;
                        }

                        lastTargetsByLevel[i] = awf;
                    }
                }

                this.GetTargetsByLevelForLogger(name, rule.ChildRules, targetsByLevel, lastTargetsByLevel);

                if (rule.Final)
                {
                    break;
                }
            }

            for (int i = 0; i <= LogLevel.MaxLevel.Ordinal; ++i)
            {
                TargetWithFilterChain tfc = targetsByLevel[i];
                if (tfc != null)
                {
                    tfc.PrecalculateStackTraceUsage();
                }
            }
        }
Exemple #14
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(Type loggerType, TargetWithFilterChain targets, LogEventInfo logEvent, LogFactory factory)
        {
            if (targets == null)
            {
                return;
            }

#if !NET_CF
            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);
            }
#endif

            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)
            {
                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);
        }
        // ...
    }
Exemple #17
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;
            }
        }
Exemple #18
0
        internal void GetTargetsByLevelForLogger(string name, LoggingRuleCollection rules, TargetWithFilterChain[] targetsByLevel, TargetWithFilterChain[] lastTargetsByLevel)
        {
            foreach (LoggingRule rule in rules)
            {
                if (rule.NameMatches(name))
                {
                    for (int i = 0; i <= LogLevel.MaxLevel.Ordinal; ++i)
                    {
                        if (i >= GlobalThreshold.Ordinal && rule.IsLoggingEnabledForLevel(LogLevel.FromOrdinal(i)))
                        {
                            foreach (Target target in rule.Targets)
                            {
                                TargetWithFilterChain awf = new TargetWithFilterChain(target, rule.Filters);
                                if (lastTargetsByLevel[i] != null)
                                {
                                    lastTargetsByLevel[i].Next = awf;
                                }
                                else
                                {
                                    targetsByLevel[i] = awf;
                                }
                                lastTargetsByLevel[i] = awf;
                            }
                        }
                    }

                    GetTargetsByLevelForLogger(name, rule.ChildRules, targetsByLevel, lastTargetsByLevel);

                    if (rule.Final)
                    {
                        break;
                    }
                }
            }
            for (int i = 0; i <= LogLevel.MaxLevel.Ordinal; ++i)
            {
                TargetWithFilterChain tfc = targetsByLevel[i];
                if (tfc != null)
                {
                    tfc.PrecalculateNeedsStackTrace();
                }
            }
        }
        private static bool WriteToTargetWithFilterChain(TargetWithFilterChain targetListHead, LogEventInfo logEvent, AsyncContinuation onException)
        {
            Target target = targetListHead.Target;
            FilterResult result = GetFilterResult(targetListHead.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)
                {
                    return false;
                }

                return true;
            }

            target.WriteAsyncLogEvent(logEvent.WithContinuation(onException));
            if (result == FilterResult.LogFinal)
            {
                return false;
            }

            return true;
        }
Exemple #20
0
 private void WriteToTargets(Type wrapperType, [NotNull] LogEventInfo logEvent, [NotNull] TargetWithFilterChain targetsForLevel)
 {
     LoggerImpl.Write(wrapperType ?? DefaultLoggerType, targetsForLevel, PrepareLogEventInfo(logEvent), Factory);
 }
Exemple #21
0
        internal static void Write(Type loggerType, TargetWithFilterChain targets, LogEventInfo logEvent, LogFactory factory)
        {
            if (targets == null)
            {
                return;
            }

#if !NETCF
            bool needTrace        = false;
            bool needTraceSources = false;

            int nst = targets.NeedsStackTrace;

            if (nst > 0)
            {
                needTrace = true;
            }
            if (nst > 1)
            {
                needTraceSources = true;
            }

            StackTrace stackTrace = null;
            if (needTrace && !logEvent.HasStackTrace)
            {
                int firstUserFrame = 0;
                stackTrace = new StackTrace(STACK_TRACE_SKIP_METHODS, needTraceSources);

                for (int i = 0; i < stackTrace.FrameCount; ++i)
                {
                    System.Reflection.MethodBase mb = stackTrace.GetFrame(i).GetMethod();

                    if (mb.DeclaringType == loggerType)
                    {
                        firstUserFrame = i + 1;
                    }
                    else
                    {
                        if (firstUserFrame != 0)
                        {
                            break;
                        }
                    }
                }
                logEvent.SetStackTrace(stackTrace, firstUserFrame);
            }
#endif
            for (TargetWithFilterChain awf = targets; awf != null; awf = awf.Next)
            {
                Target       app    = awf.Target;
                FilterResult result = FilterResult.Neutral;

                try
                {
                    FilterCollection filterChain = awf.FilterChain;

                    for (int i = 0; i < filterChain.Count; ++i)
                    {
                        Filter f = filterChain[i];
                        result = f.Check(logEvent);
                        if (result != FilterResult.Neutral)
                        {
                            break;
                        }
                    }
                    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)
                        {
                            return;
                        }
                        continue;
                    }
                }
                catch (Exception ex)
                {
                    InternalLogger.Error("FilterChain exception: {0}", ex);
                    if (factory.ThrowExceptions)
                    {
                        throw;
                    }
                    else
                    {
                        continue;
                    }
                }

                try
                {
                    app.Write(logEvent);
                }
                catch (Exception ex)
                {
                    InternalLogger.Error("Target exception: {0}", ex);
                    if (factory.ThrowExceptions)
                    {
                        throw;
                    }
                    else
                    {
                        continue;
                    }
                }
                if (result == FilterResult.LogFinal)
                {
                    return;
                }
            }
        }
Exemple #22
0
        internal static void Write([NotNull] Type loggerType, TargetWithFilterChain targets, LogEventInfo logEvent, bool throwsExceptions)
        {
            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 (throwsExceptions)
            {
                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 < 128 &&
                ReferenceEquals(logEvent.MessageFormatter, LogEventInfo.DefaultMessageFormatter))
            {
                // Signal MessageLayoutRenderer to skip string allocation of LogEventInfo.FormattedMessage
                if (!ReferenceEquals(logEvent.MessageFormatter, LogEventInfo.StringFormatMessageFormatter))
                {
                    logEvent.MessageFormatter = LogEventInfo.DefaultMessageFormatterSingleTarget;
                }
            }

            for (var t = targets; t != null; t = t.NextInChain)
            {
                if (!WriteToTargetWithFilterChain(t, logEvent, exceptionHandler))
                {
                    break;
                }
            }
        }
Exemple #23
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();
            }
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="LoggerConfiguration" /> class.
 /// </summary>
 /// <param name="targetsByLevel">The targets by level.</param>
 public LoggerConfiguration(TargetWithFilterChain[] targetsByLevel)
 {
     this.targetsByLevel = targetsByLevel;
 }