Why logging is important?
Basically, many times we tackle application errors some we got at when our web application is working in the production environment, and if there is any type of errors occurred then it’s hard to track while solving bugs that’s why Logging is important.
How to implement Logging?
There are many tools in the market using that we are able to implement logging. For example, in the .NET Core people mostly used many libraries for logging using that we are going to handle all the scenarios which are present in the application and that will be helpful for us when the application is running in a production environment.
Prerequisites
- A basic understanding of C# Programming.
- Understanding of.NET Core API
- A Basic understanding of Dependency Injection.
So, let’s start with custom and thread logging how do we implement that without any logging tool and libraries which are already present in the .NET Core.
Agenda
- First, we create .NET Core API Application.
- Create Logger Class which we are going to use for logging purposes
- Register the Logger class in the Startup class in the Dependency Injection Container
- After that, we are going to inject that from the constructor of the API Controller
- Finally, apply it to one of the controller methods for testing purposes
Step 1
Open the Visual Studio and create a .NET Core API project.
Step 2
Create the Logger class
using System;
using System.IO;
using System.Threading.Tasks;
namespace LoggingDemo.Logging
{
public class Logger
{
public async Task Log(string logMessage)
{
try
{
string dirPath = @"D:\Log";
string fileName = Path.Combine(@"D:\Log", "Log" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt");
await WriteToLog(dirPath, fileName, logMessage);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
public async Task WriteToLog(string dir, string file, string content)
{
using (StreamWriter outputFile = new StreamWriter(Path.Combine(dir, file), true))
{
await outputFile.WriteLineAsync(string.Format("Logged on: {1} at: {2}{0}Message: {3} at {4}{0}--------------------{0}",
Environment.NewLine, DateTime.Now.ToLongDateString(),
DateTime.Now.ToLongTimeString(), content, DateTime.Now.ToString("dddd, dd MMMM yyyy HH:mm:ss.fff")));
}
}
}
}
- Here you can see we create a Logger class and inside that create two methods which we are going to use for writing the Log on a particular file and location after creating a file and if the file is already present at that location, then it will append log data to it.
- So, inside the first method, we accept the log message, and inside the try block, we put our directory path on which we are going to create a Log file and write a log onto that file on a certain event and call another method and pass directory path, filename and message to that method.
- Also, inside the second method of Logger class, we used Stream Writer to write the log on that we write log in well-structured format and also in a millisecond.
Step 3
Now, we set one environmental variable inside the app setting which we are going to use in configure services method which is present in the startup class.
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"IsLoggerEnabled": "true"
}
Step 4
Next, Register the Logger class as a singleton DI service in configure services method which is present inside the Startup class.




Martin StenhoffPosted Jun 21, 2022, 9:18 AM
Nice simple logger, but this is not Thread Safe. On Windows you will receive an exception 'The process cannot access the file 'D:\Log\Log2022-06-12.txt' because it is being used by another process" and on Linux you will get intertwined messages