In program development, we usually need to record the state of the program running, after the program deployment, the occurrence of the exception can be recorded in the log, to facilitate the detection of potential problems of the program. In the. NET platform, there are many excellent log class libraries, such as log4net. If the program is small, we can use the Trace class of C # to implement a basic logging function. See the code directly below:
public class Tracehelper {private static tracehelper _tracehelper; Private Tracehelper () {} public static Tracehelper getinstance () {if (_tracehelpe r = = null) _tracehelper = new Tracehelper (); return _tracehelper; The public void Error (String message, String module) {Log (message, messagetype.error, module); The public void Error (Exception ex, string module) {Log (ex). StackTrace, Messagetype.error, module); The public void Warning (String message, String module) {Log (message, messagetype.warning, module); The public void Info (String message, String module) {Log (message, Messagetype.information, module); private void Log (String message, MessageType type, string module) {Trace.WriteLine ( String. Format ("{0},{1},{2},{3}", DateTime.Now.ToString ("Yyyy-mm-dd HH:mm:ss"), type. ToString (), module, message)); }} public enum MessageType {information = 0, Warning = 1, Error = 2}}
Add in the App. Config file (you can also create TraceListener in your code):
<?xml version= "1.0" encoding= "Utf-8"?><configuration> <startup> <supportedruntime version= "v4.0" sku= ". netframework,version=v4.5 "/> </startup> <system.diagnostics> <trace AutoFlush = "true" indentsize= "0" > <listeners> <add name= "Loglistener" type= " System.Diagnostics.TextWriterTraceListener "initializedata=" LogConsoleApp.log "/> </listeners> </trace> </system.diagnostics></configuration>
The use is also very simple,
static void Main (string[] args) { tracehelper.getinstance (). Info ("This is a information message", "Main Function"); Tracehelper.getinstance (). Error ("This was an error message", "Main Function"); }
Code click here to download.
Thank you for reading.
C # uses trace logger log