NLog.Extensions.Logging and a custom inherited logger

80 Views Asked by At

I am elaborating with a custom NLog logger, let's call it MyLogger class. It has own Trace(), Debug(), Info(), .. methods. I would like to use a classic NLog.config file and if possible register manually also some own custom Layout renderers. Is it possible to do an initial setup in a POC consumer application or somehow extend the NLog.Extensions.Logging to use MyLogger?

Or if unfortunately not, I would like to try to elaborate with a compromise - I mean at least to somehow share the NLog.config between NLog logger bound to the MS logging infrastructure and the MyLogger used in some of my own services. What would a possible setup then look like?

(updated) to add more details:

  • MyLogger class has very similar implementation to the one from the NLog extending loggers example

  • I have also added IMyLogger interface wit the specific methods signatures

  • The console project contains following references

 <ItemGroup>
    <PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.0" />
    <PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="8.0.0" />

    <PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
    <PackageReference Include="NLog.Extensions.Logging" Version="5.3.8" />
    <PackageReference Include="NLog" Version="5.2.8" />
    
    //(configuration, Microsoft.Extensions.Http.Poly,..)
  </ItemGroup>
1

There are 1 best solutions below

2
Shahar Shokrani On

So what you need is a Decorator, here is a great example!

abstract class Decorator : Component
{
    protected Component _component;

    public Decorator(Component component)
    {
        this._component = component;
    }

    public void SetComponent(Component component)
    {
        this._component = component;
    }

Follow this logic when the Component is the NLOG and choose how to inject the NLOG (via construtor or via a method).

You can add a SetLogger method to the MyLogger, and keep it as a private propetry, then the info() should be somethinkg like (just make sure its not null):

    public Method(string message)
    {
        // You custom logic...
        _component.Method(message);
    }
}

The usage

    MyLogger logger = new MyLogger();
    logger.SetNLog(nlogIntance)

    logger.Info("Hello world.");