C # Simple log system (server side)

Source: Internet
Author: User

Beginning of the new year, it's time to start learning something new, first of all, to redesign the C # server that was written last year.
Today's goal: Log system
Demand:
1. Display Log
2. Write to local file
3. Error or Exception Log need to be notified by mail
4. Can customize log type (optional)

Log:
I personally understand that the system is operating in the process of prompting information. For example, when the debug program, in addition to the breakpoint debugging, most of the text output, to see if the program is written correctly. Second, we often encounter errors or catch the exception information. By looking at the log, you can quickly help us find what we want.

In this log system, we use two classes: Debug and Loginfile,loginfile are used primarily for log write functionality.

1. Display Log
C # Statement of output text:
Console.WriteLine (info, param);
In the reality log, we only have a layer of encapsulation of the above statement.
Realize:

   <summary>///information///</summary>///<param name= "info" ></param>
        <param name= "param" ></param> public static void Loginfo (string info, params object[] param) {Loginfo ("", info.)
        ToString (), param); ///<summary>///Information///</summary>///<param name= "info" ></param&
        Gt public static void Loginfo (object info) {loginfo ("", info.
        ToString (), NULL); ///<summary>///Custom information///</summary>///<param name= "Genre" ></pa ram>///<param name= "info" ></param>///<param name= "param" ></param> p ublic static void Loginfo (string genre, string info, params object[] param) {setcolor (genre, Colorcon Fig.

            Infocolor, Info,param); Loginfileinfo LiFi = WriteLine (genre, LoggeNreenum.info, Info, param); if (lifi!=null) sendeamil (genre, Loggenreenum.info, String. Format (' {0}-info:{1} ', DateTime.Now, String. Format (info, param)), LiFi.
        GetMessage); }///<summary>///error///</summary>///<param name= "info" ></param  >///<param name= "param" ></param> public static void Logerror (string info, params object[] param) {logerror ("", info.)
        ToString (), param); }///<summary>///error///</summary>///<param name= "info" ></param > public static void Logerror (object info) {logerror ("", info.
        ToString (), NULL); }///<summary>///error///</summary>///<param name= "Genre" ></param >///<param name= "info" ></param>///<param name= "param" &GT;&LT;/PARAM&GT public static void Logerror (string genre, string info, params object[] param) {setcolor (genre, Colorc Onfig.
            Errorcolor, Info,param);
            Loginfileinfo LiFi = WriteLine (genre, Loggenreenum.error, info, param); if (lifi!=null) sendeamil (genre, loggenreenum.warring, String. Format (' {0}-error:{1} ', DateTime.Now, String. Format (info, param)), LiFi.
        GetMessage); }///<summary>///warning///</summary>///<param name= "info" ></param >///<param name= "param" ></param> public static void Logwarring (string info, params object
        [] param) {logwarring ("", info, param); }///<summary>///warning///</summary>///<param name= "info" ></param > public static void Logwarring (object info) {logwarring ("", info.
        ToString (), NULL);
      }  <summary>///warning///</summary>///<param name= "Genre" ></param> <param name= "Info" ></param>///<param name= "param" ></param> public stati c void logwarring (string genre, string info, params object[] param) {setcolor (genre, Colorconfig.warr
            Ingcolor, Info,param);
            Loginfileinfo LiFi = WriteLine (genre, loggenreenum.warring, info, param); Send Message if (LiFi!= null) sendeamil (genre, loggenreenum.warring, String. Format (' {0}-warring:{1} ', DateTime.Now, String. Format (info, param)), LiFi.
        GetMessage); }///<summary>///exception information///</summary>///<param name= "ex" ></param  >///<param name= "tag" ></param> public static void Logexception (Exception ex, string tag =
        "") {logexception ("", ex, Tag);

        }<summary>///Output Exception///</summary>///<param name= "ex" ></param> <param name= "tag" ></param> public static void Logexception (string genre, Exception ex, String ta g = "") {string info = string.
            Empty; info = string. Format ("exception information {0}-{1}" + Environment.NewLine, Tag, ex.)
            message); info = string. Format ("\ t exception object: {0}" + Environment.NewLine, ex.)
            Source); info + = "\ t exception stack:" + Environment.NewLine + "\ T" + ex.
            Stacktrace.trim () + Environment.NewLine; info = string. Format ("\ T Trigger method: {0}" + Environment.NewLine + Environment.NewLine, ex.

            TargetSite);
            SetColor (genre, Colorconfig.excepitoncolor, info);
            Loginfileinfo LiFi = WriteLine (genre,loggenreenum.exception, info); if (LiFi!= null) sendeamil (genre, Loggenreenum.exception, String. Format (' {0}-exception:{1} ', DateTime.Now, ex. Message), LiFi. GetMessage); }

It's just a layer of encapsulation there's nothing to say.
As you can see from the above, I divide the information in the program into four categories:

        Public enum Loggenreenum:int
        {
            ///<summary>
            ///information
            ///</summary>
            info = 2,
            ///& lt;summary>
            ///Errors
            ///</summary> Error
            = 4,
            ///<summary>
            ///warning
            ///</ summary>
            Warring = 8,
            ///<summary>
            ///exception
            ///</summary>
            Exception = 16
        }

