添加日志行,以指示从哪个方法调用日志记录方法

时间:2019-05-23 14:52:58

标签: c# logging methods

我正在将日志添加到我的项目中。日志行显示时间戳+当前方法+当前程序。我确实知道如何检查currentmethod,但这始终是loggingmethod本身。如何找到调用日志记录方法的方法?

附带的编码完全可以满足我的要求。 但是最好在实际的LogMessageToFile方法中添加给出当前方法和项目的部分(this.GetType()。Name + currentMethodName)。

      LOGGER.cs


      using System.IO;

      using System;

      namespace LoggerSpace

      {

      class Logger { 

       public string GetTempPath()

       {
    string path = System.Environment.GetEnvironmentVariable("TEMP");
    if (!path.EndsWith("\\")) path += "\\";
    return path;

}

public void LogMessageToFile(string msg)
{
    System.IO.StreamWriter sw = System.IO.File.AppendText(
        GetTempPath() + "My Log File.txt");

        Console.Write(GetTempPath());
        try
    {
        string logLine = System.String.Format(
            "{0:G}: {1}.", System.DateTime.Now, msg);
        sw.WriteLine(logLine);
    }
    finally
    {
        sw.Close();
    }
}

      }

      }







      CODEwithADDEDlogging.cs

      using LoggerSpace;

      using System.Diagnostics;


      private void button2_Click(object sender, EventArgs y)
    {


        //LOG PART 
        var st = new StackTrace();
        var sf = st.GetFrame(0);
        var currentMethodName = sf.GetMethod();


        var instance = new Logger();
        instance.LogMessageToFile("Button Clicked, Clicktrader, from:"+ this.GetType().Name+ currentMethodName);


    }

2 个答案:

答案 0 :(得分:1)

为此使用CallerMemberNameAttribute。像这样:

void LogSomething(string message, [CallerMemberName]string caller="")
{
    // caller will have the function or property name of the caller to LogSomething
}

您还可以获取源文件名和行号以及其他属性,所有这些都在链接中进行了描述。

答案 1 :(得分:0)

    public void LogMessageToFile(string msg,
        [CallerMemberName]string propertyName = null
        [CallerFilePath] string sourceFilePath = ""
        [CallerLineNumber] int sourceLineNumber = 0)
    {
    }

让您捕获调用函数,被调用的文件以及该文件中的行号。