Log.cs 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. //************************************************************************
  2. // https://github.com/yuzhengyang
  3. // author: yuzhengyang
  4. // date: 2017.3.29 - 2017.7.6
  5. // desc: 日志功能
  6. // Copyright (c) yuzhengyang. All rights reserved.
  7. //************************************************************************
  8. //R.Log.IsWriteFile = true;
  9. //R.Log.LogLevel = LogLevel.Warning | LogLevel.Debug;
  10. //Log.AllocConsole();
  11. //R.Log.v("this is v 啰嗦");
  12. //R.Log.d("this is d 调试");
  13. //R.Log.i("this is i 重要");
  14. //R.Log.w("this is w 警告");
  15. //R.Log.e("this is e 错误");
  16. using Azylee.Core.DataUtils.CollectionUtils;
  17. using Azylee.Core.IOUtils.DirUtils;
  18. using Azylee.Core.IOUtils.TxtUtils;
  19. using System;
  20. using System.Collections.Concurrent;
  21. using System.Collections.Generic;
  22. using System.Linq;
  23. using System.Runtime.InteropServices;
  24. using System.Threading;
  25. using System.Threading.Tasks;
  26. namespace Azylee.Core.LogUtils
  27. {
  28. /// <summary>
  29. /// Log 输出工具
  30. ///
  31. /// 说明:
  32. /// 1、Log.AllocConsole();开启控制台
  33. /// 2、Log.FreeConsole();关闭控制台
  34. /// 3、Log.i("information");输出消息
  35. /// </summary>
  36. public class Log
  37. {
  38. #region 基础属性
  39. //输出的 Log 格式
  40. const string LOG_FORMAT = "{0} {1} {2}";
  41. const string TIME_FORMAT = "HH:mm:ss.fff";
  42. const string LOG_PATH = "Log";
  43. private object LogFileLock = new object();//写日志文件锁
  44. private bool IsWriteFile = false;//是否写日志文件
  45. public string LogPath = LOG_PATH;
  46. public LogLevel LogLevel = LogLevel.All;//日志输出等级
  47. bool IsStart = false;
  48. ConcurrentQueue<LogModel> Queue = new ConcurrentQueue<LogModel>();
  49. #endregion
  50. public Log()
  51. { }
  52. public Log(bool isWrite, string logPath = LOG_PATH, LogLevel level = LogLevel.All)
  53. {
  54. if (isWrite && !string.IsNullOrWhiteSpace(logPath))
  55. {
  56. LogPath = logPath.Trim();
  57. IsWriteFile = true;
  58. LogLevel = level;
  59. }
  60. }
  61. void Start()
  62. {
  63. return;
  64. if (!IsStart)
  65. {
  66. IsStart = true;
  67. Task.Factory.StartNew(() =>
  68. {
  69. while (IsStart)
  70. {
  71. Thread.Sleep(500);
  72. if (Queue.Any())
  73. {
  74. List<LogModel> list = new List<LogModel>();
  75. for (int i = 0; i < Queue.Count; i++)
  76. {
  77. LogModel model = null;
  78. if (Queue.TryDequeue(out model)) list.Add(model);
  79. }
  80. if (ListTool.HasElements(list)) WriteFile(list);
  81. }
  82. }
  83. });
  84. }
  85. }
  86. void Stop()
  87. {
  88. if (IsStart)
  89. IsStart = false;
  90. }
  91. public bool SetWriteFile(bool isWrite, string logPath)
  92. {
  93. if (isWrite && !string.IsNullOrWhiteSpace(logPath))
  94. {
  95. LogPath = logPath.Trim();
  96. IsWriteFile = true;
  97. return true;
  98. }
  99. IsWriteFile = false;
  100. return false;
  101. }
  102. #region Console 开启/关闭 API
  103. [DllImport("kernel32.dll")]
  104. public static extern Boolean AllocConsole();
  105. [DllImport("kernel32.dll")]
  106. public static extern Boolean FreeConsole();
  107. #endregion
  108. /// <summary>
  109. /// 获取输出颜色
  110. /// </summary>
  111. /// <param name="type">输出类型</param>
  112. /// <returns></returns>
  113. private ConsoleColor GetColor(LogType type)
  114. {
  115. switch (type)
  116. {
  117. case LogType.v: return ConsoleColor.Gray;
  118. case LogType.d: return ConsoleColor.Blue;
  119. case LogType.i: return ConsoleColor.Green;
  120. case LogType.w: return ConsoleColor.Yellow;
  121. case LogType.e: return ConsoleColor.Red;
  122. default: return ConsoleColor.Gray;
  123. }
  124. }
  125. /// <summary>
  126. /// 写出到控制台
  127. /// </summary>
  128. /// <param name="type">类型</param>
  129. /// <param name="tag">标记</param>
  130. /// <param name="message">消息</param>
  131. private void Write(LogType type, string message)
  132. {
  133. try
  134. {
  135. Console.ForegroundColor = GetColor(type);
  136. Console.WriteLine(LOG_FORMAT, DateTime.Now.ToString(TIME_FORMAT), type.ToString(), message);
  137. //取消单独线程输出日志文件(单独线程输出日志必然会有延迟)
  138. //if (IsWriteFile) Queue.Enqueue(new LogModel() { Type = type, Message = message, CreateTime = DateTime.Now });
  139. if (IsWriteFile) WriteFile(new LogModel() { Type = type, Message = message, CreateTime = DateTime.Now });
  140. }
  141. catch { }
  142. }
  143. private void WriteFile(LogModel log)
  144. {
  145. if (IsWriteFile)
  146. {
  147. lock (LogFileLock)
  148. {
  149. //设置日志目录
  150. string logPath = AppDomain.CurrentDomain.BaseDirectory + LogPath;
  151. string file = string.Format(@"{0}\{1}.txt", logPath, DateTime.Now.ToString("yyyy-MM-dd"));
  152. //创建日志目录
  153. DirTool.Create(logPath);
  154. //写出日志
  155. TxtTool.Append(file, string.Format(LOG_FORMAT, log.CreateTime.ToString(TIME_FORMAT), log.Type.ToString(), log.Message));
  156. }
  157. }
  158. }
  159. private void WriteFile(List<LogModel> list)
  160. {
  161. if (IsWriteFile)
  162. {
  163. lock (LogFileLock)
  164. {
  165. //设置日志目录
  166. string logPath = AppDomain.CurrentDomain.BaseDirectory + LogPath;
  167. string file = string.Format(@"{0}\{1}.txt", logPath, DateTime.Now.ToString("yyyy-MM-dd"));
  168. //创建日志目录
  169. DirTool.Create(logPath);
  170. //整理要输出的内容
  171. List<string> txts = new List<string>();
  172. foreach (var item in list)
  173. {
  174. txts.Add(string.Format(LOG_FORMAT, item.CreateTime.ToString(TIME_FORMAT), item.Type.ToString(), item.Message));
  175. }
  176. //写出日志
  177. TxtTool.Append(file, txts);
  178. }
  179. }
  180. }
  181. #region 分类详细输出
  182. /// <summary>
  183. /// 输出 verbose (啰嗦信息)
  184. /// </summary>
  185. /// <param name="message">消息</param>
  186. /// <param name="tag">可选:标记</param>
  187. public void v<T>(T msg)
  188. {
  189. if ((LogLevel & LogLevel.Verbose) == LogLevel.Verbose)
  190. Write(LogType.v, msg.ToString());
  191. }
  192. /// <summary>
  193. /// 输出 Debug (调试信息)
  194. /// </summary>
  195. /// <param name="message">消息</param>
  196. /// <param name="tag">可选:标记</param>
  197. public void d<T>(T msg)
  198. {
  199. if ((LogLevel & LogLevel.Debug) == LogLevel.Debug)
  200. Write(LogType.d, msg.ToString());
  201. }
  202. /// <summary>
  203. /// 输出 Information (重要信息)
  204. /// </summary>
  205. /// <param name="message">消息</param>
  206. /// <param name="tag">可选:标记</param>
  207. public void i<T>(T msg)
  208. {
  209. if ((LogLevel & LogLevel.Information) == LogLevel.Information)
  210. Write(LogType.i, msg.ToString());
  211. }
  212. /// <summary>
  213. /// 输出 Warning (警告信息)
  214. /// </summary>
  215. /// <param name="message">消息</param>
  216. /// <param name="tag">可选:标记</param>
  217. public void w<T>(T msg)
  218. {
  219. if ((LogLevel & LogLevel.Warning) == LogLevel.Warning)
  220. Write(LogType.w, msg.ToString());
  221. }
  222. /// <summary>
  223. /// 输出 Error (错误信息)
  224. /// </summary>
  225. /// <param name="message">消息</param>
  226. /// <param name="tag">可选:标记</param>
  227. public void e<T>(T msg)
  228. {
  229. if ((LogLevel & LogLevel.Error) == LogLevel.Error)
  230. Write(LogType.e, msg.ToString());
  231. }
  232. #endregion
  233. }
  234. }