Of course, you can use: log4net library;
But at present, the functional requirements do not need to use such a strong log management; write the file directly; so write a simple one;
This is semi-finished products, but also can be used, there are places to optimize;
But before the optimization, the readability is better, I uploaded the:
Using System;
Using System.Text;
Using System.IO;
Using System.Diagnostics;
Using System.Threading.Tasks;
Using System.Threading;
Using System.Runtime.InteropServices;
Namespace Testing { public delegate bool Consolectrldelegate (int dwctrltype); ///<summary> ///@author jave.lin ///@date 2013-
12-11 ///</summary> Public partial class Logger { [DllImport ("kernel32.dll")] " private static extern bool Setconsole
Ctrlhandler (consolectrldelegate handlerroutine, bool add); Private Const int ctrlcevent = 0;//ctrl_c_event = 0;//A CTRL + C signal is received, the signal or from the keyboard, or from the Generatecons olectrlevent functions Private Const int ctrlbreakevent = 1;//ctrl_break_ EVENT = 1;//A ctrl+break signal is received, either from the keyboard or from the Generateconsolectrlevent function , Private const int ctrlcloseevent = 2;//ctrl_close_event = 2;//when When the user system shuts down the console, the system sends this signal to this Private Const int ctrllogoffevent = 5;//ctrl_logoff_e VENT = 5;//The system sends this signal to all console programs when the user exits the system. The signal does not show which user exited. Private Const int ctrlshutdownevent = 6;//ctrl_shutdown_event = 6;//will be sent when the system is going to close
Send this signal to all console programs public static readonly Object Locker = new Object ();
private static StreamWriter WRITER; //todo:caches can use StringBuilder to optimize private static string Conti
Nuewritecaches;
private static readonly stopwatch CONTINUE_WRITESW; private static int continuetime = 300; 300 milliseconds later, continuous write operations, are unified to a piece of operation private static int continuecountmax = 100; WhenThe number of consecutive write operations is capped to the specified value, all are written once, and then recalculated private static int continuecount = 0;
private static string loggerfilename;
public static int allwritecount = 0; static Logger () { var no
Wdatetime = DateTime.Now; var datetimestr = Nowdat Etime.year + "_" + Nowdatetime.month + "_" + Nowdatetime.day + "_" + Nowdate Time.hour + "_" + Nowdatetime.minute + "_" + Nowdatetime.second + "_" + Nowdatetime.millisecond;
Loggerfilename = "Log/logs_" + datetimestr + ". txt";
CONTINUE_WRITESW = new Stopwatch (); if (SetConsoleCtrlHandler (new Consolectrldelegate (Handlerroutine), True) & nbsp { Info ("Set Setconsolectrlhandl
ER success. "); else &NB Sp { error ("Set setconsolectrlhandler error."); } { private static bool Handlerrouti NE (int ctrltype) { switch (ctrltype) & nbsp { &NBSP; //src: //case Ctrlcevent:syst Em. Console.WriteLine ("Ctrl + C KeyDown");
Break //case CtrlBreakEvent:System.Console.WriteLine ("Ctrl+break Keydo WN ");
Break //case CtrlCloseEvent:System.Console.WriteLine ("window closed");
Break //case CtrlLogoffEvent:System.Console.WriteLine ("Log Off or shut Down ");
Break //case CtrlShutdownEvent:System.Console.WriteLine ("System shut Do" WN ");
Break //default:system.console.writeline (ctrltype.tostring ());
Break /NEW: Case CtrlCEvent:System.Console.WriteLiNE ("Ctrl + C KeyDown");
Break //case CtrlBreakEvent:System.Console.WriteLine ("Ctrl+break Keydo WN ");
Break case ctrlcloseevent: &NB Sp
_writebuffer ();
break; //case CtrlLogoffEvent:System.Console.WriteLine ("Log Off or shut Down ");
Break //case CtrlShutdownEvent:System.Console.WriteLine ("System shut Do" WN ");
Break Default:System.Console.WriteLine (ctrltype.tostring ());
Break
return false; } private static void Write (String msg)   { if (string. IsNullOrEmpty (msg)) { RE
Turn Lock (Locker) { if (continuewritecaches = null) CONTINUEW
ritecaches = msg + "\ r \ n";
Else continuewritecaches + msg + "\ r \ n"; if (continue_writesw.isrunning) { if (continue_writesw.elapsed milliseconds > Continuetime) { &NBS P  
_writebuffer ();
return; & nbsp
} ++continuecount; if (Continuecount > Continuecountmax) &NBS P { _writebuffer ();
return; if (!c ontinue_writesw.isrunning) { &N Bsp
Continue_writesw.start (); }   { } private static void _writ Ebuffer () { if (continuewritecaches!= null) { if (! File.exists (Loggerfilename)) { var dir = directory.getparent (loggerfilename).
FullName; if (! Directory.Exists (dir)) {
directory.createdirectory (dir); & nbsp } WRITER = new StreamWriter (Loggerfilename, True, Encoding.UTF8); WRITER.
WriteLine (continuewritecaches); WRITER.
Flush (); WRITER.
Close ();
continue_writesw.stop ();
continue_writesw.reset ();
continuewritecaches = null;
Continuecount = 0;
interlocked.increment (ref allwritecount); } { public partial class Logger { &NBS P
public static Consolecolor s_infocolor = Consolecolor.white; public static consolecolor S_debugcolor = ConSolecolor.green;
public static consolecolor s_warningcolor = Consolecolor.yellow;
public static consolecolor s_errorcolor = consolecolor.red;
private static Object _s_plocker = new Object (); //alwasy log public static void Info (String msg, params object[] PS) { if (PS!= null && PS. Length > 0) { msg = String.
Format (MSG, PS);
_write (S_infocolor, "[Info]" + msg);
} /Remove log when debug complete. public static void Debug (String msg, params object[] PS) { &NBSP; IF (PS!= null && PS. Length > 0) { MSG = s Tring.
Format (MSG, PS); _write (S_debugcolor, "[Debug]" + msg
);
} /remove log when bug fixed. public static void Warning (String msg, params object[] PS) {  ; if (PS!= null && PS. Length > 0) { MSG = s Tring.
Format (MSG, PS); _write (S_warningcolor, "[Warning]" +
msg);
} //Remove log when error fixed. Public STAtic void Error (String msg, params object[] PS) { IF (PS!= null && PS.) Length > 0) { MSG = s Tring.
Format (MSG, PS); _write (S_errorcolor, "[Error]" + msg
); } private static void _write (Consolecolor color, string msg) &NB Sp { Lock (_s_plocker) &NBS P
{ msg = DateTime.Now.ToString () + "" + msg;
var srccolor = Console.foregroundcolor;
Console.foregroundcolor = color; &NBSp
Console.WriteLine (msg);
Console.foregroundcolor = Srccolor;
Write (msg);
{ } }
Test Call:
for (int i = 0; i < i++)
{
logger.debug ("testsadfasdfasdf" + i);
}
Logger.debug ("Write Count:" + logger.allwritecount); Total Call io write number of times: 2 times ... But it writes more than 300 times.