It feels like these 4 classes are enough to use.
2. Write to local file
My idea is:
1. Create a queue to store log information
2. Open another thread for file write, the number of threads can be set, the default is 3
3. Every thread can write n log, log data can be set, default 100
4. When the CPU utilization rate is lower than the number, write, the usage can be set, the default 30% (my idea is, when the computer is idle to write, but I do not know how to determine whether the computer is idle, so use the CPU usage. The problem here is that I feel very slow when I get CPU usage, and I don't know why. )
5. log file per day, if the file size is greater than 50M automatically create a new file (just think up, haven't written, but is to determine the size of the file, and then a new one on the line)
6. Threads are written every few seconds, and time can be configured.

The complete Loginfile class

Using System;
Using System.Collections.Generic;
Using System.Diagnostics;
Using System.Linq;
Using System.Text;
Using System.Threading;
Using System.Threading.Tasks;

Using System.IO; Namespace SvEngine.Log {public class Loginfile {PerformanceCounter cpurate = new PerformanceCounter ("Pro
        Cessor ","% Processor time "," _total ");

        Public list<loginfileinfo> messagestack = new list<loginfileinfo> ();
        public void AddMessage (Loginfileinfo message) {Lock (Messagestack) {messagestack.add (message);}
        ///<summary>///begins writing to file///</summary> public void Startinfile ()  {while (true) {lock (messagestack) {if
                    (Messagestack.count < 1)
                        {Thread.Sleep (Debug.InFileConfig.LogInFileWriteInterval);
                    Continue

  }                  if (Cpurate.nextvalue () > Debug.InFileConfig.CpuRate) {T Hread.
                        Sleep (Debug.InFileConfig.LogInFileWriteInterval);
                    Continue
                    } list<loginfileinfo> writelist = new list<loginfileinfo> (); if (Messagestack.count > Debug.InFileConfig.LogInFileWriteNum) {writelist.
                        AddRange (Messagestack.getrange (0, Debug.InFileConfig.LogInFileWriteNum));
                    Messagestack.removerange (0, Debug.InFileConfig.LogInFileWriteNum);
                        else {writelist.addrange (messagestack);
                    Messagestack.clear (); String infomessage = String.
                    Empty; String errormessage = String.
                    Empty; String waringmessage = String.
    Empty;                Write file for (int i = 0; i < Writelist.count; i++) {
                        Loginfileinfo curmes = Writelist[i];
                                Switch (curmes.genre) {case Debug.LogGenreEnum.Info:
                                InfoMessage + = Curmes.getmessage;
                            Break
                                Case Debug.LogGenreEnum.Error:case Debug.LogGenreEnum.Exception:
                                ErrorMessage + = Curmes.getmessage;
                            Break
                                Case Debug.LogGenreEnum.Warring:waringMessage + = Curmes.getmessage;
                        Break
                    } curmes.dispose ();
                    } writetext (Debug.loggenreenum.info,infomessage); WRITETEXT (Debug.LogGenreenum.error, errormessage);

                    WRITETEXT (Debug.LogGenreEnum.Warring, waringmessage);
                Writelist = null;
            }//Waiting for execution thread.sleep (Debug.InFileConfig.LogInFileWriteInterval);
            } private void WriteText (debug.loggenreenum genre,string text) {//File Write String FilePath = String. Format (@ "{0}\{1}\", Debug.InFileConfig.LogPath, genre.)
            ToString ()); String fileName = String.
            Format ("{0}.txt", curdate); if (!
            Directory.Exists (FilePath)) directory.createdirectory (FilePath); if (!
                File.exists (FilePath + filename)) {FileStream fs = file.create (filePath + filename); Fs.
            Close (); using (FileStream fs = new FileStream (FilePath + fileName, Filemode.append, FileAccess.Write, Fileshare.wri TE)) {byte[] info = new utf8eNcoding (True).
                GetBytes (text); Fs. Write (info, 0, info.
            Length); } private string Curdate {get {a return string. Format ("{0}-{1}-{2}", DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day); }}///<summary>///log Data///</summary> public class Loginfileinfo:idisposa ble {///<summary>///log type///</summary> public debug.loggenreenum Gen

        Re
        <summary>///creation time///</summary> public DateTime createtime;
        <summary>///Content///</summary> public string messageconnect; <summary>///Get content///</summary> public string GetMessage {g ET {return string. Format ("{0}-{1}" + System.Environment.NewLine, Createtime, Messageconnect);
     }} public void Dispose ()   {

        }
    }

} 

PerformanceCounter cpurate = new PerformanceCounter ("Processor", "% Processor time", "_total");
This statement is to get the current CPU usage, be sure to note that this statement is best not to put in the method, the first time get a value of 0, if the method in each call, always get the value of 0.

if (Cpurate.nextvalue () > Debug.cpurate)
 {
       thread.sleep (debug.loginfilewriteinterval);
       Continue;
   }

Here we judge the CPU usage rate.

  Case Debug.LogGenreEnum.Error: Case
  Debug.LogGenreEnum.Exception:
       errormessage + = Curmes.getmessage;

I put the log of the error type and the log of the exception type in the same file.

if (! File.exists (FilePath + filename))
{
     FileStream fs = file.create (filePath + filename);
     Fs. Close ();
 }

After the file is created, be sure to close it, or the following will report the file is occupied by other processes of the exception.

In the Infileconfig class, log write-related configuration and methods are stored:

    <summary>///Log Write configuration///</summary> public class Infileconfig {private Loginf
        Ile _loginfile;

        Private thread[] _loginfilethread;
        private bool _isinfile = false;  <summary>///Write file///</summary> public bool Isinfile {get
            {return _isinfile;}
                set {_isinfile = value;
                    if (_isinfile) {_loginfile = new loginfile ();
                    _loginfilethread = new Thread[_loginfilethreadnum];
                Startthread ();
                    else {closethread ();
                _loginfile = null; }} private int _infilegenre = (int) loggenreenum.info | (int) Loggenreenum.error | (int) loggenreenum.exception | (int)
        loggenreenum.warring;
         <summary>

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.