Lutz Steinleger

January 25, 2024
w

Let's talk

Do you have a project idea or questions about the use of MORYX?

w

Let us exchange

We are always happy to have an open exchange with you.

Contact

Logging an ASP.NET Core application like MORYX with NLog

Digital Factory

Everyone knows the following scenario: your application is not working as expected. Whether during development or in production, logging helps to analyze a certain behavior. It may be that you only want to see messages with a higher priority at one point, while a very detailed log file is written in parallel. NLog helps to implement these requirements.

Blog entry ASP.NET Core with NLog

What is NLog?

NLog is a flexible and free logging platform for .NET platforms and makes it easy to write to different targets (database, file, console) and change the logging configuration on the fly.

 

Our initial situation

With MORYX 6, we moved to .NET Core 6 and decided to delegate everything that is not part of the MORYX domain to the .NET ecosystem. One of these is ‘logging’.

Before the changeover, we used our own implementation of a logging mechanism. Fortunately, this was already very similar to Microsoft.Extension.Loggin.Ilogger. In the old logging mechanism, we also had an ILogger interface with almost identical methods, for example.

Since our code now depends on the ‘correct’ ILogger, we can use all logging packages that support this interface, such as NLog.

 

How to use NLog

To show how NLog works, we will create a minimal MORYX application as an ASP.NET core application. This means that the Program.cs does not look much different than others:

public static void Main(string[] args)
{
  AppDomainBuilder.LoadAssemblies();                // 1
  var host = Host.CreateDefaultBuilder(args)
      .ConfigureServices(serviceCollection =>
      {
        serviceCollection.AddMoryxKernel();        // 2 
        serviceCollection.AddMoryxModels();        // 2
        serviceCollection.AddMoryxModules();       // 2
       })
       .ConfigureWebHostDefaults(webBuilder =>
       {
          webBuilder.UseStartup<Startup>();
          webBuilder.UseIISIntegration();
        })
        .Build();
   host.Services.UseMoryxConfigurations("Config");  // 3
   host.Services.StartMoryxModules(); // 4
   host.Run();
   host.Services.StopMoryxModules(); // 5
}
  1. Assemblies are loaded to set up dependencies in the following steps
  2. The MORYX services are added to the service collection
  3. The MORYX configuration directory is defined (Config)
  4. The MORYX modules are started…
  5. … and finally stopped at the end of the program.

 

Set up NLog

NLog version 5.* is used in the following examples:

PM> dotnet add package NLog -v 5.*; dotnet add package NLog.Web -v 5.*

To be able to use it, it must be configured in Program.cs:

public static void Main(string[] args)
{
   LogManager
     .Setup()
     .LoadConfigurationFromFile("Config/nlog.config");  // 1
   AppDomainBuilder.LoadAssemblies();
   var host = Host.CreateDefaultBuilder(args)
       .ConfigureServices(serviceCollection =>
       {
         serviceCollection.AddMoryxKernel();
         serviceCollection.AddMoryxModels();
         serviceCollection.AddMoryxModules();
       })
       .ConfigureWebHostDefaults(webBuilder =>
       {
         webBuilder.ConfigureLogging(builder =>
         {
           builder.ClearProviders();                   // 2 
         });
         webBuilder.UseStartup<Startup>();
         webBuilder.UseIISIntegration();
       })
       .UseNLog()                                      // 3 
       .Build();
   host.Services.UseMoryxConfigurations("Config");
   host.Services.StartMoryxModules();
   host.Run();
   host.Services.StopMoryxModules();
}
  1. Loads the NLog configuration. In this case, it is loaded from the specified path. Here it is Config/nlog.config. Instead, NLog could be configured to within appsettings.json and then loaded with LoadConfigurationFromAppSettings(), for example. There are several ways to configure this.
  2. All logging providers are removed. A ConsoleLogger is already added by default. Since we don’t want to have the logs in just one place, we decide to remove them and only use NLog loggers.
  3. Use NLog.

 

Configure NLog

Finally, NLog must be configured. This is a very simple configuration that logs to the console and the file system:

<!-- Config/nlog.config -->
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xsi:schemaLocation="NLog NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" >

    <targets>
      <!-- File Target -->
      <target name="logfile"
              xsi:type="File"
              fileName="Logs/${shortdate}.log"
              layout="${longdate} - ${level} [${logger}] - ${message} ${all-event-properties} ${exception:format=tostring}" />
      <!-- Console Target -->
      <target name="logconsole" xsi:type="Console" 
              layout="${longdate} - ${level} [${logger}] - ${message} ${all-event-properties} ${exception:format=tostring}" />
    </targets>

    <!-- Rules to map from logger name to target -->
    <rules>
      <logger name="*" minlevel="Information" writeTo="logfile" /> <!-- 1 -->
      <logger name="*" minlevel="Warning" writeTo="logconsole" /> <!-- 2 -->
    </rules>
</nlog>
  1. Logging to a file, starting with entries in the “Information” log level.
  2. As we mainly want to use the console to display errors, the minlevel here is set to “Warning”.

That’s it. From here it is quite easy to move on and customize the entire setup to the actual needs of a project.

Need more help? Feel free to contact us!

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *