C # Logging to a text file

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.