Why is logging so important during application development? Well, while your application is in developing stage it is very easy to debug the code and to find out what went wrong. But, can you debug in the production environment?

Of course not. 

That is why logging messages are a great way to find out what went wrong and where did error happen in your code in the production environment. .NET Core has its own implementation of logging messages, but in all my projects, I prefer to create my own custom logger service. 

This is what I am going to show you in this post.

If you want to see all the basic instructions and complete navigation for this series, please follow the following link: Introduction page for this tutorial.

For the previous part check out: Part 2 – Creating .NET Core WebApi project – Basic code preparations

Source code to download is available at this link: .NET Core, Angular 4 and MySQL. Part 3 – Source Code

This post is divided into several sections:

Creating required projects

Let’s create two new projects. Name the first one Contracts. You are going to store interfaces inside this project. Name the second one LoggerService. You are going to use it for logger logic.

To create a new project, right click on solution window, choose Add and then NewProject. Choose under .NET Core, Class Library (.NET Core) and name it Contracts.

create-new-project-contracts .net core logging

Do the same thing for the second project, just name it LoggerService.

With these two projects in place, you need to reference them to your main project. In the main project inside solution explorer, right click on Dependences and choose AddReference. Under Projects click Solution and check both projects.

adding-references-of-new-projects .net core logging

Also, add a reference from Contracts project to LoggerService project.

Creating interface and installing NLog

Our logger service will contain four methods of logging:

  • info messages,
  • debug messages,
  • warning messages,
  • and error messages.

Consequently, you will create an interface ILoggerManager inside Contracts project containing those four method definitions.

Add the following code to the ILoggerManager interface:

Before you implement this interface inside LoggerService project, you need to install NLog library in our LoggerService project. NLog is logging platform for .NET which will help us create and log our massages.

I’ll show you two ways of how to add NLog library into your project.

  1. In LoggerService project, right click on Dependences and choose Manage NuGet Packages. After NuGet window appears, just follow the steps from the picture below:

NLog-nuget .net core logging

  1. From the View menu choose Other Windows and then click on Package Manager Console. After console appears just follow the leads from the picture below:

package manager .net core logging

After a couple of seconds, NLog is up and running in your app.

Implementing interface and nlog.config file

In the LoggerService project create new class LoggerManager.

Add the following implementation:

Now, we need to configure it and inject it into Startup class in ConfigureServices method.

NLog needs to have information about the folder to create log files in, what the name of these files will be and what a minimum level of logging is. Therefore, you need to create one text file in the main project with name nlog.config and to populate it as in the example below. You need to change the path of internal log and filename parameters to your paths.

Configuring logger service for logging messages

Setting up the configuration for logger service is quite easy.

First,  you must update constructor in Startup class with following code:

ILoggerFactory has its implementation inside .NET Core and it serves the purpose of configuring the logging system inside it. With the extension method ConfigureNLog, we are forcing the ILoggerFactory to apply the configuration of our new logger from the XML file.

Secondly, you need to add the logger service inside .NET Core’s IOC container. There are three ways to do that:

  • by calling services.AddSingleton which will create the service the first time you request it and then every subsequent request is calling the same instance of service. This means that all components are sharing the same service every time they need it. You are using the same instance always.
  • by calling services.AddScoped which will create the service once per request. That means whenever we send the HTTP request towards application, a new instance of the service is created.
  • by calling services.AddTransient which will create the service each time application request it. This means that if during one request towards our application, multiple components need the service, this service will be created again for every single component which needs it.

So, in ServiceExtensions class add the following method:

Lastly, in ConfigureServices method invoke this extension method, right above services.AddMvc() with this code:

Every time you want to use logger service, all you need to do is to inject it into the constructor of the class that is going to use that service. .NET Core will serve you that service from the IOC container and all of its features will be available to use. This type of injecting objects is called Dependency Injection.

DI, IOC and logger service testing

What is exactly Dependency Injection(DI) and what is IOC (Inversion of Control)?

Dependency injection is a technique for achieving loose coupling between objects and their dependencies. It means that rather than instantiating object every time it is needed, we can instantiate it once and then serve it in class, most often, through constructor method. This specific approach we utilize is also known as Constructor Injection.

In a system that is designed to use DI, you may find many classes requesting their dependencies via their constructor. In that case, it is helpful to have a class which will provide all instances to classes through the constructor. These classes are referred to as containers or more specific Inversion of Control containers. An IOC container is essentially a factory that is responsible for providing instances of types that are requested from it.

For the testing purpose of logger service, you could use ValuesController. You will find it in the main project in Controllers folder. 

In Solution Explorer open Controllers folder and open ValuesController class. Update it like this:

After all, start the application, and browse to http://localhost:5000/api/values. As a result, you will see an array of two strings. Now go to the folder that you have specified in nlog.config file, and check out the result. You should see four lines logged inside that file.

logged file .net core logging

Conclusion

Now you have the working logger service, you will use through an entire process of our application development.

By reading this post you’ve learned:

  • Why logging is important,
  • how to create external service,
  • how to use NLog library and how to configure it,
  • what are DI and IOC
  • and how to use them for service injection.

Thank you for reading and see you soon in the next blog post where we will talk about repository pattern with entity framework core.

If you have any suggestions or questions please don’t hesitate to leave the comment in the comments section below.