Serilog: How to configure a logger in an Abstract class and have a derived type as the Context?

Created on 25 Jan 2018  路  3Comments  路  Source: serilog/serilog

Hello,

Looking for a way to have the derived class context be used when logging in the derived class. Is this possible?

Thank you,
Stephen

All 3 comments

Yes, I think so, if you initialize the logger in the constructor:

class SomethingAbstract
{
   protected ILogger Log { get; }

   protected SomethingAbstract()
   {
       Log = Log.ForContext(GetType());
   }

// ...

Or another variation, if you want to ensure messages from the base class are tagged with that type:

abstract class SomethingAbstract
{
    readonly ILogger _log = Log.ForContext<SomethingAbstract>();

    // Here's your base class implementation, using _log for logging
}

abstract class SomethingToDeriveFrom : SomethingAbstract
{
   protected ILogger Log { get; }

   protected SomethingToDeriveFrom()
   {
       Log = Log.ForContext(GetType());
   }
}

// Derived classes inherit from SomethingToDeriveFrom and use Log for logging

Very satisfied with the quick response, Thanks Nick!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

travis79 picture travis79  路  4Comments

riiight picture riiight  路  3Comments

ptsneves picture ptsneves  路  4Comments

fernandezjose picture fernandezjose  路  4Comments

Pvlerick picture Pvlerick  路  5Comments