Stephu
Stephu

Reputation: 3334

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();
        }
    }

Upvotes: 8

Views: 10309

Answers (2)

Hameed Syed
Hameed Syed

Reputation: 4275

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.

Upvotes: 1

Rolf Kristensen
Rolf Kristensen

Reputation: 19867

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

Upvotes: 5

Related Questions