DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Rebuilding Elasticsearch Under Load: Unsafe Watermarks and a Sampling Blind Spot
  • Idempotency Under Concurrency: Why Your Application Check Isn't the Last Line of Defense
  • Running a Self-Hosted WAF in Production: Practical Lessons From SafeLine
  • Your Application Has an Unindexed Attack Surface. Do You Know What’s in It?

Trending

  • ScyllaDB in Enterprise Java: High-Performance NoSQL With Eclipse JNoSQL
  • Replay, Scheduling, and Throttling: Engineering a Self-Service Kafka Streaming Tool at Scale
  • Taming Parameter Sniffing in SQL Server 2022 With PSP Optimization
  • The Window Closes: Why I Switched to Kotlin Before the Codebase Got Too Big

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Data Engineering
  3. Big Data
  4. Writing .NET Core Application’s Log Into ElasticSearch With NLog

Writing .NET Core Application’s Log Into ElasticSearch With NLog

By 
Matt Ghafouri
·
Updated Aug. 25, 20 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
22.3K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

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.

XML
 




xxxxxxxxxx
1
29


 
1
<?xml version="1.0" encoding="utf-8" ?>
2
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
3
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4
      autoReload="true"> 
5
  <extensions>
6
    <add assembly="NLog.Targets.ElasticSearch"></add>
7
  </extensions>
8
   
9
  
10
  <targets async="true"> 
11
    <target name="elastic"
12
            xsi:type="ElasticSearch"
13
            index="YourAppName" uri="http://192.168.50.60:9200" 
14
            layout ="API:SpecificName |${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}" >
15
    </target> 
16
  </targets>
17
  
18
  <rules>
19
    <!--All logs, including from Microsoft-->
20
    <!--<logger name="*" minlevel="Trace" writeTo="allfile" ></logger>
21
 
22
    <logger name="*" minlevel="Trace" writeTo="ownFile-web" ></logger>
23
 
24
    <logger name="*" minlevel="Trace" writeTo="database" ></logger>-->
25
     
26
    <logger name="*" minlevel="Trace" writeTo="elastic" ></logger>
27
 
28
  </rules>
29
</nlog>



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

Instal-pacakge NLog.Web.AspNetCore

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:

C#
 




xxxxxxxxxx
1
13


 
1
public void ConfigureServices(IServiceCollection services)
2
        {
3
            // other configs
4
            services.AddLogging();              
5
        }
6

          
7
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory LoggerFactory)
8
        { 
9
            // add these lines after authorization and routing config
10
 
11
            LoggerFactory.AddNLog();
12
            LoggerFactory.ConfigureNLog("nlog.config"); 
13
        }



Log Levels

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:

log levels with use case

Rules

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.

C#
 




xxxxxxxxxx
1
24


 
1
public class SampleClass
2
    {
3
        private readonly ILogger _logger;
4
 
5
        public SampleClass(ILoggerFactory loggerFactory)
6
        {
7
            _logger = loggerFactory.CreateLogger<SampleClass>();
8
        }
9
 
10
        public Task TestMethod()
11
        {
12
            try
13
            {
14
                _logger.LogDebug("Debug Information");
15
                _logger.LogInformation("Some Information");
16
                _logger.LogWarning("Some Information");
17
            }
18
            catch (Exception ex)
19
            {
20
                _logger.LogError(ex,"my custom message"); 
21
            }
22
            return Task.CompletedTask; 
23
        }
24
    }



To check the logs in ElasticSearch you could use some tools, like PostMan, Kibana 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.

POSTman GET request


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


Follow me on Medium.

Elasticsearch application

Opinions expressed by DZone contributors are their own.

Related

  • Rebuilding Elasticsearch Under Load: Unsafe Watermarks and a Sampling Blind Spot
  • Idempotency Under Concurrency: Why Your Application Check Isn't the Last Line of Defense
  • Running a Self-Hosted WAF in Production: Practical Lessons From SafeLine
  • Your Application Has an Unindexed Attack Surface. Do You Know What’s in It?

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook