We could write all types of log into ElasticSearch by configuring our application.

As the first step, you need to create an empty web application(.net core) in Visual studio.

creating new project

Now right click on the project and select Add new Item and search config to find Web Configuration File option. Set nlog.config as the file name. 

Add new Item and search config to find Web Configuration File option. Set nlog.config as the file name

Write the below code into the newly added config file.

Before set the logging config, we should install some related packages, For this purpose, select NugetPackageManager from Tools menu and after that select PackageManagerConsole

In the appeared console, to install necessary packages, use these commands :

Install-Package NLog 

Install-Package NLog.Targets.ElasticSearch

Instal-Package Microsoft.Extensions.Logging

Now, as the next step we need to config Startup.cs

open the Startup.cs file which located in the root of the project. add these code to the ConfigureServices and Configure sections :

Each log entry has a level. And each logger is configured to include or ignore certain levels. A common configuration is to specify the minimum level where that level and higher levels are included. For example, if the minimum level is Info, then Info, Warn, Error and Fatal are logged, but Debug and Trace are ignored.

The log levels, in descending order, are as follows:


The rules section maps loggers to targets and log levels.

A rule is a logger element with the following attributes:

  • name – logger name filter – may include wildcard characters (* and ?)
  • minlevel – minimal level to log
  • maxlevel – maximum level to log
  • level – single level to log
  • levels – comma separated list of levels to log
  • writeTo – comma separated list of targets to write to
  • final – no rules are processed after a final rule matches
  • enabled – set to false to disable the rule without deleting it
  • ruleName – rule identifier to allow rule lookup with Configuration.FindRuleByName and Configuration.RemoveRuleByName. Introduced in NLog 4.6.4

Everything is done. Now to write a log with NLog we just need a logger instance in our class or controller or whenever we need it. ILoggerFactory could create an instance of our class type.

To check the logs in ElasticSearch you could use some tools, like PostManKibana or some other tool which can retrieve data from ElasticSearch

Here, I’m using Postman to retrieve logs from ElasticSearch. Open PostMan Create an Empty Request.

Set the Type of the request to Get and enter the IP that you set in the nlog.config file. Remember that, you have to enter the exact name which you set in the config file (in this example we used YourApplicationName. you can replace it with whatever you want.

set the type request to Get and enter the IP

If you click on the Send button you will get the logs in Postman panel.

get logs in postman panel

Source link

Write A Comment