WebVeta - Advanced, unified, consistent search for your website(s), from content of your website(s), blogs(s). First 50 customers, who sign-up prior to 15/05/2024 get unlimited access to existing features, newer features for at least 1 year. Sign up now! https://webveta.alightservices.com/
Categories
Welcome

Why everyone must use a VPN & Password Manager!

After reading this article, most people might call me paranoid, but here is a very feasible worst-case scenario:

CrossPost: https://kantikalyan.medium.com/why-everyone-must-use-a-vpn-password-manager-9c557a186bc0

CrossPost: https://www.linkedin.com/pulse/why-everyone-must-use-vpn-password

Most of you know, I have been fighting with a group of anonymous hackers/r&aw/mafia psychopaths with very powerful equipment, with invisible microdrones capable of camera video recording, hearing, whispering, mind-reading and subliminal messaging (sleep state + whispering in ears).

After registering my own startup – ALight Technology And Services Limited, I have put significant effort into cyber-security. They might know my code, they might know some other sensitive info, but the most critical data has been locked down i.e when I launch WebVeta, where sensitive customer information would be stored, the servers would be thoroughly locked down. Over the past 1 year, whenever I think of a possible attack vector, I think about how to reduce the possibility.

Because these people have such a powerful equipment, what if they stole a web server’s private SSL key of some major website? What if they have some kind of decryption software/hardware? Now they would start packet sniffing by connecting to wireless networks and all the data submitted, session cookies would be accessible. Wireless networks locked down by mac address are also susceptible, because mac address can be spoofed.

In this scenario VPN’s would help, by encrypting packets. Most VPN software would require some kind of fee, but probably worth if you have confidential data i.e your own credentials etc…

There are few free alternatives, some with restrictions etc…

I am NOT promoting any of the following VPN vendors, nor do I have any kind of personal / business tie-ups. These are some free VPN’s some have limitations:

Proton VPN – https://protonvpn.com/free-vpn/

Urban VPN – https://www.urban-vpn.com/

Similarly, consider using password managers and MFA (Multi Factor Authentication)

I don’t have any fake aliases, nor any virtual aliases like some of the the psycho spy R&AW traitors of India. NOT associated – “ass”, eass, female “es”, “eka”, “ok”, “okay”, “is”, “erra”, yerra, karan, kamalakar, diwakar, kareem, karan, sowmya, zinnabathuni, bojja srinivas (was a friend and batchmate 1998 – 2002), mukesh golla (was a friend and classmate 1998 – 2002), thota veera, uttam’s, bandhavi’s, bhattaru’s, thota’s, bojja’s, bhattaru’s or Arumilli srinivas or Arumilli uttam (may be they are part of a different Arumilli family – not my family).

Mr. Kanti Kalyan Arumilli

Arumilli Kanti Kalyan, Founder & CEO
Arumilli Kanti Kalyan, Founder & CEO

B.Tech, M.B.A

Facebook

LinkedIn

Threads

Instagram

Youtube

Founder & CEO, Lead Full-Stack .Net developer

ALight Technology And Services Limited

ALight Technologies USA Inc

Youtube

Facebook

LinkedIn

Phone / SMS / WhatsApp on the following 3 numbers:

+91-789-362-6688, +1-480-347-6849, +44-07718-273-964

+44-33-3303-1284 (Preferred number if calling from U.K, No WhatsApp)

kantikalyan@gmail.com, kantikalyan@outlook.com, admin@alightservices.com, kantikalyan.arumilli@alightservices.com, KArumilli2020@student.hult.edu, KantiKArumilli@outlook.com and 3 more rarely used email addresses – hardly once or twice a year.

Categories
Welcome

Introduction to components in React

In React there are two ways of creating components:

  1. Functional components
  2. Class based components

Functional components seem like simple Javascript functions.

function Name(){
   return (
      <h1>Kanti</h1>
   );
}

The above component would display the name “Kanti” in h1 header tag.

class Name extends React.Component
{
   render() {
      return <h1>Kanti</h1>
   }
}

