private static void ExtendedWithException(ILogger logger, LogLevel logLevel, string message, object logProperties,
                                                  Exception ex, int exceptionIndex, int exceptionCount, string tag)
        {
            var log = new LogEventInfo(logLevel, logger.Name, message);

            TransferDataToLogEventProperties(log, logProperties);

            if (ex != null)
            {
                log.Exception = ex;
                log.Properties.Add("ExceptionIndex", exceptionIndex);
                log.Properties.Add("ExceptionCount", exceptionCount);

                if (!string.IsNullOrEmpty(tag))
                {
                    log.Properties.Add("ExceptionTag", tag);
                }
            }

            var stackTrace = new StackTrace(0);

            log.SetStackTrace(stackTrace, StackHelper.IndexOfFirstCallingMethod(stackTrace.GetFrames()));

            logger.Log(log);
        }
예제 #2
0
        private static void ExtendedWithException(ILogger logger, LogLevel logLevel, string message,
                                                  object logProperties,
                                                  Exception ex, int exceptionIndex, int exceptionCount, string tag)
        {
            var log = new LogEventInfo(logLevel, logger.Name, message);

            TransferDataObjectToLogEventProperties(log, logProperties);
            TransferContextDataToLogEventProperties(log);
            TransferScopeDataToLogEventProperties(log);

            if (ex != null)
            {
                log.Exception = ex;
                log.Properties.Add("ExceptionIndex", exceptionIndex);
                log.Properties.Add("ExceptionCount", exceptionCount);

                if (!string.IsNullOrEmpty(tag))
                {
                    log.Properties.Add("ExceptionTag", tag);
                }
            }

#if NET452
            var stackTrace = new StackTrace(0);
            log.SetStackTrace(stackTrace, StackHelper.IndexOfFirstCallingMethod(stackTrace.GetFrames()));
            // todo: There is still no netCore subsitiute for this!
#endif

            logger.Log(log);
        }
예제 #3
0
        /// <summary>
        /// 消息寫入日誌的詳細處理
        /// </summary>
        /// <param name="logLevel">日誌處理級別</param>
        /// <param name="message">日誌信息<see cref="ILogContext"/>自定義的屬性消息,寫入到<see cref="LogEventInfo.Properties"/></param>
        /// <param name="exception">異常對象</param>
        protected override void WriteInternal(Common.Logging.LogLevel logLevel, object message, Exception exception)
        {
            LogLevel     level       = GetLevel(logLevel);
            ILogContext  context     = message as ILogContext;
            object       messageText = context == null ? message : context.Message;
            LogEventInfo logEvent    = new LogEventInfo(level, _logger.Name, null, "{0}", new object[1] {
                messageText
            }, exception);

            context?.Properties.ToList().ForEach(logEvent.Properties.Add);
            StackTrace st    = new StackTrace(0);
            int        index = 0;

            StackFrame[] frames = st.GetFrames();
            foreach (StackFrame sf in frames)
            {
                MethodBase mb = sf.GetMethod();
                Type       dt = mb.DeclaringType;
                if (dt == null || ExcludeTypes.Contains(dt) || ExcludeAssemblies.Contains(dt.Assembly) || ExcludeNameSpaces.Contains(dt.Namespace))
                {
                    index++;
                    continue;
                }
                logEvent.SetStackTrace(st, index);
                break;
            }
            _logger.Log(GetType(), logEvent);
        }
        public override void TraceTransfer(TraceEventCache eventCache, string loggerName, int eventId, string message, Guid relatedActivityId)
        {
            var ev = new LogEventInfo();

            ev.LoggerName = (loggerName ?? this.Name) ?? string.Empty;

#if !NET_CF
            if (this.AutoLoggerName)
            {
                var        stack          = new StackTrace();
                int        userFrameIndex = -1;
                MethodBase userMethod     = null;

                for (int i = 0; i < stack.FrameCount; ++i)
                {
                    var frame  = stack.GetFrame(i);
                    var method = frame.GetMethod();

                    if (method.DeclaringType == this.GetType())
                    {
                        // skip all methods of this type
                        continue;
                    }

                    if (method.DeclaringType.Assembly == systemAssembly)
                    {
                        // skip all methods from System.dll
                        continue;
                    }

                    userFrameIndex = i;
                    userMethod     = method;
                    break;
                }

                if (userFrameIndex >= 0)
                {
                    ev.SetStackTrace(stack, userFrameIndex);
                    if (userMethod.DeclaringType != null)
                    {
                        ev.LoggerName = userMethod.DeclaringType.FullName;
                    }
                }
            }
#endif

            ev.TimeStamp = DateTime.Now;
            ev.Message   = message;
            ev.Level     = this.ForceLogLevel ?? LogLevel.Debug;

            ev.Properties.Add("EventID", eventId);
            ev.Properties.Add("RelatedActivityID", relatedActivityId);

            Logger logger = LogManager.GetLogger(ev.LoggerName);
            logger.Log(ev);
        }
