Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serilog with Autofac

I have a logger wrapper and I wanna inject serilog to it with following configurtion perse:

var logger = new LoggerConfiguration()
   .WriteTo.RollingFile(
      AppDomain.CurrentDomain.GetData("DataDirectory").ToString() + "/Log-{Date}.txt")
   .CreateLogger();

I cant seem to find a correct way to register it. I want it as singleton. Above is the instance.

I tried registering the instance above. Didnt work. I tried lambda, didnt work.

What works? anyone?

like image 696
DarthVader Avatar asked Apr 20 '15 18:04

DarthVader


2 Answers

Maybe this helps:

builder.Register<ILogger>((c, p) =>
{
    return new LoggerConfiguration()
      .WriteTo.RollingFile(
        AppDomain.CurrentDomain.GetData("DataDirectory").ToString() + "/Log-{Date}.txt")
      .CreateLogger();
}).SingleInstance();
like image 166
Fka Avatar answered Sep 23 '22 06:09

Fka


I created a nuget-package with an extensions method for AutoFac's ContainerBuilder.

All you need to do is install it and call the extension with either a logger-configuration or a log-path (and optional a template, you get a default).

var builder = new ContainerBuilder();
builder.RegisterSerilog("my-log-path"); // or a loggerconfiguration
var container = builder.Build();
var logger = container.Resolve<ILogger<MyClass>>();
logger.LogInformation("Hello World");

This also works perfectly with ASP.NET-Core. You find samples and the source-code on the github-repository.

like image 28
alsami Avatar answered Sep 19 '22 06:09

alsami