Write a Log file in .Net Application (2024)

  • 298.1k
  • 0
  • 4

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.

  1. usingSystem;
  2. usingSystem.Collections.Generic;
  3. usingSystem.IO;
  4. usingSystem.Linq;
  5. usingSystem.Text;
  6. usingSystem.Threading.Tasks;
  7. namespaceBackToBasicProj
  8. {
  9. classWriteLogFile
  10. {
  11. publicstaticboolWriteLog(stringstrFileName,stringstrMessage)
  12. {
  13. try
  14. {
  15. FileStreamobjFilestream=newFileStream(string.Format("{0}\\{1}",Path.GetTempPath(),strFileName),FileMode.Append,FileAccess.Write);
  16. StreamWriterobjStreamWriter=newStreamWriter((Stream)objFilestream);
  17. objStreamWriter.WriteLine(strMessage);
  18. objStreamWriter.Close();
  19. objFilestream.Close();
  20. returntrue;
  21. }
  22. catch(Exceptionex)
  23. {
  24. returnfalse;
  25. }
  26. }
  27. }
  28. }

Now calling WriteLog method form Program.cs file.

  1. usingSystem;
  2. usingSystem.Collections.Generic;
  3. usingSystem.Linq;
  4. usingSystem.Text;
  5. usingSystem.Threading.Tasks;
  6. namespaceBackToBasicProj
  7. {
  8. classProgram
  9. {
  10. staticvoidMain(string[]args)
  11. {
  12. WriteLogFile.WriteLog("ConsoleLog",String.Format("{0}@{1}","LogisCreatedat",DateTime.Now));
  13. Console.WriteLine("LogisWrittenSuccessfully!!!");
  14. Console.ReadLine();
  15. }
  16. }
  17. }

Now run this !!!

Write a Log file in .Net Application (3)

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.

Write a Log file in .Net Application (4)

Now open with notepad.

Done!!!

Hope you Enjoy with this. Comment your feedback.

Write a Log file in .Net Application (2024)
Top Articles
Latest Posts
Article information

Author: Delena Feil

Last Updated:

Views: 5735

Rating: 4.4 / 5 (65 voted)

Reviews: 88% of readers found this page helpful

Author information

Name: Delena Feil

Birthday: 1998-08-29

Address: 747 Lubowitz Run, Sidmouth, HI 90646-5543

Phone: +99513241752844

Job: Design Supervisor

Hobby: Digital arts, Lacemaking, Air sports, Running, Scouting, Shooting, Puzzles

Introduction: My name is Delena Feil, I am a clean, splendid, calm, fancy, jolly, bright, faithful person who loves writing and wants to share my knowledge and understanding with you.