How to get the method name for logging purpose?

Ashutosh Pareek 26 Reputation points
2021-03-03T08:23:38.247+00:00

I have integrated Serilog for ILogger interface. I did not not find any Enricher which could enrich my message with MethodName who is actually logging the message.
One solution was present at : https://gist.github.com/nblumhardt/0e1e22f50fe79de60ad257f77653c813

But unfortunately this doesn't work for async methods as it logs MoveNext and other methods from statemachine, after putting conditions for these specific method, It was not working with middleware pipeline.

public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
    {
        var skip = 3;
        while (true)
        {
            var stack = new StackFrame(skip);
            if (!stack.HasMethod())
            {
                logEvent.AddPropertyIfAbsent(new LogEventProperty("Caller", new ScalarValue("<unknown method>")));
                return;
            }
            var method = stack.GetMethod();
            if (method.DeclaringType.Assembly != typeof(Log).Assembly)
            {
                var caller = $"{method.DeclaringType.FullName}.{method.Name}({string.Join(", ", method.GetParameters().Select(pi => pi.ParameterType.FullName))})";
                logEvent.AddPropertyIfAbsent(new LogEventProperty("Caller", new ScalarValue(caller)));
                return;
            }
            skip++;
        }
    }

Question : Did anyone else has developed a solution for this problem which they can share? Help is very much appriciated.

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,535 questions
{count} votes