The above class based component would also have the same functionality i.e display the name “Kanti” in h1 header tag.

The components can be used in other components by using the following syntax:

<Name />

As of now these components aren’t doing anything yet. But SPA frameworks are very useful in code-resuse, specifically when we create re-usable components. Pretty much every SPA framework – AngularJS, Angular, KnockOut, React, Vue etc… supports developing components.

There are several component libraries available for the SPA frameworks.

In future blog posts, I would write on some React based things, concepts such as micro frontends, code re-usability, compare and contrast some SPA frameworks etc…

One of the primary considerations are:

Angular is a framework and provides end to end. React is a front-end library i.e you can use React along with other libraries. Angular is backed by Google.

React can be compiled into static files and hosted or can be rendered on the server (SSR – Server side rendering) using Node. React is backed by Facebook

I have not played around with Vue much, but Vue is also very nice framework and like React, Vue is a library.

In the past (about 7 – 8 years ago) I have played around with AngularJS (the older version) and KnockOut. AngularJS and KnockOut are completely browser based with no SSR.

Modern frameworks, specifically React and Vue support in-browser mode and SSR. For example, you can develop and take advantage of SSR, or you can use in-browser or even a combination of both.

I choose using Cookie based authentication over JWT and React in-browser mode due to certain reasons.

For ease and flexibility, I am using React in one of my projects – Web Veta.

I don’t have any fake aliases, nor any virtual aliases like some of the the psycho spy R&AW traitors of India. NOT associated – “ass”, eass, female “es”, “eka”, “ok”, “okay”, “is”, “erra”, yerra, karan, kamalakar, diwakar, kareem, karan, sowmya, zinnabathuni, bojja srinivas (was a friend and batchmate 1998 – 2002), mukesh golla (was a friend and classmate 1998 – 2002), thota veera, uttam’s, bandhavi’s, bhattaru’s, thota’s, bojja’s, bhattaru’s or Arumilli srinivas or Arumilli uttam (may be they are part of a different Arumilli family – not my family).

Mr. Kanti Kalyan Arumilli

Arumilli Kanti Kalyan, Founder & CEO
Arumilli Kanti Kalyan, Founder & CEO

B.Tech, M.B.A

Facebook

LinkedIn

Threads

Instagram

Youtube

Founder & CEO, Lead Full-Stack .Net developer

ALight Technology And Services Limited

ALight Technologies USA Inc

Youtube

Facebook

LinkedIn

Phone / SMS / WhatsApp on the following 3 numbers:

+91-789-362-6688, +1-480-347-6849, +44-07718-273-964

+44-33-3303-1284 (Preferred number if calling from U.K, No WhatsApp)

kantikalyan@gmail.com, kantikalyan@outlook.com, admin@alightservices.com, kantikalyan.arumilli@alightservices.com, KArumilli2020@student.hult.edu, KantiKArumilli@outlook.com and 3 more rarely used email addresses – hardly once or twice a year.

Categories
Welcome

Injecting Metrics into Graphite – Hosted Grafana – Some C# Code samples

There are various solutions for collecting, storing and viewing metrics. This blog post is specifically about the following list of software:

  1. CollectD – For collecting system metrics
  2. Carbon-Relay-ng – Like a server but forwards the metrics into Graphite
  3. Hosted Graphite at Grafana.com – The backend that stores the metrics
  4. Grafana – For viewing metrics
  5. Grafana for alerts

Collectd

Collectd is a very light-weight, low memory, low CPU usage Linux tool that runs as a service and can collect various system related metrics. Collectd is very extensible and has several plugins. Some of the plugins, I like and have used are:

  1. Apache web server – Gathers Apache related stats
  2. ConnTrack – Number of connections in Linux connection tracking table
  3. ContextSwitch – Number of context switches
  4. CPU
  5. DNS
  6. IP-Tables
  7. Load
  8. MySQL
  9. Processes
  10. tcpconns
  11. users
  12. vmem

My favorite output plugins and some I am familiar with are:

  1. CSV
  2. Write Graphite
  3. gRPC

Carbon-relay-ng

