1 public class TraceHelper 2 { 3 private static TraceHelper _traceHelper; 4 5 private TraceHelper() 6 { 7 } 8 9 public static TraceHelper GetInstance() 10 { 11 if (_traceHelper == null) 12 _traceHelper = new TraceHelper(); 13 14 return _traceHelper; 15 } 16 17 public void Error(string message, Exception ex) 18 { 19 Log(message, MessageType.Error, ex); 20 } 21 22 public void Warning(string message, Exception ex) 23 { 24 Log(message, MessageType.Warning, ex); 25 } 26 27 public void Info(string message, Exception ex) 28 { 29 Log(message, MessageType.Information, ex); 30 } 31 32 private void Log(string message, MessageType type, Exception ex) 33 { 34 string exmsg = ex == null ? "" : "堆栈信息:" + ex.StackTrace; 35 Trace.WriteLine( 36 string.Format("{0},{1},{2},{3}", 37 DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), 38 type.ToString(), 39 message, 40 exmsg)); 41 } 42 } 43 44 public enum MessageType 45 { 46 Information = 0, 47 Warning = 1, 48 Error = 2 49 }
config配置
1 <configuration> 2 <system.diagnostics> 3 <trace autoflush="true" indentsize="0"> 4 <listeners> 5 <add name="LogListener" type="System.Diagnostics.TextWriterTraceListener" initializeData="..logLogConsoleApp.log"/> 6 </listeners> 7 </trace> 8 </system.diagnostics> 9 </configuration>
在运行程序目录上一层会生成一个Log\LogConsoleApp.log文件