Add a storage path to the log file in the configuration file:
1 <appsettings>2 <add key= "LogPath" value= "H:\Logs"/>3 </appSettings>
Encapsulates a class of logging:
1 Public classSystemlog2 {3 Public Static voidWritelogline (stringexceptionmessage)4 {5 stringPath =string. Empty;6 Try7 {8Path = configurationmanager.appsettings["LogPath"];9 }Ten Catch(Exception) One { APath =@"C:\Temp"; - } - if(string. IsNullOrEmpty (path)) thePath =@"C:\Temp"; - Try - { - //If the log directory does not exist, the directory is created + if(!directory.exists (path)) - { + directory.createdirectory (path); A } at stringLogFileName = path +"\ \ Program Log _"+ DateTime.Now.ToString ("yyyy_mm_dd_hh") +". Log"; -StringBuilder logcontents =NewStringBuilder (); - Logcontents.appendline (exceptionmessage); - //new If the log file for the day does not exist, otherwise append content -StreamWriter SW =NewStreamWriter (LogFileName,true, System.Text.Encoding.Unicode); -Sw. Write (DateTime.Now.ToString ("YYYY-MM-DD hh:mm:sss") +" "+logcontents.tostring ()); in SW. Flush (); - SW. Close (); to } + Catch(Exception) - { the } * } $}
Use the log class in your program:
Systemlog.writelogline ("======> program starts execution ");//Record the time the program started executing
C # Logging to a text file