This is not necessarily my favorite, because little heavy on system resources 🙁

Now host Carbon-relay-ng on one of the servers, Install Collectd on the servers that need to ingest metrics. Use Collectd’s Write_Graphite for ingesting metrics into Carbon-relay-ng. Configure Carbon-relay-ng to ingest metrics into hosted Graphite on Grafana.com.

For ingesting any code-based metrics use ahd.Graphite.

var client = new CarbonClient("example.com");

var datapoints = new[]
    {
        new Datapoint("data.server1.cpuUsage", 10, DateTime.Now),
        new Datapoint("data.server2.cpuUsage", 15, DateTime.Now),
        new Datapoint("data.server3.cpuUsage", 20, DateTime.Now),
    };

await client.SendAsync(datapoints);

//Sample code from - https://github.com/ahdde/graphite.net

I would say instead of instantiating too many instances, use either singleton or use a very small pool of instances.

I have promised to semi-open-source some code from my upcoming project – Alerts in the anouncements blog. Anyone with some programming knowledge, can implement such a solution by following this blog. This would be implemented slowly because I am planning to get normal 9 – 5 job, instead of joining or participating in the r&aw dawgs human rights violation, game of loans, game of identity distortion (in this case, I am the victim and their offer, if I participate – identity distortion of some American – sorry, I am not a psycho)

Moreover, for at least 6 – 12 months, the project would be offered completely free of charge for some companies / individuals who see a need and can provide feedback.

Roadmap for next few months!

I don’t have any fake aliases, nor any virtual aliases like some of the the psycho spy R&AW traitors of India. NOT associated – “ass”, eass, female “es”, “eka”, “ok”, “okay”, “is”, “erra”, yerra, karan, kamalakar, diwakar, kareem, karan, sowmya, zinnabathuni, bojja srinivas (was a friend and batchmate 1998 – 2002), mukesh golla (was a friend and classmate 1998 – 2002), thota veera, uttam’s, bandhavi’s, bhattaru’s, thota’s, bojja’s, bhattaru’s or Arumilli srinivas or Arumilli uttam (may be they are part of a different Arumilli family – not my family).

Mr. Kanti Kalyan Arumilli

Arumilli Kanti Kalyan, Founder & CEO
Arumilli Kanti Kalyan, Founder & CEO

B.Tech, M.B.A

Facebook

LinkedIn

Threads

Instagram

Youtube

Founder & CEO, Lead Full-Stack .Net developer

ALight Technology And Services Limited

ALight Technologies USA Inc

Youtube

Facebook

LinkedIn

Phone / SMS / WhatsApp on the following 3 numbers:

+91-789-362-6688, +1-480-347-6849, +44-07718-273-964

+44-33-3303-1284 (Preferred number if calling from U.K, No WhatsApp)

kantikalyan@gmail.com, kantikalyan@outlook.com, admin@alightservices.com, kantikalyan.arumilli@alightservices.com, KArumilli2020@student.hult.edu, KantiKArumilli@outlook.com and 3 more rarely used email addresses – hardly once or twice a year.

Categories
Welcome

How to mount EFS on EC2 Ubuntu instances and automount on reboot

EFS stands for Elastic File System. EFS is a network filesystem where data can persistent and can be accessed by several different EC2 instances.

In pursuit of having my own crash-resistant, tamper-proof, immutable logs and any other future sensitive information I wanted to leverage EFS in my startup ALight Technology And Services Limited.

This article does not discuss EFS in-depth i.e throughput types, Standard vs One Zone etc.. This article is simply about how to mount and automatically mount.

  1. Create the EFS in the region where you need. My current datacenter is in London, United Kingdom because my company is registered in London, United Kingdom (Once again my sincere respect and gratitude for the Government of United Kingdom)
  2. In your EC2 security groups allow port 2049, attach the EC2’s security groups in the networking section of the EFS.
  3. Install the required software
sudo apt install nfs-common -y && \
    sudo systemctl status nfs-utils

4. The command for mounting can be found in EFS, click the EFS name, click “Attach” and you can get the instructions:

