asp.net-corehttprequest

Log RequestId in asp.net core


I manage a service displaying "user-friendly" error to my beloved users. If they get an error, usually they call support and mention the RequestId. I get this request id using the code below:

public string RequestId => Activity.Current?.Id ?? HttpContext.TraceIdentifier;

Now the interesting thing is ... we display the id to the user but we do not keep it in our logs :).

Currently we send all the logs to Cloudwatch using this code

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
       (...)
       loggerFactory.AddAWSProvider(
            Configuration.GetAWSLoggingConfigSection("Cloudwatch"),
            (l, obj, ex) =>
            {
                var level = "info";
                if (l == LogLevel.Error || l == LogLevel.Critical) level = "error";
                else if (l == LogLevel.Warning) level = "warn";
                return JsonConvert.SerializeObject(new
                {
                    level,
                    msg = ex?.Message ?? obj.ToString(),
                    meta = ex?.ToString()
                });
            });

        (...)
    }

I have some trouble finding a good way to send the HttpRequest all the way down this lambda so I can consistently log the Id.

How would you handle that?

Thank you, Seb


Solution

  • Can you try:

    public class Startup
    {
        ...
        public void ConfigureServices(IServiceCollection services)
        {
            ...
            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
            ...
        }
    
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, 
            ILoggerFactory loggerFactory, IHttpContextAccessor httpContextAccessor)
        {
            ...
    
            var httpContext = httpContextAccessor.HttpContext;
            var user = httpContext.User;
    
            ...
        }
    }
    

    Let me know if this is working or not, because I have no way to set up the same environment you have so I have no way to test the code before I post.

    Update:

    Just like what @Tseng said: the above code is not right, and httpContextAccessor will be always NULL. I wanted to delete the post but since it's marked as accepted, I couldn't.