C#- Logging files with Nlog

Adewale Adeleye
3 min readDec 29, 2018

--

Logging is an essential part of any application. If a log is well designed, it will be a crucial utility for developers and system administrators to maintain the application. In this post, I will be writing about how to create logs in a C# application.

You might want to log some activities (application event, debug information, SQL query executed) or exception in your application, so knowing how to add logging functionality to your application is very important. We will be using Nuget package manager to install Nlog library in our application.

Create a sample console application.

Creating a console application VS for Mac
Create Application

I will install the library needed for logging and in this case, I will be using Nlog package by installing it from the Nuget package manager and also include the NLog.config package to configure the NLog package.

Install Nlog and Nlog.config package

Following best practice, I will try to catch certain exceptions using the try…catch statement which will help in handling exceptions.

I created a ReadFile method and will try to execute a simple console application and try to catch some file exceptions so that we can log the exception and see how it works. e.g. if the directory of the file cannot be found or if the text file cannot be found.

Console application file and ReadFile method

The next step is to modify the Nlog.config file.

I can decide to modify the directory of the log file and the naming format of the log from te NLog.config. After running the application, a log directory will be added to the debug or release directory. Uncomment the following lines.

<! — Write events to a file with the date in the filename…

and

<! —
Write all events with minimal level of Debug (So Debug, Info, Warn, Error and Fatal, but not Trace) to “f”…

You can also set the minimum logging level/hierarchy. In this case, I used Trace

Nlog configuration file

Here’s the screenshot of the exception and the successful run of the application.

Text file located and is displayed on the console.
Could not find file location exception

Open the bin>debug directory of the project.

Logs directory and log file created after running the application

After opening the created log file, We can now see all exceptions thrown and Trace method added to the application.

Log file

I believe with this post, I have been able to share a quick overview of how logging works and how to include Nlog package into your c# project.

--

--