[. Net] Create your own log component-release version and. netlog component release version

Source: Internet
Author: User

[. Net] Create your own log component-release version and. netlog component release version

In the previous article, we created a simple Log record class.

However, many park friends have not carefully understood threads, congestion, resource competition, and so on.

In this version of improvement, we have added thread operations, thread waits, and multi-layer error capture. I don't know what to use, but the subconscious asks me to add it]

These improvements are used as a local Log, which does not affect the process of the main thread and does not block it. At the same time, they can meet the requirements for writing multiple logs and avoid resource competition. Take full advantage of the cpu to ensure stable Log recording.

 

Improved code

[Thanks to @ Leandro for his suggestion and the modified Code again]

Using System; using System. componentModel; using System. IO; using System. threading; using System. threading. tasks; namespace CustomerLog {// <summary> // Save the log // </summary> public class Loghelper {private static Mutex _ mutex; static Loghelper () {_ mutex = new Mutex ();} # The region Public thread writes logs /// <summary> // message Log // </summary> /// <param name = "message"> message </param> public void Log (string message) {try {New Task () => Writelog (message )). start ();} catch {// ignored }}/// <summary> // Error Log // </summary> /// <param name = "ex"> error </ param> public void Log (Exception ex) {try {new Task () => WriteBuglog (ex )). start ();} catch {// ignored }}# endregion # region log category // <summary> // Save the common log // </summary> // <param name =" message "> </param> private bool Writelog (string message) {string logConte Nt = string. format ("[{0}] => {1}", DateTime. now. toString ("yyyy-MM-dd hh: mm: ss"), message); return SetFile (@ "Log.txt", logContent );} /// <summary> /// Save the error message log /// </summary> /// <param name = "ex"> </param> private bool WriteBuglog (Exception ex) {var logContent = string. format ("[{0}] error occurred at: {1}, \ r \ n content: {2}", DateTime. now. toString ("yyyy-MM-dd hh: mm: ss"), ex. source, ex. message); logContent + = string. for Mat ("\ r \ n trace: {0}", ex. stackTrace); return SetFile (@ "BugLog.txt", logContent) ;}# endregion # region common operations /// <summary> // standardize the write process, after inheritance, you can customize the written content. // The content is saved in the Log directory of the debug directory by default. // </summary> /// <param name = "filename"> file name </ param> // <param name = "logContent"> write content </param> private static bool SetFile (string filename, string logContent) {_ mutex. waitOne (); try {Isexist (); // determine whether the Log directory contains string errLogFilePath = Environment. CurrentDirectory + @ "\ Log \" + filename. Trim (); // obtain the current directory address StreamWriter sw; if (! File. exists (errLogFilePath) {FileStream fs1 = new FileStream (errLogFilePath, FileMode. create, FileAccess. write); sw = new StreamWriter (fs1);} else {sw = new StreamWriter (errLogFilePath, true);} sw. writeLine (logContent); sw. flush (); sw. close (); return true;} catch {// ignore error return false;} finally {_ mutex. releaseMutex () ;}}// determine whether a log file exists. private static void Isexist () {string path = Environm Ent. CurrentDirectory + @ "\ Log \"; if (! File. Exists (path) {Directory. CreateDirectory (path) ;}# endregion }}

 

The static method is canceled in the new Code. When the class is initialized, the instance is a controller that controls the thread.

 

OK. If you have any questions, I hope you can raise them and learn and improve them together.

 

Related Article

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.