log4net之类3方组件确实很方便,但是想写个小小的demo之类的程序,有点用不起啊。
微软自带的TraceListener要实现一个简易的日志帮助类还是很简单的,直接上代码,自己备用,也希望对同样烦恼的哥们有用:
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Diagnostics; namespace TestExpressionLambda { public class Logger { /// <summary> /// 默认路径 /// </summary> public static readonly string RootPath = AppDomain.CurrentDomain.BaseDirectory + "log"; /// <summary> /// 默认文件名格式 /// </summary> public static readonly string FileFormat = DateTime.Now.ToString("yyyy-MM-dd") + ".log"; /// <summary> /// 默认Trace监听 /// </summary> public static TextWriterTraceListener traceListener; /// <summary> /// 静态实例 /// </summary> private static readonly Logger instance = new Logger(); static Logger() { if (!Directory.Exists(RootPath)) { Directory.CreateDirectory(RootPath); } string logFile = RootPath.TrimEnd('\') + "\" + FileFormat; if (!File.Exists(logFile)) { File.Create(logFile); } Trace.AutoFlush = true; traceListener = new TextWriterTraceListener(logFile); Trace.Listeners.Add(traceListener); } /// <summary> /// log输出
/// 当然这里可以自己随便扩充 /// </summary> /// <param name="msg"></param> public static void Log(string msg) { Trace.WriteLine(msg); } } }