0
votes

I have an ASP.NET project using .NET Core 2 and I notice that when I use the default logger provided by ASP.NET (injected into any controller as ILogger), I see log messages formatted as follows:

default logger

notice how the log level "info" is coloured. Clearly, the IDE is recognising that this is a logger message and handling it in some special way.

However, if I use NLog instead, by doing:

    public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .UseNLog() // add this line!
            .Build();

in Program.cs, without any further code changes

this will then route all log message to nlog processor as well which will handle logging based on nlog logging rules in nlog.config file. So, for example if I have a rule to print to console, then I see the following:

nlog console log

(note that the default Microsoft logger is still active! and will still print the same message again like the first picture)

Now, my real question is, is there a way to make all nlog console log messages appear the same way like the ones coming from the default logger?

You might be wondering why I need nlog console log at all since the default logger is still active anyway. That's because the default logger is only available to controllers using dependency injection and I don't see an easy way to use it in all my classes, whereas NLog is easy to add to any class by doing:

    private static readonly Logger Logger = LogManager.GetCurrentClassLogger();

So, I have two options here:

  • Make nlog console messages recognised by the IDE similar to how it recognised the default logger's message.
  • Make the default Microsoft logger available to any class without needing complex dependency injection, and make sure it is still routing all messages to NLog logger (since I still need nlog's file logging rules with compression, archiving and other nlog features)
1
You should be able to inject ILogger<MyClass> in any class, using dependency injection. just like you do in your controller. NLog can be useful, but the reason you gave isn’t really a valid one.Shane Ray

1 Answers

0
votes

What does you layout look like in your NLog.Config file?

You can try something like this to get the layout you want.

Layout="${level:uppercase=false}: ${logger}${newline}${message}"

NLog has a ColoredConsole Target that might give you the colors you are looking for if the Layout does not do it in the ASP.Net Logger.