« Nlog » : différence entre les versions

De Banane Atomic
Aller à la navigationAller à la recherche
Ligne 11 : Ligne 11 :
== Config file ==
== Config file ==
{{warn | Be sure to have the config file copied to the output folder while building.}}
{{warn | Be sure to have the config file copied to the output folder while building.}}
<filebox fn='appsettings.json'>
<filebox fn='appsettings.json' collapsed>
{
{
   "NLog": {
   "NLog": {
Ligne 30 : Ligne 30 :
     ]
     ]
   }
   }
}
</filebox>
== Program ==
<filebox fn='Program.cs'>
var logger = LogManager.GetCurrentClassLogger();
try
{
    var config = new ConfigurationBuilder()
      .SetBasePath(Directory.GetCurrentDirectory())
      .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
      .Build();
    // to log in this class only
    LogManager.Configuration = new NLogLoggingConfiguration(config.GetSection("NLog"));
    using var servicesProvider = new ServiceCollection()
        .AddTransient<MyApp>()
        .AddLogging(loggingBuilder =>
        {
            // configure Logging with NLog
            loggingBuilder.ClearProviders();
            loggingBuilder.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
            loggingBuilder.AddNLog(config);
        }).BuildServiceProvider();
    var myApp = servicesProvider.GetRequiredService<MyApp>();
    myApp.Run();
}
catch (Exception ex)
{
    // NLog: catch any exception and log it.
    logger.Error(ex, "Stopped program because of exception");
    throw;
}
finally
{
    // Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux)
    LogManager.Shutdown();
}
}
</filebox>
</filebox>

Version du 16 mars 2023 à 14:31

Links

Console project

Nuget packages

  • NLog.Extensions.Logging
  • Microsoft.Extensions.DependencyInjection
  • Microsoft.Extensions.Configuration.Json

Config file

Be sure to have the config file copied to the output folder while building.
appsettings.json
{
  "NLog": {
    "throwConfigExceptions": true,
    "targets": {
      "async": true,
      "logconsole": {
        "type": "ColoredConsole",
        "layout": "${longdate}|${level}|${message} |${all-event-properties} ${exception:format=tostring}"
      }
    },
    "rules": [
      {
        "logger": "*",
        "minLevel": "Info",
        "writeTo": "logconsole"
      }
    ]
  }
}

Program

Program.cs
var logger = LogManager.GetCurrentClassLogger();

try
{
    var config = new ConfigurationBuilder()
       .SetBasePath(Directory.GetCurrentDirectory())
       .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
       .Build();

    // to log in this class only
    LogManager.Configuration = new NLogLoggingConfiguration(config.GetSection("NLog"));

    using var servicesProvider = new ServiceCollection()
        .AddTransient<MyApp>()
        .AddLogging(loggingBuilder =>
        {
            // configure Logging with NLog
            loggingBuilder.ClearProviders();
            loggingBuilder.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
            loggingBuilder.AddNLog(config);
        }).BuildServiceProvider();

    var myApp = servicesProvider.GetRequiredService<MyApp>();
    myApp.Run();
}
catch (Exception ex)
{
    // NLog: catch any exception and log it.
    logger.Error(ex, "Stopped program because of exception");
    throw;
}
finally
{
    // Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux)
    LogManager.Shutdown();
}