articles

Home / DeveloperSection / Articles / Create Log File in C#

Create Log File in C#

Create Log File in C#

Anonymous User1696 03-Jul-2021

So, Do you know what is the need for Log Files in an application? If not, don't we'll let you know from basic to advance.

Log files are the primary data source on an application to observe the network. Log files are the computer generated data file which contains information about usage pattern, activities and operations within in an application or a program. So, these information will clear you why we are using log files. Now lets create a log file in C# for better understanding.

Create Log File in C#|Create Log File in C#

Step 1 : Open Visual Studio 2019 on your machine and click on 'Create a New Project' after clicking a new window will open. Now select the 'Console Application' on project templates and click on the next button placed at the bottom of the window. Now a new Window open where you have to enter your Project name. Fill the field and click on the next button. Now your project has been created.

Create Log File in C#|Create Log File in C#

Step 2 : Let's create a new class on your Project. On Solution Explorer present at right side in Visual Studio. Right click on the project and go to Add section and select the class option to add new class. This will open a new sub window where you have to enter your class name at the bottom and after filing click the button 'Add' present at the right bottom. This will crate your new class file.

Create Log File in C#|Create Log File in C#

Step 3 : Now start writing the code snippet. Logic of the code will be like these if the function call of this class. This will create a new .txt file if now present at the directory and append the error with proper time convention on that and the other scenario will be that if the .txt file is already created so we have to only append the file on that .txt file. Following codes are written over here on the basics of these logics.

Create Log File in C#|Create Log File in C#

Step 4 : Now go to your Default class file, i.e., Program.cs add call the function with genuine parameters of other class file(In my scenario I've created a 'Log.cs' for Log creation).

Create Log File in C#|Create Log File in C#

Step 5 : Now run your program you'll see the Log File will be generate as per your defined directory with a proper Date time convention.

Create Log File in C#|Create Log File in C#

Hurrah! You have successfully learn about how log file works in the projects.

Note : Here, we are passing parameters just for learning purpose but in actually we put that code snippet in catch block and pass the argument of Generate exceptions.


Updated 03-Jul-2021
I am a content writter !

Leave Comment

Comments

Liked By