sudo mount -t nfs4 -o nfsvers=4.1,rsize=1048576,wsize=1048576,hard,timeo=600,retrans=2,noresvport <FS_ID>.efs.aws-region.amazonaws.com:/ <YOUR_MOUNT_POINT>

5. Copy some file

6. Edit /etc/fstab and add the following line

file_system_id.efs.aws-region.amazonaws.com:/ mount_point nfs4 nfsvers=4.1,rsize=1048576,wsize=1048576,hard,timeo=600,retrans=2,noresvport,_netdev 0 0

Update the above bolded text as per your configuration.

7. Reboot

8. See if the filesystem got attached

Reference List

Mounting on Amazon EC2 Linux instances using the EFS mount helper – Amazon Elastic File System (no date). Available at: https://docs.aws.amazon.com/efs/latest/ug/mounting-fs-mount-helper-ec2-linux.html (Accessed: February 1, 2023).

Using NFS to automatically mount EFS file systems – Amazon Elastic File System (no date). Available at: https://docs.aws.amazon.com/efs/latest/ug/nfs-automount-efs.html (Accessed: February 1, 2023).

Categories
Welcome

Introduction to collectd for metrics

As I have mentioned in a previous blog post – Business activities would continue normal, the primary focus right now is enhancing monitoring and alerting. The strategy is to have a centralized logging and monitoring. Then anomaly detection and alerts. As part of this effort, I came across an excellent utility known as collectd. This tool is easy to install and configure. An alternate is statsd.

I have been looking for metric tools i.e servers that are lightweight, easy to configure and can be easily used from C# applications i.e I want to ingest metrics from my C# applications and consume from C# applications. collectd has GRPC plugin, this would mean a GRPC application can be developed in any programming language. I would definitely provide some code examples for ingesting metrics and reading metrics in the future. For now this is a getting started with collectd blog post.

The installation instructions are bit messed up for collectd, specifically the service file of collectd needs to be manually edited based upon your installation location. As of now, I am collecting some simpler metrics, but there are some plugins that would allow for enhanced metrics gathering.

All the logs are being ingested into AWS CloudWatch. Now, I would be developing some dashboards for monitoring, setting up alerting rules etc… I don’t like existing monitoring front-ends due to very less security restrictions. I want my dashboard to be very secure.

Based on collectd – wiki – first steps here is a summary of installation procedure:

The list of library dependencies for plugins can be found here: README

> sudo apt-get install build-essential
// Install any necessary dependency libraries of plugins, I have installed the following
> sudo apt-get install libgrpc-dev libiptc-dev libmysqlclient-dev libprotobuf-dev libprotobuf-c-dev
> cd cd /tmp/
> wget https://storage.googleapis.com/collectd-tarballs/collectd-5.12.0.tar.bz2
> tar jxf collectd-5.12.0.tar.bz2
> cd collectd-5.12.0
> ./configure
> make all install
> sudo nano /opt/collectd/etc/collectd.conf

I have enabled logfile, syslog, cpu, csv, df, disk, load, memory, swap, uptime, users plugins. These plugins require very less configuration. For csv specify an directory in configuration, for logfile specify a file.

The following was for Ubuntu, but based upon your system edit the collectd.service file. Look for the proper location of the config file, binary and then enable and start the service. On Ubuntu:

Service file: /lib/systemd/system/collectd.service

Configuration file: /opt/collectd/etc/collectd.conf

Binary: /opt/collectd/sbin/collectd

I don’t have any fake aliases, nor any virtual aliases like some of the the psycho spy R&AW traitors of India. NOT associated – “ass”, eass, female “es”, “eka”, “ok”, “okay”, “is”, “erra”, yerra, karan, kamalakar, diwakar, kareem, karan, sowmya, zinnabathuni, bojja srinivas (was a friend and batchmate 1998 – 2002), mukesh golla (was a friend and classmate 1998 – 2002), thota veera, uttam’s, bandhavi’s, bhattaru’s, thota’s, bojja’s, bhattaru’s or Arumilli srinivas or Arumilli uttam (may be they are part of a different Arumilli family – not my family).

