How to log stack trace using log4net (C#)

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-28 03:04:38

问题


How to log stack trace with log4net? I am using .Net version.

They way I have is Log.Error(ex).

Thanks


回答1:


Use this:

void Error(object message,Exception t)

Reason is in log4net documentation for void Error(object message):

WARNING Note that passing an Exception to this method will print the name of the Exception but no stack trace. To print a stack trace use the void Error(object,Exception) form instead.

Error(object message, Exception t) is the most flexible way to log exception data because it goes as an Exception rather than Object and that can be used in appenders to narrow logs to a particular exception class (rather than by searching for a string which is much slower and less consistent)

There are special versions of all non-format logging methods that take message and exception:

namespace log4net
{
    public interface ILog
    {
        ...
        /* Log a message object and exception */
        void Debug(object message, Exception t);
        void Info(object message, Exception t);
        void Warn(object message, Exception t);
        void Error(object message, Exception t);
        void Fatal(object message, Exception t);
        ...
    }
}



回答2:


You need to ensure that the definition of the layout pattern is structured to output what format and data you want.

log4Net Pattern Layout

Used to output the stack trace of the logging event The stack trace level specifier may be enclosed between braces. For example, %stacktrace{level}. If no stack trace level specifier is given then 1 is assumed

Output uses the format: type3.MethodCall3 > type2.MethodCall2 > type1.MethodCall1

This pattern is not available for Compact Framework assemblies.




回答3:


There are two basic forms, one that takes an object and an exception explicitly:

catch(Exception ex)
{
    // the form that takes two args has an exception as second, prints trace...
    _log.Error("My custom message", ex);
}

And one that takes any object and performs a ToString() on it:

catch(Exception ex)
{
    // the form that takes one arg uses ToString()
    _log.Error(ex);
}

The former allows you to attach a more meaningful message on the log entry first to give any additional detail you'd like. The latter will do the job but only prints the exception details using ToString(), which gives you:

The default implementation of ToString obtains the name of the class that threw the current exception, the message, the result of calling ToString on the inner exception, and the result of calling Environment.StackTrace. If any of these members is Nothing, its value is not included in the returned string.




回答4:


You can extend the ILog to have a method that logs just an exception with his stack trace.

public static void ErrorWithStackTrace(this ILog log, Exception exception)
 {
    log.Error(exception.Message,exception);
   }



回答5:


public static Logger SetIfNeededAndGetLogger(string serviceName, string methodName)
{
    Logger logger = null;

    try
    {
        if (!string.IsNullOrWhiteSpace(serviceName) && !string.IsNullOrWhiteSpace(methodName))
        {
            ILog log = null;
            var traceSourceName = string.Format("{0}{1}", serviceName, methodName);
            if (!string.IsNullOrWhiteSpace(traceSourceName))
            {
                logger = LogSources.FirstOrDefault(x => x.ServiceLogType == traceSourceName);
                if (logger == null)
                {
                    log = LogManager.GetLogger(traceSourceName);
                    //logger = new Logger(log, IHEService.MediLogClientGuid, traceSourceName, methodName);
                    logger = new Logger(log, System.Guid.NewGuid(), traceSourceName, methodName);
                    SetLoggingSource(logger);
                }
            }
        }
    }
    catch (Exception)
    {
        //silent faiure
    }

    return logger;
}

private static void SetLoggingSource(Logger value)
{
    LogSources.Add(value);
}


来源:https://stackoverflow.com/questions/9319810/how-to-log-stack-trace-using-log4net-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!