In application development environment we always require to track our application performance as well as error and bugs. To tracking bugs and error we always write the log in temporary folder. So today we are going to discuss how to write the log in .Net application. Writing log not only saves our time as well as helps us to track our application in proper manner.
So in this blog I will tell you how to write the log using C# programming language.
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
-
- namespace BackToBasicProj
- {
- class WriteLogFile
- {
- public static bool WriteLog(string strFileName,string strMessage)
- {
- try
- {
- FileStream objFilestream = new FileStream(string.Format("{0}\\{1}", Path.GetTempPath(), strFileName), FileMode.Append, FileAccess.Write);
- StreamWriter objStreamWriter = new StreamWriter((Stream)objFilestream);
- objStreamWriter.WriteLine(strMessage);
- objStreamWriter.Close();
- objFilestream.Close();
- return true;
- }
- catch(Exception ex)
- {
- return false;
- }
- }
- }
- }
Now calling WriteLog method form Program.cs file.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
-
- namespace BackToBasicProj
- {
- class Program
- {
- static void Main(string[] args)
- {
- WriteLogFile.WriteLog("ConsoleLog", String.Format("{0} @ {1}", "Log is Created at", DateTime.Now));
- Console.WriteLine("Log is Written Successfully !!!");
- Console.ReadLine();
- }
- }
- }
Now run this !!!
And now check your Temp folder where the file is created with name "ConsoleLog".
Press-> window+r
Type Temp then click ok to see the log file.
Now open with notepad.
Done!!!
Hope you Enjoy with this. Comment your feedback.