当我在我的PatternLayout中使用%l或%L进行调试时,我会得到扩展静态类的位置和文件中的行号,而不是调用者的位置和行。任何一种标准的日志记录方法都会产生正确的结果。有什么方法可以让扩展方法来做到这一点吗?
我的Log4NetExtensions.cs的一部分
namespace Dashboard
{
public static partial class Util
{
public static void SqlError(this ILog log, SqlException sqle)
{
if (log.IsDebugEnabled)
{
string[] names = Enum.GetNames(typeof(Dashboard.Models.Response.DashError.StandardErrors));
int idx = Array.IndexOf(names, sqle.Message);
if (idx > 0)
{
log.Debug(sqle.Message);
}
else
{
log.Error(sqle);
}
}
else
{
log.Error(sqle);
}
}
}
}编辑:在wageoghe的回答中,我将log.Error()和log.Debug更改为以下内容,但它仍然打印Util,而不是调用者:
log.Logger.Log(typeof(Util), Level.Error, sqle.Message, sqle);发布于 2014-03-07 18:28:39
关于如何在包装log4net时维护呼叫站点信息,请参见这里对另一个问题的回答。
how to log method name when using wrapper class with Log4net
尽管您正在编写扩展方法,但实际上您正在包装log4net。这个答案中描述的技术应该适用于扩展方法,也可以用于包装器。您的解决方案应该是在包装器中使用Log方法而不是Info、Error等。作为Log方法的第一个参数,发送扩展方法静态类的类型。
您的扩展方法将如下所示(未编译或测试):
namespace Dashboard
{
public static partial class Util
{
public static void SqlError(this ILog log, SqlException sqle)
{
if (log.IsDebugEnabled)
{
string[] names = Enum.GetNames(typeof(Dashboard.Models.Response.DashError.StandardErrors));
int idx = Array.IndexOf(names, sqle.Message);
if (idx > 0)
{
//Note that I am using the Logger member and then calling the Log method it.
log.Logger.Log(typeof(Util), LogLevel.Debug, sqle.Message, null);
}
else
{
//Not sure about this call because you want to log only the exception. Don't
//know if log4net will accept null as "message" parameter.
log.Logger.Log(typeof(Util), LogLevel.Error, null, sqle);
}
}
else
{
//Not sure about this call because you want to log only the exception. Don't
//know if log4net will accept null as "message" parameter.
log.Logger.Log(typeof(Util), LogLevel.Error, null, sqle);
}
}
}
}如果不完全正确的话,我想你会明白的。
更新
FWIW,我将这个小示例放在一起,它使用扩展方法记录调用站点所需的方法(Main):
class Program
{
static void Main(string[] args)
{
var logger = LogManager.GetLogger("abc");
ILogger ilog = logger.Logger;
logger.Info("Hello");
logger.InfoExt("Hello2");
}
}
public static class Extensions
{
public static void InfoExt(this ILog logger, string message)
{
logger.Logger.Log(typeof(Extensions), Level.Info, message, null);
}
}https://stackoverflow.com/questions/22255890
复制相似问题