Skip to content

Transfer request for an ScopedLogContext enriched and a HttpRequestLogContext #7

@MonticolaExplorator

Description

@MonticolaExplorator

Hello everyone,

I have created two enrichers that I would like to transfer, if you see any value on them. First one is an HttpRequestLogContext enricher. It is an enricher intented to be used in ASP.NET Core projects, in order to have a convenient way to have properties scoped to the current http request. This way, for instance, you can push a property in the controller, and have it logged when ASP.NET Core logs the request time.

[HttpGet]
public WeatherForecast Get(string location)
{
    var forecast = new WeatherForecast
    {
        Date = DateTime.Now.AddDays(1),
        TemperatureC = Random.Shared.Next(-20, 55),
        Summary = Summaries[Random.Shared.Next(Summaries.Length)]
    };
    HttpRequestLogContext.PushProperty("Location", location);
    HttpRequestLogContext.PushProperty("PredictedTemp", forecast.TemperatureC);

    _logger.LogInformation("Returning weather forecast");

    if (forecast.TemperatureC < -10)
        throw new Exception("It's going to be freezing cold!");

    return forecast;
}

I have also created an ScopedLogContext enricher, which is like the normal LogContext, except that it is not static and it can be disposed. This was my first attempt to solve the problem of the scope of the properties on an ASP.NET Core project, but it does not work for this purpose.

using(var scopedLogContext = new ScopedLogContext())
{
    scopedLogContext.PushProperty("A", 1);

    Log.Information("Carries property A = 1");

    scopedLogContext.PushProperty("A", 2);
    scopedLogContext.PushProperty("B", 1);
    
    Log.Information("Carries A = 2 and B = 1");
}

Log.Information("Carries no properties");

I did this for fun, and I would also be happy to collaborate on this project. If you find any of these insteresting, let me know and I will gladly transfer them to this repo.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions