4

I was wondering if anyone has seen a demo/example of using the Serilog.Extras.MSOwin package with a web api project or a example/tutorial of using Serilog with a web api project.

Any help greatly appreciated, Jim

Jim Fritchman
  • 563
  • 1
  • 5
  • 6
  • 1
    Questions asking us to recommend or find a book, tool, software library, tutorial or other off-site resource are off-topic for Stack Overflow, as stated in the [help/on-topic]. (See the items in the numbered list on that page.) – Ken White Aug 15 '14 at 15:48

2 Answers2

4

I will take this as question as "How do I used Serilog.Extras.MSOwin?" and given it is currently a rather small library answer here.

This reflects the current library (1.4.102) and is subject to change in the future.

Serilog.Extras.MSOwin provides two things: a Microsoft.Owin.Logging.ILoggerFactory implementation to have OWIN's logging infrastructure write to Serilog (more details about logging in OWIN in this blog post) and Guid identifier (RequestId) for each web request to aid in associating logged events.

The Logging integration is done with the following:

IAppBuilder app = ...;
Serilog.ILogger logger = ...'
app.SetLoggerFactory( new Serilog.Extras.MSOwin.LoggerFactory( logger ) );

The request id functionality needs to be registered in the OWIN pipeline:

IAppBuilder app = ...;
app.UseSerilogRequestContext("RequestId");

You will want to register that very early in the pipeline because any logging occurring before that pipeline step will not have the request id available.

You also need will need to retrieve it from the LogContext using Enrich.FromLogContext() and add that property to what you write to your sinks. For example,

const string DefaultOutputTemplate =
  "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} ({RequestId}) {Message}{NewLine}{Exception}";

ILogger logger =
    new LoggerConfiguration().Enrich.FromLogContext()
        .WriteTo
            .RollingFile(
                "log.txt",
                outputTemplate: DefaultOutputTemplate)
        .CreateLogger();
vossad01
  • 11,552
  • 8
  • 56
  • 109
  • I there a working sample of this somewhere? Preferably just basic ASP.NET MVC? It's unclear to me how the lifecycle works, i.e. how to get an initialized instance of the logger inside a Controller. – Maarten Jan 28 '15 at 16:14
  • I will consider contributing a demo to the Serilog project and will post back here if I do. However, unless you are talking about ASP.NET 5 (MVC 6) I think your are looking in the wrong place so the demo would not answer your question. Current versions of ASP.NET MVC cannot be hosted by OWIN. – vossad01 Jan 28 '15 at 16:48
0

Serilog.Extras.MSOwin was superseded by SerilogWeb.Owin (which has since also been discontinued.)

Ruben Bartelink
  • 59,778
  • 26
  • 187
  • 249