Share a logging class that can be used by multiple threads.

Source: Internet
Author: User

Haven't written a blog for a long time, today to share a log class of their own, non-original, borrowed from the predecessors of an idea, and then modified.

Log we are required, and now the program is multi-threaded concurrency, log there may be problems, lock? Affect performance. Log4net is too heavyweight, this log is a lightweight gadget.

Don't say much nonsense, look at the source:

1 usingSystem;2 usingSystem.Collections.Generic;3 usingSystem.IO;4 usingSystem.Text;5 6 namespaceGEDU.CourseOnline.Common7 {8     /// <summary>9     ///Log class (multi-threaded version)Ten     /// </summary> One      Public classLoghelper A     { -         Private string_filename; -         Private Staticdictionary<Long,Long> lockdic =Newdictionary<Long,Long>(); the  -         /// <summary>   -         ///Gets or sets the file name -         /// </summary>   +          Public stringFileName -         { +             Get{return_filename;} A             Set{_filename =value;} at         } -  -         /// <summary>   -         ///constructor Function -         /// </summary> -         /// <param name= "FileName" >file full path name</param>   in          PublicLoghelper (stringfileName) -         { to             if(string. IsNullOrEmpty (fileName)) +             { -                 Throw NewException ("filename cannot be empty! "); the             } * Create (fileName); $_filename =FileName;Panax Notoginseng         } -  the         /// <summary>   +         ///Create file path A         /// </summary>   the         /// <param name= "FileName" >file path</param>   +          Public voidCreate (stringfileName) -         { $             varDirectoryPath =Path.getdirectoryname (fileName); $             if(string. IsNullOrEmpty (directorypath)) -             { -                 Throw NewException ("filename Path Error! "); the             } -             if(!directory.exists (directorypath))Wuyi             { the directory.createdirectory (directorypath); -             } Wu         } -  About         /// <summary>   $         ///writing text -         /// </summary>   -         /// <param name= "Content" >text content</param> -         /// <param name= "NewLine" >Line break Marker</param>   A         Private voidWrite (stringContentstringnewLine) +         { the             using(FileStream fs =NewFileStream (_filename, FileMode.OpenOrCreate, FileAccess.ReadWrite, Fileshare.readwrite,8, fileoptions.asynchronous)) -             { $byte[] DataArray = Encoding.UTF8.GetBytes (content +newLine); the                 BOOLFlag =true; the                 LongSlen =dataarray.length; the                 LongLen =0; the                  while(flag) -                 { in                     Try the                     { the                         if(Len >=FS. Length) About                         { the FS. Lock (len, slen); theLockdic[len] =Slen; theFlag =false; +                         } -                         Else the                         {BayiLen =FS. Length; the                         } the                     } -                     Catch(Exception ex) -                     { the                          while(!Lockdic.containskey (len)) the                         { theLen + =Lockdic[len]; the                         } -                     } the                 } the FS. Seek (len, seekorigin.begin); theFs. Write (DataArray,0, dataarray.length);94 FS. Close (); the             } the         } the 98         /// <summary>   About         ///Write file Contents -         /// </summary>  101         /// <param name= "Content" >content</param>  102          Public voidWriteLine (stringcontent)103         {104              This. Write (content, Environment.NewLine); the         }106 107         /// <summary>  108         ///write to file content does not wrap109         /// </summary>   the         /// <param name= "Content" >content</param>  111          Public voidWrite (stringcontent) the         {113              This. Write (Content,""); the         } the     } the}
View Code

Usage:

1 string strpath = HttpContext.Current.Server.MapPath (string. Format ("/log/{0:yyyymmdd}.txt", Datetime.today)); 2 // string strpath = string. Format (@ "D:\log\{0:yyyymmdd}.txt", datetime.today); 3 New Loghelper (strpath); 4 "   Time:" + DateTime.Now);

Please advise if you have any deficiencies.

The

shares a logging class that can be used by multiple threads.

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.