Click here to Skip to main content
15,881,173 members
Articles / Web Development / HTML
Tip/Trick

Using nLog with ASP.NET vNext

Rate me:
Please Sign up or sign in to vote.
3.41/5 (8 votes)
29 Nov 2015CPOL3 min read 38.5K   7   10
This tip helps you implement the nLog in conjunction with Microsoft.Extension.Logging framework in ASP.NET vNext.

Introduction

NLog is a free open source logging framework for .NET (official site here), started by Microsoft’s Jarek Kowalski. It is extremely powerful, and very easy to setup. And it also happens to be my favorite one, that’s why I am going to use it here today with new and latest ASP.NET vNext RC1 release.

Background

The idea came up with nLog implementation with ASP.NET vNext as many of us will be willing to use nLog with ASP.NET vNext. But since the ASP.NET vNext has many changes from its previous version, hence one finds it difficult to implement nLog and how to deal with configuring the nLog.

Using the Code

Create an ASP.NET vNext solution. After the project is created, observe the file appsetting.json as shown in the below image:

Open the "appsettings.json" and add the nlog config section.

C#
"NLogConfig": {
   "Name": "LogFile",
   "Type": "File",
   "FileName": "Project.Log",
   "KeepFileOpen": "false",
   "CreateDirectory": "true",
   "ConcurrentWrites": "true",
   "ArchiveOldFileOnStartup": "false",
   "Level": "Info",
   "Layout": "[${shortdate} | ${level} | ${logger}] ${message}"
 }

Now once this section is added, we need to get the required packages by referencing them in project.json file which is observable in the image above.

Contents of the project.json file shown below:

Now we have to read the nLog config section from appsetting.json file and use it to configure our nlog for logging purposes. Hence, we prepare a class "NLogConfig.cs" as shown in the first image.

The NLogConfig is used to deserialize JSON content of nlog config from the appsettings.json. The content of NLogConfig is shown as below.

Now let's open up startup.cs file and configure our nlog. Here, we will be deserializing the nlog config into NLogConfig object and use it to create configuration for the nLog.

Under the Configure method of our startup file, we need to put the following code which does 3 things:

  1. Deserialize the nlog config into NLogConfig object.
  2. Use NLogConfig to create the LoggingConfiguration
  3. Finally, add the nlog to the default Ilogger factory which is provided by the Microsoft.Extensions.Logging framework.

Code for the LoadNLogConfig is as below:

Now our nLog is completely configured to write the log to files. We need to inject ILoggerFactory in controller where we wish to log things. The code for logging inside a controller is shown below:

This completes our logging implementation with nLog together with Microsoft.Extensions.Logging framework.

Points of Interest

The nLog support for ASP.NET vNext is still very minimal. The good thing is Microsoft.Extensions.Logging.Nlog uses ILogger internally to log, hence it becomes easy to implement and it works together with as many loggers as you add to the logger factory in the startup class.

Moreover, the NLogConfig section can have other targets too apart from File like Database and Email. If we wish to use more targets than one has to put the setting under the nLogConfig section in appsetting.json file and corresponding structure should also be reflected in the deserialized object class.

The nLogConfig section can also put inside a completely new .json file which will serve the sole purpose of Logging Settings for nLog. If this is the approach you wish to follow, then one has to add this file in services collection similar to the way as the appsetting.json is added and read in startup.cs file.

I have tried to kept this tip as simple as it could be. The tip only depicts one of the many ways to implement the nLog with ASP.NET vNext, there might be different and even better approaches that can always come to any of us. It is just a start up code.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



Comments and Discussions

 
GeneralAdd code snippets not as images! Pin
Nightking21-Apr-16 0:49
Nightking21-Apr-16 0:49 
AnswerRe: Adding my code Pin
Nightking21-Apr-16 1:09
Nightking21-Apr-16 1:09 
Besides that, you didn't provide all informations needed...

If you want to use the LogInformation extension method you also have to add following package:

Microsoft.Extensions.Logging.Abstractions

I post my code with the hope someone sees it and can use it.

Package.json
JavaScript
"NLog.Config": "4.3.1",
"Microsoft.Extensions.Logging.NLog": "1.0.0-rc1-final",
"Microsoft.Extensions.Logging.Abstractions": "1.0.0-rc1-final"


Project\Properties\NLogConfig.cs
C#
public class NLogConfig
    {
        public string Name { get; set; }
        public string Type { get; set; }
        public string FileName { get; set; }
        public bool KeepFileOpen { get; set; }
        public bool CreateDirectory { get; set; }
        public bool ConcurrentWrites { get; set; }
        public bool ArchiveOldFileOnStartup { get; set; }
        public string Level { get; set; }
        public string Layout { get; set; }
    }


Startup.cs
C#
public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
            services.Configure<NLogConfig>(Configuration.GetSection("NLogConfig"));

            services.AddMvc();
        }


C#
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IOptions<AppSettings> settings, IOptions<NLogConfig> nlogconfig, ILoggerFactory loggerFactory) {
    app.Map("/myapp", (appb) => this.Configure1(appb, env, settings, nlogconfig, loggerFactory));
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure1(IApplicationBuilder app, IHostingEnvironment env, IOptions<AppSettings> settings, IOptions<NLogConfig> nlogconfig, ILoggerFactory loggerFactory)
{

    loggerFactory.AddNLog(new NLog.LogFactory(GetNLogConfig(nlogconfig)));

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });
}


C#
private LoggingConfiguration GetNLogConfig(IOptions<NLogConfig> nlogconfig)
        {
            var jsonconfig = nlogconfig.Value;
            var config = new LoggingConfiguration();

            var target = new FileTarget {
                ArchiveOldFileOnStartup = jsonconfig.ArchiveOldFileOnStartup,
                ConcurrentWrites = jsonconfig.ConcurrentWrites,
                FileName = jsonconfig.FileName,
                KeepFileOpen = jsonconfig.KeepFileOpen,
                Layout = jsonconfig.Layout,
                Name = jsonconfig.Name
            };

            config.AddTarget(target);

            config.LoggingRules.Add(new LoggingRule("*", NLog.LogLevel.FromString(jsonconfig.Level), target));

            return config;
        }

NewsMicrosoft.Extensions.Logging.NLog is no more, long live NLog.Framework.logging Pin
J. Verdurmen4-Feb-16 21:50
J. Verdurmen4-Feb-16 21:50 
QuestionRe: Microsoft.Extensions.Logging is no more, long live NLog.Framework.logging Pin
Nightking21-Apr-16 1:16
Nightking21-Apr-16 1:16 
AnswerRe: Microsoft.Extensions.Logging is no more, long live NLog.Framework.logging Pin
J. Verdurmen24-May-16 12:12
J. Verdurmen24-May-16 12:12 
QuestionUpdates Pin
Eniep Yrekcaz6-Jan-16 3:58
Eniep Yrekcaz6-Jan-16 3:58 
AnswerRe: Updates Pin
J. Verdurmen4-Feb-16 21:47
J. Verdurmen4-Feb-16 21:47 
QuestionCode snippets Pin
Nelek29-Nov-15 22:27
protectorNelek29-Nov-15 22:27 
AnswerRe: Code snippets Pin
JaredThirsk13-Jan-16 16:23
JaredThirsk13-Jan-16 16:23 
GeneralRe: Code snippets Pin
Rumen Yankov4-Apr-16 23:14
Rumen Yankov4-Apr-16 23:14 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.