Skip to content
This repository was archived by the owner on Dec 13, 2018. It is now read-only.
This repository was archived by the owner on Dec 13, 2018. It is now read-only.

CreateLogger<T>() should return ILogger<T> #312

Closed
@sunsided

Description

@sunsided

Since ILogger<T> already is an ILogger, shouldn't LoggerFactoryExtensions.CreateLogger<T>() return an ILogger<T> instead of an ILogger?

In order to automatically inject a logger, it needs to be of type ILogger<T>. If one needs to create an instance of a class with such a type in the constructor manually (e.g. in a unit test), ILoggerFactory is required (either way, since we can't construct Logger<T> without one).

However, no method or extension of that class is able to construct the required type ILogger<T> by itself. Instead, the type has to be created manually with new Logger<T>(factory) which is kind of awkward, especially since it internally calls factory.CreateLogger<T>() - that is, I'm now passing a logger factory to a logger I created in order to construct itself ...

The sad thing is that the neither of these perfectly valid looking options work

ILogger<Foo> foo = factory.CreateLogger<Foo>();
ILogger<Foo> bar = (ILogger<Foo>)factory.CreateLogger<Foo>();

where the second one explodes with a firework at runtime.

My suggestion would be to implement CreateLogger<T>() as

public static ILogger<T> CreateLogger<T>(this ILoggerFactory factory)
{
    if (factory == null)
    {
        throw new ArgumentNullException(nameof(factory));
    }

    return new Logger<T>(factory);
}

and the constructor of Logger<T> as

public Logger(ILoggerFactory factory)
{
    _logger = factory.CreateLogger(TypeNameHelper.GetTypeDisplayName(typeof(T), fullName: true));
}

instead.

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions