[Personal use of. Net class library] (2) Log logging class,. net Log record

Source: Internet
Author: User

[Personal use of. Net class library] (2) Log logging class,. net Log record

When developing an interface program, to ensure stable operation of the program, you must monitor the data sent and received by the interface program at all times. This requires a log record class to record the required information in the log file, you can easily maintain the interface program on your own. (The same is true for Web systems, but the corresponding log implementation is a little more complicated than this ).

At the beginning, there were few considerations and the function of controlling the number of log files was not added. After running for a period of time, the Log files in the folder are as follows:

Using System; using System. collections; using System. IO; namespace DotNetCommon. logger {// <summary> // implements the IComparer interface to sort files by name in descending order. // </summary> class FileSorter: IComparer {// <summary> // inherit the methods required by the IComparer interface /// </summary> /// <param name = "x"> FileInfo file x </param> /// <param name = "y"> FileInfo file y </param> /// <returns> </returns> public int Compare (object x, object y) {if (x = null & y = null) return 0; if (x = null) return-1; if (y = null) return 1; var xInfo = (FileInfo) x; var yInfo = (FileInfo) y; // sort return String by name in descending order. compare (yInfo. fullName, xInfo. fullName, StringComparison. ordinal );}}}

The next step is to automatically delete log files. The specific idea is to check whether the maximum number of logs is exceeded when a new log file is created. If this parameter is exceeded, use the comparator defined above to delete it. The automatic log deletion code is as follows:

/// <Summary> /// Delete unnecessary Log files in the Log directory /// </summary> public void DeleteUnnecessaryLogFiles () {var path = new DirectoryInfo (AppDomain. currentDomain. baseDirectory + @ "Log \"); var fileInfos = path. getFiles ("*. log "); Array. sort (fileInfos, new FileSorter (); if (fileInfos. length <= (_ maxLogNum-1) return; for (var I = _ maxLogNum-1; I <fileInfos. length; I ++) {var filepath = fileInfos [I]. fullName; if (! File. Exists (filepath) continue; try {File. Delete (filepath) ;}catch (Exception) {return ;}}}

The Log Code is as follows:

Using System; using System. IO; using System. text; namespace DotNetCommon. logger {/// <summary> /// class description: log record (Text record and byte array record) // encoded by Xiaojun // contact information: binghuojxj@qq.com // </summary> class Log {// <summary> // current program directory // </summary> private readonly DirectoryInfo _ dir = new DirectoryInfo (AppDomain. currentDomain. baseDirectory); // <summary> // The maximum number of default log files is 20 /// </summary> private readonly int _ maxLogNum = 20; /// <summary> /// constructor /// </summary> /// <param name = "maxLogNum"> maximum number of Log files in the Log directory </param> public Log (int maxLogNum) {_ maxLogNum = maxLogNum ;} /// <summary> /// write the string to the log file /// </summary> /// <param name = "msg"> write the string text </param> public void WriteLog_Txt (string msg) {FileStream stream = null; var sb = new StringBuilder (); var path = _ dir + "Log"; if (! Directory. exists (path) {Directory. createDirectory (path);} var str2 = path + @ "\" + DateTime. now. toString ("yyyy-MM-dd") + ". log "; sb. append (DateTime. now. toString ("yyyy-MM-dd HH: mm: ss") + ""); sb. append (msg); var bytes = Encoding. UTF8.GetBytes (sb + "\ r \ n"); try {if (! File. exists (str2) DeleteUnnecessaryLogFiles (); stream = File. openWrite (str2); stream. position = stream. length; stream. write (bytes, 0, bytes. length);} catch (Exception exception) {Console. writeLine ("file opening failed {0}", exception. message);} finally {if (stream! = Null) stream. close ();}} /// <summary> /// write the byte array to the log file /// </summary> /// <param name = "msg"> message </param> // /<param name = "data"> byte array </param> public void WriteLog_Bytes (string msg, byte [] data) {FileStream stream = null; var sb = new StringBuilder (); var path = _ dir + @ "\ Log"; if (! Directory. exists (path) {Directory. createDirectory (path);} var str2 = path + @ "\" + DateTime. now. toString ("yyyy-MM-dd") + ". log "; sb. append (DateTime. now. toString ("yyyy-MM-dd HH: mm: ss") + ""); sb. append (msg); foreach (var num in data) {sb. appendFormat ("{0: x2}", num);} var bytes = Encoding. UTF8.GetBytes (sb + "\ r \ n"); try {if (! File. exists (str2) DeleteUnnecessaryLogFiles (); stream = File. openWrite (str2); stream. position = stream. length; stream. write (bytes, 0, bytes. length);} catch (Exception exception) {Console. writeLine ("file opening failed {0}", exception. message);} finally {if (stream! = Null) stream. close () ;}//< summary> /// Delete redundant Log files in the Log directory /// </summary> public void DeleteUnnecessaryLogFiles () {var path = new DirectoryInfo (AppDomain. currentDomain. baseDirectory + @ "Log \"); var fileInfos = path. getFiles ("*. log "); Array. sort (fileInfos, new FileSorter (); if (fileInfos. length <= (_ maxLogNum-1) return; for (var I = _ maxLogNum-1; I <fileInfos. length; I ++) {var filepath = FileInfos [I]. FullName; if (! File. Exists (filepath) continue; try {File. Delete (filepath) ;}catch (Exception) {return ;}}}}}

Currently, the log class is not complete. I have not added the necessary functions such as file size exceeding the fixed size (for example, 2 MB) to automatically create new files. The necessary functions will be improved in the future. Do you have any suggestions.


What is the difference between the String class and the StringBuilder class? Why do these two classes exist simultaneously in the Net class library? Please

If you want to operate on a growing String, use the StringBuilder class instead of the String class. The two classes work in different ways: the String class is a traditional way of modifying strings. It can indeed add a String to another String, but in.. Because the system first writes two strings to the memory, then deletes the original String object, creates a String object, and reads the data in the memory and assigns it. This process takes a lot of time. The StringBuilder class under the System. Text namespace is not like this. It provides the Append method, which can be used to modify strings in the existing object, which is simple and direct. Of course, the efficiency difference between the two is usually not noticed, but if you want to add a large number of operations to a string, the time consumed by the StringBuilder class and the String class are not an order of magnitude.

What is the difference between the String class and the StringBuilder class? Why do these two classes exist simultaneously in the Net class library?

String is an ordered set of Unicode characters used to represent text. An ordered collection system of string objects .. A character object represents a string. The content of the string value object is an ordered set, which is immutable. A String object is called a constant (read-only) because its value cannot be modified once it is created. Method, it seems that modifying a String object will actually return a New String object, which contains modifications;

The StringBuilder class represents a variable character sequence. It is said that this value is variable, because it can be modified once created by adding, deleting, replacing, or inserting characters. In contrast, we can see the String class. For most methods, you can modify the instance of this class to return a reference to the same instance. A method or attribute reference can be called for an instance returned by a reference. This is convenient. If you want to write a declaration, you can operate one chain at a time. An instance with the maximum number of characters of a StringBuilder can be stored at any given time, and an instance with a length greater than or equal to the string value;

Use the StringBuilder class if it is necessary to modify a linear object of the actual content.

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.