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

Add calling NUnit test to NLog output

我正在 运行 通过 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;
                }

            }
        }