0

In order to use serilog, I call

Serilog.SerilogHostBuilderExtensions.UseSerilog (actual implementation: Serilog.Extensions.Logging.SerilogLogger)

Then, my service is defined like below

public class MyService
{
    // constructor
    public MyService(Microsoft.Extensions.Logging.ILogger<MyService> logger)
    {
        ...
    }
}

Everything is fine and I can get the logger object in the constructor with actual implementation of Serilog.Extensions.Logging.SerilogLogger

But when I change the parameter of the constructor to a non-generic ILogger like below, it fails to be resolved in the DI container.

public MyService(Microsoft.Extensions.Logging.ILogger logger)

According to the page https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.logging.ilogger-1?view=dotnet-plat-ext-6.0, the generic version (ILogger<TCategoryName> Interface) is explicitly designed for activation from dependency injection.

What is the use of TCategoryName? It does not seems to be included in the log, why I need it? Is there any reason why I must use a named/generic ILogger when using DI? Any reasons behind?

====================================================

Update after comments:

Thanks for the comments. I now understand TCategoryName is being used in default format and explicitly by {SourceContext}.

But I still do not understand why I must use a named/generic ILogger when using DI?

It seems to me that it is by design, but why we have this design?

Why MS DI container does not allow us to use a non-generic one (https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.logging.ilogger?view=dotnet-plat-ext-6.0).

====================================================

kzfid
  • 688
  • 3
  • 10
  • 17
  • 1
    `TCategoryName` is definitely included in the log by default. Unless you have a different format in your Serilog config. – DavidG Aug 16 '22 at 10:34

1 Answers1

0

Here is a source code:

public class Logger<T> : ILogger<T>
{
    public Logger(ILoggerFactory factory)
    {
        if (factory == null)
        {
            throw new ArgumentNullException(nameof(factory));
        }

        _logger = factory.CreateLogger(TypeNameHelper.GetTypeDisplayName(typeof(T)));
    }
//  ...

To use this name of type that is passed you can enrich serilog with {SourceContext} property

KrystianL
  • 1
  • 2
  • Thanks. This answers the first questions "What is the use of TCategoryName? It does not seems to be included in the log, why I need it?". But I still do not understand why I must use a named/generic ILogger when using DI? I mean why a non-generic one is not allowed. – kzfid Aug 16 '22 at 14:30