ASP.NET CORE 2.0 Hosting – How To Use StringBuilder And File Class For .NET Application?

In this article, I am going to share how to use StringBuilder and File Class to create an error log for your .NET application.

Here, I am going to share how and why should we create error log in our application. In our application, generally, we use try, catch block to handle unforeseen errors. As we know, catch block executes when an error occurs in the try block. We write the error inside the catch block. Often, inside the catch block, we call a function which writes the error log. I will explain with the help of an example. Developers use error log to know the type of error and error position in the running application. We write a date, error type, and position of error inside our error log file.

Step 1

Create one method as I created below. I created one method with WriteErrorLog name and passed two parameters – errorMessage and errorPosition. errorMessage parameter contains an error message and errorPosition parameter contains the method name from where the error is created. I used File class to write the StringBuilder contents over the .txt file inside the bin folder of the application. File class is available inside System.IO namespace.

Step 2

Call this WriteErrorLog method inside the all catch block and pass these two parameters as I did in the below code. I called WriteErrorLog method inside the catch block. First, the try block will be executed and if any error occurs, then the control goes to catch block and WriteErrorLog method will be called.

In my try block, I am trying to convert a string into an integer. At this point, an error will come and control will go to the catch block.  As control goes to the catch block, the WriteErrorLog method will be called and the error log will be created inside the bin folder of the application.

Step 3

See your bin folder. You will find an errorLog.txt file with some details similar to what I have shown in the below picture: