Git Product home page Git Product logo

serilog-enrichers-aspnetcore-httpcontext's Introduction

serilog-enrichers-aspnetcore-httpcontext · NuGet PRs Welcome GitHub license

Enriches Serilog events with Aspnetcore HttpContext. By default logs all information about the Http Request. Provides access to log whatever you want from the HttpContext, including Session, Cookies, Request, Connection, User - basically anything from the HttpContext object.

Installation

Install-Package Serilog.Enrichers.AspnetcoreHttpcontext

Usage example

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>()
                .UseSerilog((provider, context, loggerConfiguration) =>
                {
                    loggerConfiguration.MinimumLevel.Debug()
                        .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
                        .Enrich.WithAspnetcoreHttpcontext(provider)
                        .WriteTo.Console(
                            outputTemplate:
                            "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj} {NewLine}{HttpContext}")
                        .WriteTo.Elasticsearch(new ElasticsearchSinkOptions(new Uri("http://localhost:9200"))
                        {
                            IndexFormat = "serilog-enrichers-aspnetcore-httpcontext-{0:yyyy.MM}"
                        });
                });

You'll have enriched log event like pictures listed bellow

alt text

alt text

The Basics

Move LoggerConfiguration to the UseSerilog method

The reason for this move is becuase within ASP.NET Core the HttpContext is only available after the dependency injection engine is established. The LogggerConfiguration setup is the same as you would do elsewhere, just the location has moved.

Use the WithAspnetcoreHttpcontext extension method

Using the method as shown above (with only the providers parameter passed) will use the default enrichment method. It will format the HttpContextCache object from this project, which contains mostly information from the Request object of the HttpContext.

Provide your own method that returns what you want from HttpContext

If you want different items from the HttpContext in your log entries, you can provide your own method to do this. A full working example can be seen in the samples folder.

You provide a second argument to the WithAspnetcoreHttpcontext method, which is the name of a method with a signature like this:

SomeClassYouDefine WhateverNameYouWant(IHttpConextAccessor hca)

SomeClassYouDefine is a simple class that you would create that contains properties for the information from the HttpContext you want in the log entry. Then inside the method you "new up" the class into an actual object, and use the hca parameter's HttpContext property to fill your object with whatever you want and then return the object.

Here's the example from the samples folder:

...
            .Enrich.WithAspnetcoreHttpcontext(provider,
                            customMethod: CustomEnricherLogic)
...

private static MyObject CustomEnricherLogic(IHttpContextAccessor ctx)
{
    var context = ctx.HttpContext;
    if (context == null) return null;
    
    var myInfo = new MyObject
    {
        Path = context.Request.Path.ToString(),
        Host = context.Request.Host.ToString(),
        Method = context.Request.Method
    };

    var user = context.User;
    if (user != null && user.Identity != null && user.Identity.IsAuthenticated)
    {
        myInfo.UserClaims = user.Claims.Select(a => new KeyValuePair<string, string>(a.Type, a.Value)).ToList();
    }
    return myInfo;
}

public class MyObject
{
    public string Path { get; set; }
    public string Host { get; set; }
    public string Method { get; set; }

    public List<KeyValuePair<string, string>> UserClaims { get; set; }
}

Format (or don't) your log entries

Either the standard HttpContextCache class or your own custom class will be added to the log entry as the HttpContext property. You can use this in your custom formatting logic or just leave it to the built-in formatters to handle.

Contributing

  1. Fork it
  2. Create your feature branch (git checkout -b feature/fooBar)
  3. Commit your changes (git commit -am 'Add some fooBar')
  4. Push to the branch (git push origin feature/fooBar)
  5. Create a new Pull Request

serilog-enrichers-aspnetcore-httpcontext's People

Contributors

trenoncourt avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

serilog-enrichers-aspnetcore-httpcontext's Issues

Only include at certain log levels

This extension is the best I've found so far for logging httpContext in .net core. I couldn't get the others to work correctly.

Is there a way to only include the httpContext at certain log levels?
I'm concerned performance may be an issue if the properties are being added for every event level.

Capturing the response

Right now the enricher captures the request in the property "body" which is the request body how about adding the response body as well? any thoughts?

context.Response.OnStarting(state =>
{
var httpContext = (HttpContext)state;
//something like the below capture and store the body
// httpContext.Response.Body
return Task.CompletedTask;
}, context);

Whats the difference between this and the built in Serilog AspNetCore function?

In serilog.aspnetcore nuget package you can do this:

app.UseSerilogRequestLogging(options =>
{
	options.EnrichDiagnosticContext = (diagnosticContext, httpContext) =>
	{
		diagnosticContext.Set("UserAgent", httpContext.Request.Headers["User-Agent"].ToString());
		diagnosticContext.Set("HttpRequestClientHostIP", httpContext.Connection.RemoteIpAddress);
		diagnosticContext.Set("HttpRequestUrl", httpContext.Request.GetDisplayUrl());
		diagnosticContext.Set("UserName", httpContext.User.Identity.Name == null ? "(anonymous)" : httpContext.User.Identity.Name);
	};
});

And the logs for HTTP requests/responses will have that extra information in it.

What does this nuget do in addition?

cause 404 error if Loging happened from background thread.

as this nuget uses HttpContextAccessor to get the http context properties, it cause 404 to next incoming request as the http-method becomes empty string.
please see aspnet/KestrelHttpServer#2591 for more details.

So instead of getting the properties at logging time it would be good idea to set the properties to LogContext in a middle ware so that HttpContextAccessor wont be accessed from a background thread.

Sink MSSqlServer

I was able to write to the console, but when I modified to write the log in MSSqlServer nothing appeared.
I think it has to do with outputTemplate, right?
Is there any documentation on how to use it to write to MSSqlServer?

LoggerConfiguration in the UseSerilog method

When I moved the LoggerConfiguration to the UseSerilog method I was unable to log the start and end time of the host, in Program.cs, Log in this file no longer work, is there a way to fix this?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.