Git Product home page Git Product logo

nancy.serilog's Introduction

Nancy.Serilog Build Status Nuget

Nancy plugin for application-wide logging using the Serilog logging framework.

Available Packages:

Package Nancy Version
Nancy.Serilog 2.0+ (dotnet core stable) Nuget

Getting Started

Install it from Nuget:

# Dotnet core
dotnet add package Nancy.Serilog

Enable logging from your Bootstrapper at ApplicationStartup, this block is a good place to configure the actual logger.

using Nancy.Serilog;
// ...
class CustomBootstrapper : DefaultNancyBootstrapper
{
    protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines)
    {
        pipelines.EnableSerilog();

        // Configure logger to output json-formatted logs to the console
        // or use the sink of your choice 
        Log.Logger = new LoggerConfiguration()
           .MinimumLevel.Information()
           .WriteTo.Console(new JsonFormatter())
           .CreateLogger()
    }
    
    protected override void ConfigureRequestContainer(TinyIoCContainer container, NancyContext context)
    {
        // Register request based dependency
        container.Register((tinyIoc, namedParams) => context.GetContextualLogger());
        
        // other dependencies using ILogger should be registered here as well
        container.Register<IThirdPartyService, ThirdPartyService>(); 
    }
    
    
}

Now data from your requests will be logged when receiving requests and when returing responses:

public class Index : NancyModule
{
    public Index()
    {
        Get("/", args => "Hello From Home");
    }
}

Without doing any extra configuration, navigating to / (root) will be logged: In the following screenshot I am using a self-hosted Nancy app (the sample of this repo) with some ignored fields.

console

Log Correlation

Notice how the two logs are correlated with the same RequestId property. This property is attached to requests and responses so that you can find logs coming from a single roundtrip. When you write custom log messages, you want to include this RequestId property to your custom logs so that these too will be correlated to the same requests and responses. To do that, you want to use a logger that is bound to the request context: Nancy.Serilog provides an extension method called GetContexualLogger() you can register as the request container level from your Bootstrapper as in the following snippet.

using Nancy;
using Serilog;

public class Users : NancyModule
{
    // have ILogger as a dependency
    public Users(ILogger logger)
    {
        Post("/hello/{user}", args =>
        {
            var user = (string)args.user;
            logger.Information("{User} Logged In", user);
            return $"Hello {user}";
        };
    }
}

public class Bootstrapper : DefaultNancyBootstrapper
{
    protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines)
    {
        pipelines.EnableSerilog();
        StaticConfiguration.DisableErrorTraces = false;
    }
    
    protected override void ConfigureRequestContainer(TinyIoCContainer container, NancyContext context)
    {
        // Register request based dependency
        container.Register((tinyIoc, namedParams) => context.GetContextualLogger());
        
        // other dependencies using ILogger should be registered here as well
        container.Register<IThirdPartyService, ThirdPartyService>(); 
    }
}

Then POSTing some data from Postman will give us the following (using Seq to browse log data), see how the second log message also has RequestId:

post

Ignoring Fields

Nancy.Serilog will try to retrieve all the information it can get from requests, responses and errors. However, you can still tell the library what fields to ignore fluently from the logs, it goes like this:

class CustomBootstrapper : DefaultNancyBootstrapper
{
    protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines)
    {
        pipelines.EnableSerilog(new NancySerilogOptions
        {
            IgnoredResponseLogFields = 
                Ignore.FromResponse()
                      .Field(res => res.RawResponseCookies)
                      .Field(res => res.ReponseHeaders)
                      .Field(res => res.ResponseCookies),
            IgnoredRequestLogFields = 
                Ignore.FromRequest()
                      .Field(req => req.Method)
                      .Field(req => req.RequestHeaders),
            IgnoredErrorLogFields = 
                Ignore.FromError() 
                      .Field(error => error.ResolvedRouteParameters)
                      .Field(error => error.StatusCode)
        });
    }
}

nancy.serilog's People

Contributors

zaid-ajaj avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

nancy.serilog's Issues

Cannot access a closed file

Sending a very long request as body in json format results in the same error #2 did. Following your advice there i ignored the contentbody as a hack to avoid the error. Tell me how o what can i do to help you.

Regards

Port to .NET Core

Preferably by linking the same source files into a netstandard2.0 based project and building/publishing from there

Feature Request: Update to Nancy Version 2.0.

Greetings, since Nancy threw a newer version of their lib, could we get an updated version targeting Nancy 2.0?

Perhaps move Nancy.Serilog lib to depend on Nancy 2.0 and deprecate Nancy.Serilog.Core?

Any feedback would be appreciated, also i could help with PR if necessary.

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.