Mr. Kanti Kalyan Arumilli

Arumilli Kanti Kalyan, Founder & CEO
Arumilli Kanti Kalyan, Founder & CEO

B.Tech, M.B.A

Facebook

LinkedIn

Threads

Instagram

Youtube

Founder & CEO, Lead Full-Stack .Net developer

ALight Technology And Services Limited

ALight Technologies USA Inc

Youtube

Facebook

LinkedIn

Phone / SMS / WhatsApp on the following 3 numbers:

+91-789-362-6688, +1-480-347-6849, +44-07718-273-964

+44-33-3303-1284 (Preferred number if calling from U.K, No WhatsApp)

kantikalyan@gmail.com, kantikalyan@outlook.com, admin@alightservices.com, kantikalyan.arumilli@alightservices.com, KArumilli2020@student.hult.edu, KantiKArumilli@outlook.com and 3 more rarely used email addresses – hardly once or twice a year.

Categories
Welcome

Sitemaps an intro!

Several search engines support sitemaps. Sitemaps are either xml documents or plain text files that contain a list of URL’s that need to be indexed by search engines. The text file version is simple and straight-forward. I will discuss both the text and xml versions.

Text:

A simple text file that contains one URL per line.

https://www.example.com/file1.html
https://www.example.com/file2.html

XML:

<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
   <url>
      <loc>http://www.example.com/</loc>
      <lastmod>2005-01-01</lastmod>
      <changefreq>monthly</changefreq>
      <priority>0.8</priority>
   </url>
   <url>
      <loc>http://www.example.com/file1.html</loc>
      <changefreq>weekly</changefreq>
   </url>
</urlset>

Most of these are self-explanatory.

lastmod – Needs to be in W3C format.

Year:
YYYY (eg 1997)
Year and month:
YYYY-MM (eg 1997-07)
Complete date:
YYYY-MM-DD (eg 1997-07-16)
Complete date plus hours and minutes:
YYYY-MM-DDThh:mmTZD (eg 1997-07-16T19:20+01:00)
Complete date plus hours, minutes and seconds:
YYYY-MM-DDThh:mm:ssTZD (eg 1997-07-16T19:20:30+01:00)
Complete date plus hours, minutes, seconds and a decimal fraction of a
second
YYYY-MM-DDThh:mm:ss.sTZD (eg 1997-07-16T19:20:30.45+01:00)
where:

 YYYY = four-digit year
 MM   = two-digit month (01=January, etc.)
 DD   = two-digit day of month (01 through 31)
 hh   = two digits of hour (00 through 23) (am/pm NOT allowed)
 mm   = two digits of minute (00 through 59)
 ss   = two digits of second (00 through 59)
 s    = one or more digits representing a decimal fraction of a second
 TZD  = time zone designator (Z or +hh:mm or -hh:mm)

changefreq – This value is optional and needs to be between 0 and 1.0. The default value is 0.5.

There are some restrictions on the number of entries and size. The maximum number of URL’s per file is 50,000 and the maximum size is 50 Mb (uncompressed).

I am planning to provide some C# code snippets for generating XML sitemaps in the next few days. I had some code and generated sitemaps for the alpha version of PodDB, but now I am kind of integrating into the application i.e now the codebase would handle every update, removal, addition, planned for version 0.2.3 (New Year’s release).

Further references:

Google – Build and submit a sitemap

SiteMaps – Protocol

W3C – DateTime

I don’t have any fake aliases, nor any virtual aliases like some of the the psycho spy R&AW traitors of India. NOT associated – “ass”, eass, female “es”, “eka”, “ok”, “okay”, “is”, “erra”, yerra, karan, kamalakar, diwakar, kareem, karan, sowmya, zinnabathuni, bojja srinivas (was a friend and batchmate 1998 – 2002), mukesh golla (was a friend and classmate 1998 – 2002), thota veera, uttam’s, bandhavi’s, bhattaru’s, thota’s, bojja’s, bhattaru’s or Arumilli srinivas or Arumilli uttam (may be they are part of a different Arumilli family – not my family).

