Get current method name from async function?

后端 未结 8 1279
我在风中等你
我在风中等你 2020-12-04 01:43

Is there anyway to get the current method name from inside an async function?

I\'ve tried:

System.Reflection.MethodInfo.GetCurrentMethod();
         


        
8条回答
  •  旧巷少年郎
    2020-12-04 02:07

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

提交回复
热议问题