将调用NUnit测试添加到NLog输出

将调用NUnit测试添加到NLog输出,nunit,nlog,Nunit,Nlog,我正在通过NUnit运行测试,希望NLog消息能够快速告诉我每个日志消息上的调用测试。差不多 <target xsi:type="File" layout="${longdate} ${someMagic} ${message}" /> 有没有一种不深入NLog代码的简单方法呢?这里有一个有效的解决方案:一组扩展方法包装NLogILogger.Error(…)方法等,在堆栈中查找NUnit[Test]或[TestCase]属性

我正在通过NUnit运行测试,希望NLog消息能够快速告诉我每个日志消息上的调用测试。差不多

<target xsi:type="File" 
          layout="${longdate} ${someMagic} ${message}"
          />


有没有一种不深入NLog代码的简单方法呢?

这里有一个有效的解决方案:一组扩展方法包装NLog
ILogger.Error(…)
方法等,在堆栈中查找NUnit
[Test]
[TestCase]
属性

    public static void XError(this ILogger log, String message)
    {
        if (log.IsErrorEnabled == false)
            return;

        var prefix = GetCallerTestDescription();
        log.Error("[{0}] {1}", prefix, message);
    }

    private static string GetCallerTestDescription()
    {
        var stack = new StackTrace(false).GetFrames();

        if (stack != null)
        {
            foreach (var frame in stack)
            {
                var method = frame.GetMethod();
                var testAttributes = method.GetCustomAttributes<TestAttribute>();

                if (testAttributes != null && testAttributes.Any())
                {
                    return method.Name;
                }

                var tcAttributes = method.GetCustomAttributes<TestCaseAttribute>();
                if (tcAttributes != null && tcAttributes.Any())
                {
                    return method.Name;
                }

            }
        }
publicstaticvoidxerror(此ILogger日志,字符串消息)
{
如果(log.IsErrorEnabled==false)
返回;
var prefix=GetCallerTestDescription();
错误(“[{0}]{1}”,前缀,消息);
}
私有静态字符串GetCallerTestDescription()
{
var stack=new StackTrace(false).GetFrames();
如果(堆栈!=null)
{
foreach(堆栈中的var帧)
{
var method=frame.GetMethod();
var testAttributes=method.GetCustomAttributes();
if(testAttributes!=null&&testAttributes.Any())
{
返回方法.Name;
}
var tcAttributes=method.GetCustomAttributes();
if(tcAttributes!=null&&tcAttributes.Any())
{
返回方法.Name;
}
}
}