0

I am adding logs to my projects. The logline shows timestamp + current method + current program. I do know how to check currentmethod, but this will always be the loggingmethod itself. How do I find the method that called for the logging method?

The coded attached is doing exactly what I want. But it would be nice to add the part that gives the current method and project (this.GetType().Name+ currentMethodName) in the actual LogMessageToFile method.

      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);


    }
Cindy88
  • 123
  • 1
  • 3
  • This worked: https://stackoverflow.com/questions/171970/how-can-i-find-the-method-that-called-the-current-method – Cindy88 May 23 '19 at 15:02

2 Answers2

1

Use the CallerMemberNameAttribute for this. Something like this:

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

You can also get the source file name and line number with other attributes, all described in the link.

zmbq
  • 38,013
  • 14
  • 101
  • 171
0
    public void LogMessageToFile(string msg,
        [CallerMemberName]string propertyName = null
        [CallerFilePath] string sourceFilePath = ""
        [CallerLineNumber] int sourceLineNumber = 0)
    {
    }

lets you catch the calling function, the file it was called from and the line number within that file.

Steve Todd
  • 1,250
  • 6
  • 13