简单的自定义日志记录器
我们在项目中经常会对一些信息去做记录,常用的组件是log4net,使用起来非常的简便。引用程序集,进行简单的配置,便可对项目全局进行全面的记录,后边会介绍如何使用Loge4net。下边我们写两个简单的自定义的日志记录器。
1. 我们在API接口中,常常需要把一次完整的请求记录下来,并为了阅读日志便利,做一些简单的封装,代码如下:dispose 参数可供我们手动控制何时写入。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public class ApiLoger : IDisposable 2 { 3 /// <summary> 4 /// The STB 5 /// </summary> 6 StringBuilder stb = null; 7 8 static object _locker = new object(); 9 10 /// <summary> 11 /// 日志文件 12 /// </summary> 13 string _logFile = ""; 14 15 /// <summary> 16 /// 实例化日志记录对象 17 /// </summary> 18 /// <param name="request">函数名称.</param> 19 public ApiLoger(string request) 20 { 21 System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace(); 22 23 lock (_locker) 24 { 25 stb = new StringBuilder(); 26 stb.AppendFormat("{0}\tAPI:{1}\n", DateTime.Now.ToString(), request); 27 28 //日志存放目录 29 string dir = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "App_Data", "Log"); 30 31 //创建日志目录 32 if (Directory.Exists(dir) == false) 33 Directory.CreateDirectory(dir); 34 35 //实例化日志文件 36 _logFile = System.IO.Path.Combine(dir, DateTime.Now.ToString("yyyyMMdd") + ".log"); 37 } 38 } 39 40 /// <summary> 41 /// Initializes a new instance of the <see cref="Logger"/> class. 42 /// </summary> 43 /// <param name="request">The request.</param> 44 /// <param name="paramsJson">The parameters json.</param> 45 public ApiLoger(string request, string paramsJson) 46 : this(request) 47 { 48 this.Write(paramsJson); 49 } 50 51 /// <summary> 52 /// 写日志。 53 /// </summary> 54 /// <param name="content">符合格式字符串.</param> 55 /// <param name="args">要设置其格式的对象的数组.</param> 56 public void Write(string content) 57 { 58 string body =content; 59 stb.AppendFormat("{0}\t{1}\n", DateTime.Now.ToString(), body); 60 } 61 62 /// <summary> 63 /// 写日志 64 /// </summary> 65 /// <param name="content">符合格式字符串</param> 66 /// <param name="disposed">是否释放</param> 67 /// <param name="args">要设置其格式的对象的数组</param> 68 public void Write(string content,bool disposed,params object[] args ) 69 { 70 string body = string.Format(content, args); 71 stb.AppendFormat("{0}\t{1}\n", DateTime.Now.ToString(), body); 72 if (disposed) 73 this.Dispose(); 74 } 75 76 /// <summary> 77 /// 执行与释放或重置非托管资源相关的应用程序定义的任务。 78 /// </summary> 79 public void Dispose() 80 { 81 stb.AppendFormat("{0}\t执行结束\n\n", DateTime.Now.ToString()); 82 83 //通过异步的方式写文件. 84 Task.Run(() => 85 { 86 System.IO.File.AppendAllText(_logFile, stb.ToString()); 87 }); 88 } 89 }
2. 日志队列有内容时,执行写操作,代码如下:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public class CustomLoger 2 { 3 4 static object _async = new object(); 5 6 /// <summary> 7 /// 是否可写 8 /// </summary> 9 static bool startedLog = false; 10 11 /// <summary> 12 /// 日志内容 13 /// </summary> 14 static string info_logFile = ""; 15 16 /// <summary> 17 /// 日志内容记录队列 18 /// </summary> 19 static ConcurrentQueue<string> logInfoQueue = new ConcurrentQueue<string>(); 20 21 /// <summary> 22 /// 静态函数 23 /// </summary> 24 static CustomLoger() 25 { 26 info_logFile = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Finance", "Info", DateTime.Now.ToString("yyyyMMdd") + ".txt"); 27 28 var fileInfo = new FileInfo(info_logFile); 29 if (fileInfo.Directory.Exists == false) 30 fileInfo.Directory.Create(); 31 } 32 33 /// <summary> 34 /// 普通日志 35 /// </summary> 36 /// <param name="formart"></param> 37 /// <param name="args"></param> 38 public static void Info(string formart, params object[] args) 39 { 40 logInfoQueue.Enqueue(DateTime.Now.ToString() + ":\t" + string.Format(formart, args)); 41 WriteInfo(); 42 } 43 44 static void WriteInfo() 45 { 46 if (startedLog) 47 return; 48 49 lock (_async) 50 { 51 startedLog = true; 52 StreamWriter oWrite = new StreamWriter(info_logFile, true); 53 54 while (startedLog) 55 { 56 while (logInfoQueue.Count > 0) 57 { 58 try 59 { 60 string item = logInfoQueue.First(); 61 logInfoQueue.TryDequeue(out item); 62 oWrite.WriteLine(item); 63 } 64 catch (Exception) 65 { 66 continue; 67 } 68 } 69 oWrite.Close(); 70 startedLog = false; 71 } 72 } 73 } 74 75 } 76 }
3. 使用 Trace 进行日志记录
Global中添加如下代码
System.Diagnostics.Trace.Listeners.Clear();
System.Diagnostics.Trace.Listeners.Add(new Crowd.Core.CrowdTraceListener(Server.MapPath("~/logs")));
加油!