Log Calling Method

A common task when writing an application is to capture diagnostics and logging information. One of the pieces of information to capture is the method name that is being logged. Rather than pass the method name in when logging you can use methods from System.Diagnostics to automatically populate that information.

System.Diagnostics

This namespace provides access to system processes, event logs and performance counters. In order to get the calling method we will be using the following objects

  • StackTrace
  • StackFrame

StackTrace

The StackTrace class is an ordered collection of StackFrames. The collection is indexed from zero, where zero represent the current StackFrame. Every time a new method is called a StackFrame is created on the stack.

StackFrame

The StackFrame contains diagnostic information about the code that is currently executed. Below are some of the methods that you can call on the StackFrame:

  • GetFileColumnNumber - returns the file column number
  • GetFileLineNumber - returns the file line number
  • GetFileName - returns the file name
  • GetMethod - returns the method name of the frame

Get Calling Function

The method below takes a message as a string and then logs to the console the time and calling method name. It does this by

  • Creating an instance of the StackTrace class.
  • Getting the 2nd frame in the StackFrames collection. The first place is the current method (Log)
  • Finally calling GetMethod on the StackFrame and then accessing the Name property
using System;
using System.Diagnostics;

void Log(string message)
{
	var stackTrace = new StackTrace();
	var caller = stackTrace.GetFrame(1).GetMethod().Name;
	Console.WriteLine($"{DateTime.Now:dd/MM/yyyy hh:mm:ss} {caller} : {message}");
}

Running the Code

This script below is run using LINQPad. It calls the Log method from the main method and then via another method to show the capture of the calling method name. The output will look like :

  • 07/06/2020 10:34:00 Main : Called from Main
  • 07/06/2020 10:34:00 AnotherMethod : Called from another method
using System;
using System.Diagnostics;

void Main()
{
	Log("Called from Main");
	AnotherMethod();
}

void AnotherMethod()=> Log("Called from another method");

void Log(string message)
{
	var stackTrace = new StackTrace();
	var caller = stackTrace.GetFrame(1).GetMethod().Name;
	Console.WriteLine($"{DateTime.Now:dd/MM/yyyy hh:mm:ss} {caller} : {message}");
}