I've been using Serilog inside a .net core webapi project and am able to happily use it. However, an example I want to include in the information log the method name - accessing the class name is ok using SourceContext.
However, following various suggestions / guides online I added an enricher but the result each time is the actual Enrich method.
To summarize my knowledge, I've come from a primarily .net 3.5 and below background so everything beyond this is a very steep learning curve at the moment. Please be gentle :-)
I have tried both:
logEvent.AddOrUpdateProperty(new LogEventProperty("MethodName", new ScalarValue(System.Reflection.MethodBase.GetCurrentMethod().Name)));
and
logEvent.AddOrUpdateProperty(new LogEventProperty("MethodName", new ScalarValue(GetActualAsyncMethodName())));
In the end I have fixed this by adding an action filter and adding a property to the LogContext for Serilog as follows:
public class LoggingPropertiesFilter : IActionFilter
{
public void OnActionExecuting(ActionExecutingContext context)
{
// Do something before the action executes.
ControllerBase controllerBase = context.Controller as ControllerBase;
if(controllerBase != null)
{
var routeAction = controllerBase.RouteData.Values["action"];
LogContext.PushProperty("method", routeAction);
}
}
public void OnActionExecuted(ActionExecutedContext context)
{
// Do something after the action executes.
}
}
The only issue I have with this so far is that I have to manually attach an attribute to each action for this to work, but this does solve the initial problem I had if it's any use to anyone.