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
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Building Threat Intelligence Pipelines Using Python, APIs, and Elasticsearch
  • Key Takeaways From Integrating a RAG Application With LangSmith
  • Improving Java Application Reliability with Dynatrace AI Engine
  • How We Rebuilt a Legacy HBase + Elasticsearch System Using Apache Iceberg, Spark, Trino, and Doris

Trending

  • LLM-Powered Deep Parsing for Industrial Inventory Search
  • Contract-First Integration: Building Scalable Systems With Flyway, OpenAPI, and Kafka
  • MuleSoft IDP: Enhancing Efficiency and Accuracy in Data Extraction
  • Using LLMs to Automate Data Cleaning and Transformation Pipelines
  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 user avatar
Matt Ghafouri
·
Updated Aug. 25, 20 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
22.3K Views

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.

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

  • Building Threat Intelligence Pipelines Using Python, APIs, and Elasticsearch
  • Key Takeaways From Integrating a RAG Application With LangSmith
  • Improving Java Application Reliability with Dynatrace AI Engine
  • How We Rebuilt a Legacy HBase + Elasticsearch System Using Apache Iceberg, Spark, Trino, and Doris

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • 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