Is there anyway to get the current method name from inside an async function?
I\'ve tried:
System.Reflection.MethodInfo.GetCurrentMethod();
>
I came across the same issue recently for my log message and the answers here helped. I am sharing my code in case it can help others with their questions.
using System.Runtime.CompilerServices;
namespace Foo.Services
{
public interface ILogFormatter
{
public string FormatMessage(LogType logType, string details, [CallerMemberName] string caller = "");
}
public enum LogType
{
Debug,
Information,
Warning,
Error
}
public class LogFormatterOptions
{
public string Subject { get; set; }
}
public class LogFormatter : ILogFormatter
{
public LogFormatter(LogFormatterOptions options)
{
Subject = options.Subject;
}
public string Subject { get; set; }
public string FormatMessage(LogType logType, string details, [CallerMemberName] string caller = "")
{
return $"{Subject} - {logType}: caller: {caller} - {details}";
}
}
}
This is how this method is called and it works for both async and synchronized methods. Note that I am not passing value for the caller input & it picks up the caller method name.
logger.LogInformation(logFormatter.FormatMessage(LogType.Information, ""));