记录和行号 [英] Logging and line numbers

查看:82
本文介绍了记录和行号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种方法来确定登录的行号.我知道我可以通过带有异常的堆栈跟踪来做到这一点,但是我们有许多级别的日志记录,并且大多数级别与异常无关.有人知道我要报告什么的方法吗 一条消息是来自而没有对它们进行硬编码的?

I am looking for a way to determine what line number something was logged on. I know I can do it via a stack trace with an exception, but we have many levels of logging and most are not exception related. Is anyone aware of a way for my to report what line a message is coming from without hardcoding the them?

谢谢

推荐答案

您可以在运行时从被调用的文件上方的堆栈跟踪和堆栈框架中获取文件和行号.

You can get the file and line number at run-time from the stack trace and stack frame above the one that is called.

示例:

using System.Diagnostics;

class Program
{
    static void Log( string msg )
    {
        StackFrame stackFrame = new StackTrace( new StackFrame( 1, true ) ).GetFrame( 0 );
        Debug.WriteLine( "{0}({1}): {2}", stackFrame.GetFileName(), stackFrame.GetFileLineNumber(), msg );
    }

    static void Main( string[] args )
    {
        Log( "hello" );
    }
}

我还使用了Visual Studio首选的输出格式,因此您可以双击输出窗口中的日志消息,它将带您到该行代码.  魔术!

I also used the output format that Visual Studio prefers so you can double click on the log message in the output window and it will take you to that line of code.  Magic!

另一种实现方法是使用CallerInformation.  这样做可以说是更好的方法,因为它是在编译时完成的,而不是在运行时完成的,只要这样就可以方便地将您的参数放在最后.

Another way of doing it is with CallerInformation.  This is arguably better because it's done at compile time, rather than at run time, provided it's convenient to have your arguments at the end like that.

示例:

using System.Diagnostics;
using System.Runtime.CompilerServices;

class Program
{
    static void Log( string msg,
        [CallerFilePath] string filePath = "",
        [CallerLineNumber] int lineNumber = 0 )
    {
        Debug.WriteLine( "{0}({1}): {2}", filePath, lineNumber, msg );
    }

    static void Main( string[] args )
    {
        Log( "hello" );
    }
}


这篇关于记录和行号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