aXe
aXe

Reputation: 101

How to use Microsoft.Extesions.ILogger together with NLog?

I have a system and I want to make a custom logs to create separate folders for each user. Now, I made it in NLog.Logger like a custom file target

public static LogFactory ConfigureCustomNLog(string userName)
        {
            var target = new FileTarget();
            target.Name = "fileLog";
            target.FileName = $"${{basedir}}/log" + $"/{userName}/{userName}" + "${shortdate}.log";
            target.Layout =
                "${longdate}|${uppercase:${level}} ${logger}|${message} ${exception:format=ToString,StackTrace}";

            var config = ConfigureNLog("NLog.Config").Configuration;
            config.RemoveTarget("fileLog");
            config.AddTarget(target.Name, target);

            var rule = new LoggingRule(userName, LogLevel.Debug, target);
            config.LoggingRules.Add(rule);

            LogManager.Configuration = config;

            return LogManager.LogFactory;
        }

Everything is working fine, but I want to use like Microsoft.Extensions.ILogger. How I can import NLog.Logger to ILogger? Or how I can make custom config for ILogger?

Upvotes: 7

Views: 10629

Answers (1)

Rolf Kristensen
Rolf Kristensen

Reputation: 19847

Normally Microsoft ILogger is used together with dependency injection. Like described here:

https://github.com/NLog/NLog/wiki/Getting-started-with-.NET-Core-2---Console-application

But you can also do it manually:

class MyClass
{
    private readonly Microsoft.Extensions.Logging.ILogger Logger;
 
    public MyClass(Microsoft.Extensions.Logging.ILoggerFactory loggerFactory)
    {
        Logger = loggerFactory.CreateLogger(GetType().ToString());
        Logger.LogInformation("Hello");
    }
}

var loggerFactory = new NLog.Extensions.Logging.NLogLoggerFactory();
var myClass = new MyClass(loggerFactory);

If you are building a Web-Application then this might help: https://github.com/NLog/NLog/wiki/Getting-started-with-ASP.NET-Core-5

Upvotes: 12

Related Questions