Mr. Kanti Kalyan Arumilli

Arumilli Kanti Kalyan, Founder & CEO
Arumilli Kanti Kalyan, Founder & CEO

B.Tech, M.B.A

Facebook

LinkedIn

Threads

Instagram

Youtube

Founder & CEO, Lead Full-Stack .Net developer

ALight Technology And Services Limited

ALight Technologies USA Inc

Youtube

Facebook

LinkedIn

Phone / SMS / WhatsApp on the following 3 numbers:

+91-789-362-6688, +1-480-347-6849, +44-07718-273-964

+44-33-3303-1284 (Preferred number if calling from U.K, No WhatsApp)

kantikalyan@gmail.com, kantikalyan@outlook.com, admin@alightservices.com, kantikalyan.arumilli@alightservices.com, KArumilli2020@student.hult.edu, KantiKArumilli@outlook.com and 3 more rarely used email addresses – hardly once or twice a year.

Categories
Welcome

Some helpful database commands in MySQL / MariaDB

I personally am NOT a DBA. But as a one person company I do everything from product planning, feature prioritization, architecture, documentation, development, deployment, DBA and monitoring. Below are some helpful commands in MySQL / MariaDB that I found useful when I do DBA activities. This is more of a blog post for my own reference.

Connect to database:

mysql -u root -p

Get a list of databases:

show databases;

Use a particular database

use <DATABASE_NAME>;

Show tables in current database

show tables;

Get a list of all the stored procedures in all the databases

SHOW PROCEDURE STATUS;

or

SELECT 
    routine_schema as "Database",
    routine_name
FROM 
    information_schema.routines
WHERE 
    routine_type = 'PROCEDURE'
ORDER BY 
    routine_schema ASC, 
    routine_name ASC;

Get a list of stored procedures in all the databases that match a certain string pattern.

SHOW PROCEDURE STATUS LIKE '%pattern%';

or

SELECT 
    routine_schema as "Database",
    routine_name
FROM 
    information_schema.routines
WHERE 
    routine_type = 'PROCEDURE'
    and routine_name LIKE '%pattern%'
ORDER BY 
    routine_schema ASC, 
    routine_name ASC;

The second select statement can be modified to limit to a certain database by including filters in the where clause on “routine_schema”.

SELECT 
    routine_schema as "Database",
    routine_name
FROM 
    information_schema.routines
WHERE 
    routine_type = 'PROCEDURE'
    and routine_name LIKE '%pattern%'
    and routine_schema = 'database_name'
ORDER BY 
    routine_schema ASC, 
    routine_name ASC;

Hoping this helps someone!

I don’t have any fake aliases, nor any virtual aliases like some of the the psycho spy R&AW traitors of India. NOT associated – “ass”, eass, female “es”, “eka”, “ok”, “okay”, “is”, “erra”, yerra, karan, kamalakar, diwakar, kareem, karan, sowmya, zinnabathuni, bojja srinivas (was a friend and batchmate 1998 – 2002), mukesh golla (was a friend and classmate 1998 – 2002), thota veera, uttam’s, bandhavi’s, bhattaru’s, thota’s, bojja’s, bhattaru’s or Arumilli srinivas or Arumilli uttam (may be they are part of a different Arumilli family – not my family).

Never trust the scammers who claim to have exchanged identities and who use bank accounts on other people’s name. They are either identity thieves / impersonators / anonymous hackers. Example – Erra’s, Thota’s, Bojja’s, Uttam’s, Srinivas’s etc… the R&AW hackers / spies.

Mr. Kanti Kalyan Arumilli

Arumilli Kanti Kalyan, Founder & CEO
Arumilli Kanti Kalyan, Founder & CEO

B.Tech, M.B.A

Facebook

LinkedIn

Threads

Instagram

Youtube

Founder & CEO, Lead Full-Stack .Net developer

ALight Technology And Services Limited

ALight Technologies USA Inc

Youtube

Facebook

LinkedIn

