Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using NLog in asp.net core 2.0 web application

Which is the best way to use Nlog in an asp.net core 2.0 web application

I found a lot of different solutions how to configure. Here are two of them. Are there other better ways?

A) Create Logger before start server:

 public class Program
{
    public static void Main(string[] args)
    {    
        // NLog: setup the logger first to catch all errors
        var logger = NLogBuilder.ConfigureNLog("NLog.config").GetCurrentClassLogger();    
        try
        {
            logger.Debug("init main");
            BuildWebHost(args).Run();
        }
        catch (Exception e)
        {
            //NLog: catch setup errors
            logger.Error(e, "Stopped program because of exception");
            throw;
        }    
    }

    public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>().UseNLog() // use NLog for DI Logger
            .Build();
}

B) Configure inside startup

public class Startup
    {
        public Startup(IHostingEnvironment env, IConfiguration configuration)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                .AddEnvironmentVariables();
            Configuration = builder.Build();            
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {            
            services.AddMvc();                            
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddNLog();
            loggerFactory.ConfigureNLog("nlog.config");

            LogManager.Configuration.Variables["connectionString"] = Configuration.GetConnectionString("myDb");

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseMvc();
        }
    }
like image 328
Stephu Avatar asked Nov 21 '17 12:11

Stephu


People also ask

Does NLog work with .NET Core?

NLog is an open source framework for logging. It is easy to configure with ASP.NET Core application.

Does NLog support .NET 6?

NLog supports the following platforms: . NET 5 & 6 (. NET Standard 2.0)


2 Answers

There is a wiki document about this:

https://github.com/NLog/NLog.Web/wiki/Getting-started-with-ASP.NET-Core-2

To inject custom data like your connection-string, then just create and register a custom layout renderer:

https://github.com/NLog/NLog/wiki/How-to-write-a-custom-layout-renderer

Or put the connection-string into the NLog-Global-Diagnostic-Context at startup:

https://github.com/NLog/NLog/wiki/Var-Layout-Renderer

Maybe something like this where NLog.config makes use of ${gdc:connectionString}:

var myConnectionString = Configuration.GetConnectionString("myDb");
NLog.GlobalDiagnosticsContext.Set("connectionString", myConnectionString);
var logFactory = NLogBuilder.ConfigureNLog("NLog.config"); // Uses ${gdc:connectionString}
var logger = logFactory.GetCurrentClassLogger();
logger.Info("Hello World");

See also https://github.com/NLog/NLog/wiki/Gdc-Layout-Renderer

Update - ${configsetting}

NLog.Extension.Logging ver. 1.4 now supports ${configsetting} so NLog can read settings from appsettings.json directly without needing to use NLog variables. See https://github.com/NLog/NLog/wiki/ConfigSetting-Layout-Renderer

like image 93
Rolf Kristensen Avatar answered Nov 13 '22 16:11

Rolf Kristensen


So here is what I have tried and been using in my project to display logs on console.

  • Install the below packages using nuget

  • create a new file with the name nlog.config and add it to your project with the below content.

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

 <extensions>
    <add assembly="NLog.Web.AspNetCore"/>
  </extensions>
  <!-- the targets to write to -->
  <targets>
    <!-- write logs to file  -->
    <target name="file" xsi:type="File"
            fileName="${basedir}/App_Data/Logs/${shortdate}.txt" encoding="utf-8" layout="[${longdate}][${machinename}][${level}] ${message} ${exception}" />
  </targets>

  <!-- rules to map from logger name to target -->
  <rules>
    <!--All logs, including from Microsoft-->
    <logger name="*" minlevel="Trace" writeTo="allfile" />

    <!--Skip Microsoft logs and so log only own logs-->
    <logger name="Microsoft.*" minlevel="Trace" writeTo="blackhole" final="true" />
    <logger name="*" minlevel="Trace" writeTo="ownFile-web" />
  </rules>
</nlog>
  • Now make sure your appsettings.json has these minimum config to see the logs on console.

{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default":"Trace",
      "Microsoft": "Warning"
    }
  }
  • Configure Program.cs to use this 3rd party NLog as your logger.

    using NLog;
using  NLog.Extensions.Logging;     

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
                WebHost.CreateDefaultBuilder(args)
                .UseKestrel(options =>
                {
                    // options.Listen(IPAddress.Loopback, 5000); //HTTP port
                })
                    .UseContentRoot(Directory.GetCurrentDirectory())
                    .UseIISIntegration()
                    .ConfigureLogging((hostingContext, logging) =>
                                {
                                    logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
                                    logging.AddConsole();
                                    logging.AddDebug();
                                    logging.AddEventSourceLogger();
                                    // Enable NLog as one of the Logging Provider
                                    logging.AddNLog();
                                })
                    .UseStartup<Startup>();

Note: I have used code snippet to insert the code as I am not able to format properly the code in the current editor.

like image 43
Hameed Syed Avatar answered Nov 13 '22 15:11

Hameed Syed