Writing .NET Core Application’s Log Into ElasticSearch With NLog
Join the DZone community and get the full member experience.Join For Free
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.
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.
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:
Now, as the next step, we need to configure 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:
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
falseto disable the rule without deleting it
ruleName– rule identifier to allow rule lookup with
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.
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.
If you click on the Send button you will get the logs in Postman panel.
Opinions expressed by DZone contributors are their own.