Phone / SMS / WhatsApp on the following 3 numbers:

+91-789-362-6688, +1-480-347-6849, +44-07718-273-964

+44-33-3303-1284 (Preferred number if calling from U.K, No WhatsApp)

kantikalyan@gmail.com, kantikalyan@outlook.com, admin@alightservices.com, kantikalyan.arumilli@alightservices.com, KArumilli2020@student.hult.edu, KantiKArumilli@outlook.com and 3 more rarely used email addresses – hardly once or twice a year.

Categories
Welcome

NLog in .Net Applications

NLog in .Net Applications

The source code can be obtained from: https://github.com/ALightTechnologyAndServicesLimited/NLogSampleDemo001

NLog is a structured logging framework for .Net. NLog is highly extensible, configurable and supports lot of plugins. This post is about some basic usage of NLog, we won’t be discussing any of the advanced features. NLog can be added via nuget package. There are several ways to configure NLog, the documentation can be found here.

NLog supports several built-in Targets such as Console, File, Database etc…, the list of layouts are found here. Some of my favorite targets are: Console, File, Database, BufferingWrapper, AsyncWrapper, AspNetBufferingWrapper, FallbackGroup, RetryingWrapper, ElasticSearch, EventLog, FluentD, MicrosoftTeams, Amazon CloudWatch, Amazon SNS, Amazon SQS, Microsoft Azure ApplicationInsights, Microsoft Azure Blob Storage, Microsoft Azure DataTables Storage, Microsoft Azure FileSystem, Microsoft Azure Queue Storage, Memory, Network, WebService, MessageBox and many more. All the targets are very well documented.

Layouts allow custom layout of log messages and can be viewed here.

Layout Renders are very useful and can be used to determine exactly what information needs to be captured and can be found here. Determining the proper information to capture helps in troubleshooting issues.

In this post, we are going to discuss how to integrate NLog into a console application and how to inject logger into a class for use.

We start off by adding the required nuget packages:

NLog
NLog.Extensions.Logging
Microsoft.Extensions.Configuration.Json
Microsoft.Extensions.DependencyInjection

//packages can be added using the syntax below from .Net CLI
> dotnet add package <package_name>
// optionally the version can be specified via --version flag
// As of the date of this blog post, the following commands would add the latest packages.

> dotnet add package NLog --version 5.0.1
> dotnet add package NLog.Extensions.Logging --version 5.0.0
> dotnet add package Microsoft.Extensions.Configuration.Json --version 7.0.0-preview.5.22301.12
> dotnet add package Microsoft.Extensions.DependencyInjection --version 7.0.0-preview.5.22301.12

Next we will create a nlog.config file with the following content:

<?xml version="1.0" encoding="utf-8" ?>
<!-- XSD manual extracted from package NLog.Schema: https://www.nuget.org/packages/NLog.Schema-->
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xsi:schemaLocation="NLog NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      autoReload="true"
      internalLogFile="c:\temp\logs\nlog-internal.log"
      internalLogLevel="Info" >

  <!-- the targets to write to -->
  <targets>
    <!-- write logs to file -->
    <target xsi:type="File" name="logfile" fileName="c:\temp\logs\logs.log"
            layout="${longdate}|${level}|${message} |${all-event-properties} ${exception:format=tostring}" />
    <target xsi:type="Console" name="logconsole"
            layout="${longdate}|${level}|${message} |${all-event-properties} ${exception:format=tostring}" />
  </targets>

  <!-- rules to map from logger name to target -->
  <rules>
    <logger name="*" minlevel="Trace" writeTo="logfile,logconsole" />
  </rules>
</nlog>

I personally prefer creating environment specific nlog.config files, so a file with the name nlog.Development.config can be created for Development specific configuration. We will see some code snippets further in this blog for using environment specific config file. Remember to set the copyToOutput value to Always.

Now we will add a sample Interface and called IMyInterface

public interface IMyInterface
{
   void PrintHello();
}

Now will add a class that implements IMyInterface known as MyClass

public class MyClass : IMyInterface
{
   private readonly ILogger<MyClass> logger;