예제 #5
0
        public void CallSiteShouldWorkEvenInlined()
        {
            Type loggerType = typeof(Logger);
            var  stacktrace = StackTraceUsageUtils.GetWriteStackTrace(loggerType);
            var  index      = LoggerImpl.FindCallingMethodOnStackTrace(stacktrace, loggerType);
            var  logEvent   = new LogEventInfo(LogLevel.Error, "logger1", "message1");

            logEvent.SetStackTrace(stacktrace, index);
            Layout l        = "${callsite}";
            var    callSite = l.Render(logEvent);

            Assert.Equal("NLog.UnitTests.LayoutRenderers.CallSiteTests.CallSiteShouldWorkEvenInlined", callSite);
        }
예제 #6
0
        public async Task <string> GetAsyncCallSite()
        {
            Type loggerType = typeof(Logger);
            var  stacktrace = StackTraceUsageUtils.GetWriteStackTrace(loggerType);
            var  index      = LoggerImpl.FindCallingMethodOnStackTrace(stacktrace, loggerType);
            var  logEvent   = new LogEventInfo(LogLevel.Error, "logger1", "message1");

            logEvent.SetStackTrace(stacktrace, index);

            await Task.Delay(0);

            Layout l        = "${callsite}";
            var    callSite = l.Render(logEvent);

            return(callSite);
        }
예제 #7
0
        public void RenderStackTraceNoCaptureStackTraceWithStackTrace()
        {
            LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
            <nlog>
                <targets><target name='debug' type='Debug' layout='${message} ${stacktrace:captureStackTrace=false}' /></targets>
                <rules>
                    <logger name='*' minlevel='Debug' writeTo='debug' />
                </rules>
            </nlog>");

            var logEvent = new LogEventInfo(LogLevel.Info, null, "I am:");

            logEvent.SetStackTrace(new System.Diagnostics.StackTrace(true), 0);
            LogManager.GetCurrentClassLogger().Log(logEvent);
            AssertDebugLastMessageContains("debug", $" => {nameof(StackTraceRendererTests)}.{nameof(RenderStackTraceNoCaptureStackTraceWithStackTrace)}");
        }
예제 #8
0
        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;
                }
            }
        }
예제 #9
0
        public void Log(LoggingData loggingData)
        {
            var logEvent = new LogEventInfo();

            logEvent.LoggerName = loggingData.LoggerName;
            logEvent.Message    = loggingData.Message;
            logEvent.TimeStamp  = loggingData.TimeStamp;

            if (!string.IsNullOrEmpty(loggingData.ExceptionString))
            {
                logEvent.Exception = new Exception(loggingData.ExceptionString);
            }

            if (loggingData.Properties != null && loggingData.Properties.Count > 0)
            {
                var properties = loggingData.Properties;
                var dict       = new Dictionary <object, object>();

                foreach (var k in properties.Keys.OfType <string>())
                {
                    properties.Add(k, properties[k]);
                }
            }

            if (loggingData.LocationInfo != null)
            {
                var locationInfo = loggingData.LocationInfo;
                var lineNumber   = 0;
                int.TryParse(locationInfo.LineNumber, out lineNumber);
                logEvent.SetStackTrace(new StackTrace(new StackFrame(locationInfo.FileName, lineNumber)), 0);
            }

            LogLevel level;

            if (!s_LevelDict.TryGetValue(loggingData.Level, out level))
            {
                level = LogLevel.Info;
            }

            logEvent.Level = level;

            m_Logger.Log(logEvent);
        }
