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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Spring Boot Application With Kafka, Elasticsearch, Redis With Enterprise Standards Part 1
  • Sprinkle Some ELK on Your Spring Boot Logs
  • Reactive Elasticsearch With Quarkus
  • Power BI Embedded Analytics — Part 3: Power BI Embedded Demo

Trending

  • The Perfection Trap: Rethinking Parkinson's Law for Modern Engineering Teams
  • The Role of AI in Identity and Access Management for Organizations
  • Navigating Change Management: A Guide for Engineers
  • Analyzing Techniques to Provision Access via IDAM Models During Emergency and Disaster Response
  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
DZone Core CORE ·
Updated Aug. 25, 20 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
22.0K 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

  • Spring Boot Application With Kafka, Elasticsearch, Redis With Enterprise Standards Part 1
  • Sprinkle Some ELK on Your Spring Boot Logs
  • Reactive Elasticsearch With Quarkus
  • Power BI Embedded Analytics — Part 3: Power BI Embedded Demo

Partner Resources

×

Comments
Oops! Something Went Wrong

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

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!