   public MyClass(ILogger<MyClass> logger)
   {
      this.logger = logger;
      logger.LogDebug("Constructor Invoked.");
   }

   public void PrintHello()
   {
      logger.LogDebug("PrintHello Invoked.");
      Console.WriteLine("Hello!");
   }
}

Now for the main, The following list of usings are used.

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog;
using NLog.Extensions.Logging;

Now the actual code:

var logger = LogManager.GetCurrentClassLogger();

try
{
    var environment = Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT");
    var configBuilder = new ConfigurationBuilder()
           .SetBasePath(System.IO.Directory.GetCurrentDirectory())
           .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
    var nlogConfigFileName = "nlog.config";

    if (!String.IsNullOrEmpty(environment))
    {
        configBuilder.AddJsonFile($"appsettings.json", optional: true, reloadOnChange: true);
        nlogConfigFileName = $"nlog.{environment}.config";
    }

    var config = configBuilder.Build();

    
    var servicesProvider = new ServiceCollection()
       .AddTransient<IMyInterface, MyClass>()
// Add Additional Services i.e bind interfaces to classes
       .AddLogging(loggingBuilder =>
       {
           // configure Logging with NLog
           loggingBuilder.ClearProviders();
           loggingBuilder.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
           loggingBuilder.AddNLog(nlogConfigFileName);
       })
       .BuildServiceProvider();

   using(servicesProvider as IDisposable)
      {
         var myInterface = servicesProvider.GetRequiredService<IMyInterface>();
        myInterface.PrintHello();
  }
}
catch(Exception e)
{
    logger.Error(e, "Stopped program because of exception");
    throw;
}
finally
{
    LogManager.Shutdown();
}

In the above code, we assume DOTNET_ENVIRONMENT environment variable holds information about the environment. ASPNETCORE_ENVIRONMENT environment variable is used for ASP.Net core applications. Another assumption is that the appsetting.[ENVIRONMENT].json holds environment specific information that needs to be over-written and of course, we specified the appsettings.[ENVIRONMENT].json file as optional.

We are specifying the nlog.[ENVIRONMENT].config to be used for NLog logging. If needed, some additional code can be added for verifying the file exists. This way we can have seperate NLog config files for each environment.

Now using dependency injection ILogger<classname> can be injeced into the constructor of the class and the logger gets injected through dependency injection. For example:

using Microsoft.Extensions.Logging;

public class MyClass : IMyInterface {
   private ILogger<MyClass> logger;

   public MyClass(ILogger<MyClass> logger){
      this.logger = logger;

      logger.LogDebug("Message");
   }
}

The source code can be obtained from: https://github.com/ALightTechnologyAndServicesLimited/NLogSampleDemo001

NLog in .Net Applications

Categories
Welcome

Classic example of corruption in India!

Bofors scandal was a major scandal where 64 crores INR was misused in a arms deal. India’s investigation agency CBI investigated for several years and cleared all the names and said 250 crores INR was spent. After few years the truth is only 4.77 crores INR were spent in the investigation. It’s like making claims of spending 4 times the scandal amount for investigation but in reality, very less was spent. So what happened to the remaining 245.23 crores INR? Would the CBI investigate CBI?

References:

Bofors Scandal – Wikipedia

CBI misled Delhi High Court that Rs 250 crore spent on Bofors probe: Supreme Court told

Categories
Welcome

Welcome!

This blog is for technical related information. As a one-person company, recently, I have been doing a lot of development and some system administration. This blog is to share code snippets – primarily C#, ASP.Net MVC, Javascript, HTML and some server administration, AWS / Azure cloud administration related knowledge. Once in a while, I might post some R and Python code snippets on a necessary basis, I did dabble with R and Python a few years ago to learn Data Analysis, Machine Learning and A.I. But I did not take up Data Analysis, Machine Learning and A.I as a career, but have some knowledge. This blog serves as a reference for myself and for other .Net developers. In other words, like millions of other people, this blog helps for sharing knowledge. My 2 cents to the blogosphere.