예제 #10
0
        public void LineNumberNoCaptureStackTraceWithStackTraceTest()
        {
            // Arrange
            LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
        <nlog>
            <targets><target name='debug' type='Debug' layout='${callsite-linenumber:captureStackTrace=false} ${message}' /></targets>
            <rules>
                <logger name='*' minlevel='Debug' writeTo='debug' />
            </rules>
        </nlog>");

            // Act
            var logEvent = new LogEventInfo(LogLevel.Info, null, "msg");

            logEvent.SetStackTrace(new System.Diagnostics.StackTrace(true), 0);
            LogManager.GetLogger("A").Log(logEvent);

            // Assert
            AssertDebugLastMessageContains("debug", " msg");
            Assert.NotEqual(" msg", GetDebugLastMessage("debug"));
        }
예제 #11
0
        public void CallSiteFileNameNoCaptureStackTraceWithStackTraceTest()
        {
            // Arrange
            LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
            <nlog>
                <targets><target name='debug' type='Debug' layout='${callsite-filename:captureStackTrace=False}|${message}' /></targets>
                <rules>
                    <logger name='*' minlevel='Debug' writeTo='debug' />
                </rules>
            </nlog>");

            // Act
            var logEvent = new LogEventInfo(LogLevel.Info, null, "msg");

            logEvent.SetStackTrace(new System.Diagnostics.StackTrace(true), 0);
            LogManager.GetLogger("A").Log(logEvent);

            // Assert
            var lastMessage      = GetDebugLastMessage("debug");
            var lastMessageArray = lastMessage.Split('|');

            Assert.Contains("CallSiteFileNameLayoutTests.cs", lastMessageArray[0]);
            Assert.Equal("msg", lastMessageArray[1]);
        }
 private void ThisNameWillNotApppearinTheCallSite(LogEventInfo logEvt)
 {
     logEvt.SetStackTrace(new StackTrace(1), 0);
 }
예제 #13
0
 /// <summary>
 /// Sets the stack trace for the event info.
 /// </summary>
 /// <param name="stackTrace">The stack trace.</param>
 /// <param name="userStackFrame">Index of the first user stack frame within the stack trace.</param>
 /// <returns>current <see cref="LogBuilder"/> for chaining calls.</returns>
 public LogBuilder StackTrace(StackTrace stackTrace, int userStackFrame)
 {
     _logEvent.SetStackTrace(stackTrace, userStackFrame);
     return(this);
 }
예제 #14
0
 public void CallSiteShouldWorkEvenInlined()
 {
     Type loggerType = typeof(Logger);
     var stacktrace = StackTraceUsageUtils.GetWriteStackTrace(loggerType);
     var index = LoggerImpl.FindCallingMethodOnStackTrace(stacktrace, loggerType);
     var logEvent = new LogEventInfo(LogLevel.Error, "logger1", "message1");
     logEvent.SetStackTrace(stacktrace, index);
     Layout l = "${callsite}";
     var callSite = l.Render(logEvent);
     Assert.Equal("NLog.UnitTests.LayoutRenderers.CallSiteTests.CallSiteShouldWorkEvenInlined", callSite);
 }
예제 #15
0
        public async Task<string> GetAsyncCallSite()
        {
            Type loggerType = typeof(Logger);
            var stacktrace = StackTraceUsageUtils.GetWriteStackTrace(loggerType);
            var index = LoggerImpl.FindCallingMethodOnStackTrace(stacktrace, loggerType);
            var logEvent = new LogEventInfo(LogLevel.Error, "logger1", "message1");
            logEvent.SetStackTrace(stacktrace, index);

            await Task.Delay(0);

            Layout l = "${callsite}";
            var callSite = l.Render(logEvent);
            return callSite;
        }