EndlessSpace
EndlessSpace

Reputation: 1380

NLog, .net core: How to get access to a specific logger in my service through dependency injection

Software versions:

I'm using NLog along with Microsoft logging extensions in my .net core console application.

The application contains multiple services that run in background as hosted services.

Each service has access to its typed logger that is set in its constructor through the usual dependency injection. But I also need to add access to a special email logger that will send out an email on critical exceptions. Is there any other way to get a special logger injected into my serivce instead of creating it from "NLog.LogManager.GetLogger()" in every service?

    public class TestService: IHostedService
    {
        private readonly ILogger<TestService> _logger;
        private readonly ILogger _emailOnFatalError;

        public TestService(ILogger<TestService> logger)
        {
            _logger = logger;
            //_emailOnFatalError = (ILogger) NLog.LogManager.GetLogger("emailOnFatalError");
        }
    }

Upvotes: 1

Views: 1590

Answers (1)

Rolf Kristensen
Rolf Kristensen

Reputation: 19912

Instead of having ILogger as constructor-parameter, then use ILoggerFactory:

public class TestService: IHostedService
{
    private readonly ILogger _logger;
    private readonly ILogger _emailOnFatalError;

    public TestService(ILoggerFactory loggerFactory)
    {
        _logger = loggerFactory.CreateLogger(GetType().ToString());
        _emailOnFatalError = loggerFactory.CreateLogger("emailOnFatalError");
    }
}

Alternative consider adding an event-property like this:

_logger.LogError("Something awful - {EmailAlert}", "Important");

Then you can use NLog filtering to only send log-events that contains ${event-property:EmailAlert}:

<logger name="*" writeTo="emailOnFatalError" minLevel="Error">
   <filters defaultAction="Log">
      <when condition="'${event-property:EmailAlert}' == ''" action="Ignore" />
   </filters>
 </logger> 

Upvotes: 2

Related Questions