Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using log4net with WebApi - Keeping same correlation id throughout instance

I have a LoggingHandler class that I'm using as a message handler to log (using log4net) request and responses to my WebApi

public class LoggingMessageHandler : DelegatingHandler
{
    public ILogManager LogManager { get; set; }

    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
    {
        var controllerType = GlobalConfiguration.Configuration.Services
            .GetHttpControllerSelector()
            .SelectController(request)
            .ControllerType;

        var requestInfo = string.Format("{0} {1}", request.Method, request.RequestUri);
        var correlationId = request.GetCorrelationId().ToString();

        var requestMessage = await request.Content.ReadAsStringAsync();

        await LogIncommingMessageAsync(controllerType, correlationId, requestInfo, requestMessage.Replace("\r\n", ""));

        var response = await base.SendAsync(request, cancellationToken);

        string responseMessage;

        if (response.IsSuccessStatusCode)
            responseMessage = await response.Content.ReadAsStringAsync();
        else
            responseMessage = response.ReasonPhrase;

        await OutgoingMessageAsync(controllerType, correlationId, requestInfo, responseMessage);

        return response;
    }

    protected async Task LogIncommingMessageAsync(Type type, string correlationId, string requestInfo, string body)
    {
        var logger = LogManager.GetLogger(type);
        await Task.Run(() => logger.Debug("{0} {1} - API Request: \r\n{2}", correlationId, requestInfo, body));
    }

    protected async Task OutgoingMessageAsync(Type type, string correlationId, string requestInfo, string body)
    {
        var logger = LogManager.GetLogger(type);
        await Task.Run(() => logger.Debug("{0} {1} - API Response: \r\n{2}", correlationId, requestInfo, body));
    }
}

ILogManager is injected via Autofac (see our Autofac module further down)

My issue is with a correlation id;

How can this be passed further down into our app?

For example, in another assembly, containing some of our business logic, we want to use a call to LogManager.GetLogger to get a log for another type, but since it originated at the request, re-use the same correlation Id, so we can tie our log messages together?

For clarity, our Autofac module looks like this:

public class LoggingAutofacModule : Autofac.Module
{
    protected override void Load(ContainerBuilder builder)
    {
        builder.RegisterType<LogManager>().As<ILogManager>().InstancePerApiRequest();
    }

    protected override void AttachToComponentRegistration(IComponentRegistry registry, IComponentRegistration registration)
    {
        registration.Preparing += OnComponentPreparing;

        var implementationType = registration.Activator.LimitType;
        var injectors = BuildInjectors(implementationType).ToArray();

        if (!injectors.Any())
            return;

        registration.Activated += (s, e) =>
        {
            foreach (var injector in injectors)
                injector(e.Context, e.Instance);
        };
    }

    private static void OnComponentPreparing(object sender, PreparingEventArgs e)
    {
        var t = e.Component.Activator.LimitType;
        e.Parameters =
            e.Parameters.Union(new[] { new ResolvedParameter((p, i) => p.ParameterType == typeof(ILogger), (p, i) => e.Context.Resolve<ILogManager>().GetLogger(t)) });
    }

    private static IEnumerable<Action<IComponentContext, object>> BuildInjectors(Type componentType)
    {
        var properties =
            componentType.GetProperties(BindingFlags.SetProperty | BindingFlags.Public | BindingFlags.Instance)
                         .Where(p => p.PropertyType == typeof(ILogger) && !p.GetIndexParameters().Any())
                         .Where(p =>
                         {
                             var accessors = p.GetAccessors(false);
                             return accessors.Length != -1 || accessors[0].ReturnType == typeof(void);
                         });

        foreach (var propertyInfo in properties)
        {
            var propInfo = propertyInfo;
            yield return (context, instance) => propInfo.SetValue(instance, context.Resolve<ILogManager>().GetLogger(componentType), null);
        }
    }
}
like image 595
Alex Avatar asked Jan 24 '14 13:01

Alex


1 Answers

The easiest way is to just add it to the properties for the log4net logical thread context:

LogicalThreadContext.Properties["CorrelationId"] = request.GetCorrelationId();

Note that since this is a logical thread context, it will persist across await points, even if a different thread is used to resume the request.

like image 158
Stephen Cleary Avatar answered Oct 18 '22 16:10

Stephen Cleary