LogHelper.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. using log4net;
  2. using log4net.Config;
  3. using log4net.Repository;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Text;
  9. using System.Timers;
  10. using System.Xml;
  11. namespace Logs
  12. {
  13. /// <summary>
  14. /// 日志帮助类
  15. /// </summary>
  16. public static class LogHelper
  17. {
  18. /// <summary>
  19. /// 日志仓库
  20. /// </summary>
  21. public static ILoggerRepository? LoggerRepository { get; set; }
  22. #region 写入日志
  23. private static ILog? GetLog(ILogType type, string flagKey)
  24. {
  25. if (LoggerRepository == null)
  26. return null;
  27. if (type.SubLogNames.ContainsKey(flagKey))
  28. return LogManager.GetLogger(LoggerRepository.Name, type.SubLogNames[flagKey]);
  29. string defaultKey = string.Empty;
  30. foreach (var key in type.SubLogNames.Keys)
  31. {
  32. defaultKey = key;
  33. break;
  34. }
  35. return LogManager.GetLogger(LoggerRepository.Name, type.SubLogNames[defaultKey]);
  36. }
  37. #region Info
  38. /// <summary>
  39. /// 运行记录
  40. /// </summary>
  41. /// <param name="type">日志类型</param>
  42. /// <param name="message">消息</param>
  43. /// <param name="ex">异常</param>
  44. /// <param name="flagKey">日志子项索引Key</param>
  45. public static void Info(this ILogType type, string message, Exception ex, string flagKey) => GetLog(type, flagKey.ToUpper())?.Info(GetLogMessage(message, ex));
  46. /// <summary>
  47. /// 运行记录
  48. /// </summary>
  49. /// <param name="type">日志类型</param>
  50. /// <param name="message">消息</param>
  51. /// <param name="flagKey">日志子项索引Key</param>
  52. public static void Info(this ILogType type, string message, string flagKey) => type.Info(message, null, flagKey);
  53. /// <summary>
  54. /// 运行记录
  55. /// </summary>
  56. /// <param name="type">日志类型</param>
  57. /// <param name="ex">异常</param>
  58. /// <param name="flagKey">日志子项索引Key</param>
  59. public static void Info(this ILogType type, Exception ex, string flagKey) => type.Info(null, ex, flagKey);
  60. #endregion Info
  61. #region Error
  62. /// <summary>
  63. /// 错误记录
  64. /// </summary>
  65. /// <param name="type">日志类型</param>
  66. /// <param name="message">消息</param>
  67. /// <param name="ex">异常</param>
  68. /// <param name="flagKey">日志子项索引Key</param>
  69. public static void Error(this ILogType type, string message, Exception ex, string flagKey) => GetLog(type, flagKey.ToUpper())?.Error(GetLogMessage(message, ex));
  70. /// <summary>
  71. /// 错误记录
  72. /// </summary>
  73. /// <param name="type">日志类型</param>
  74. /// <param name="message">消息</param>
  75. /// <param name="flagKey">日志子项索引Key</param>
  76. public static void Error(this ILogType type, string message, string flagKey) => type.Error(message, null, flagKey);
  77. /// <summary>
  78. /// 错误记录
  79. /// </summary>
  80. /// <param name="type">日志类型</param>
  81. /// <param name="ex">异常</param>
  82. /// <param name="flagKey">日志子项索引Key</param>
  83. public static void Error(this ILogType type, Exception ex, string flagKey) => type.Error(null, ex, flagKey);
  84. #endregion Error
  85. #region Warn
  86. /// <summary>
  87. /// 警告
  88. /// </summary>
  89. /// <param name="type">日志类型</param>
  90. /// <param name="message">消息</param>
  91. /// <param name="ex">异常</param>
  92. /// <param name="flagKey">日志子项索引Key</param>
  93. public static void Warn(this ILogType type, string message, Exception ex, string flagKey) => GetLog(type, flagKey.ToUpper())?.Warn(GetLogMessage(message, ex));
  94. /// <summary>
  95. /// 警告
  96. /// </summary>
  97. /// <param name="type">日志类型</param>
  98. /// <param name="message">消息</param>
  99. /// <param name="flagKey">日志子项索引Key</param>
  100. public static void Warn(this ILogType type, string message, string flagKey) => type.Warn(message, null, flagKey);
  101. /// <summary>
  102. /// 警告
  103. /// </summary>
  104. /// <param name="type">日志类型</param>
  105. /// <param name="ex">异常</param>
  106. /// <param name="flagKey">日志子项索引Key</param>
  107. public static void Warn(this ILogType type, Exception ex, string flagKey) => type.Warn(null, ex, flagKey);
  108. #endregion Warn
  109. /// <summary>
  110. /// 获取详细日志信息
  111. /// </summary>
  112. /// <param name="message">信息</param>
  113. /// <param name="ex">异常</param>
  114. /// <returns>详细信息</returns>
  115. private static string GetLogMessage(string message, Exception ex)
  116. {
  117. if (string.IsNullOrEmpty(message) && ex == null)
  118. return "Unknown error.";
  119. if (string.IsNullOrEmpty(message) && ex != null)
  120. return $"[Type:{ex.GetType().Name}][StackTrace:{ex.StackTrace}][Message:{ex.Message.Replace("\r\n", " ")}]";
  121. if (!string.IsNullOrEmpty(message) && ex == null)
  122. return message;
  123. return $"[Message:{message}][Type:{ex.GetType().Name}][StackTrace:{ex.StackTrace}][Ex Message:{ex.Message.Replace("\r\n", " ")}]";
  124. }
  125. #endregion 写入日志
  126. #region 初始化日志
  127. private static string? _configPath = "Log";
  128. private static int _fileSize = 500;
  129. private static readonly List<ILogType> _initList = new List<ILogType>();
  130. private static readonly LogConfig _configModel = new LogConfig();
  131. private static bool _cleanSet = false;
  132. private static string _previousCleanDay = null;
  133. private static int _cleanDays = 30;
  134. private static Timer _logCleanTimer;
  135. /// <summary>
  136. /// 设置配置信息
  137. /// </summary>
  138. /// <param name="logConfigs">配置信息</param>
  139. public static void SetConfigInfo(LogConfig logConfig)
  140. {
  141. SetConfigPath(logConfig.LogPath);
  142. SetLogFileSize(logConfig.LogSize);
  143. SetLogCleanDays(logConfig.LogDays);
  144. SetConfigInfo(logConfig.Logs);
  145. }
  146. /// <summary>
  147. /// 日志配置
  148. /// </summary>
  149. /// <param name="path"></param>
  150. public static void SetConfigPath(string path)
  151. {
  152. _configPath = path;
  153. }
  154. /// <summary>
  155. /// 设置日志层级关系
  156. /// </summary>
  157. /// <param name="logConfigs">配置信息</param>
  158. public static void SetConfigInfo(List<LogConfigModel> logConfigs)
  159. {
  160. _configModel.Logs = logConfigs;
  161. }
  162. /// <summary>
  163. /// 设置日志项目文件数量和大小
  164. /// </summary>
  165. /// <param name="size">单文件大小(单位MB,最小10)</param>
  166. public static void SetLogFileSize(int size)
  167. {
  168. if (size < 10)
  169. return;
  170. _fileSize = size;
  171. }
  172. /// <summary>
  173. /// 设置日志清理周期
  174. /// </summary>
  175. /// <param name="days">清理周期</param>
  176. public static void SetLogCleanDays(int days)
  177. {
  178. if (days < 7)
  179. return;
  180. _cleanDays = days;
  181. }
  182. /// <summary>
  183. /// 初始化Log组件
  184. /// </summary>
  185. /// <param name="types">日志类型数组</param>
  186. public static void Init(params ILogType[] types)
  187. {
  188. var addedTypes = types.Where(p => !_initList.Contains(p)).ToList();
  189. if (addedTypes.Count == 0)
  190. return;
  191. if (_configModel.Logs == null || _configModel.Logs.Count == 0)
  192. throw new Exception("Log init, config is null.");
  193. _configPath = _configModel.Logs.FirstOrDefault(p => !string.IsNullOrEmpty(p.FileName)).FileName;
  194. XmlDocument xmlDoc = new XmlDocument();
  195. xmlDoc.AppendChild(xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null));
  196. XmlElement configuration = xmlDoc.CreateElement("configuration");
  197. XmlElement root = xmlDoc.CreateElement("log4net");
  198. foreach (var item in addedTypes)
  199. {
  200. _initList.Add(item);
  201. LogConfigModel config = _configModel.Logs.FirstOrDefault(p => p.Name == item.LogName);
  202. if (config is null)
  203. {
  204. config = new LogConfigModel
  205. {
  206. Name = item.LogName,
  207. FileName = _configPath,
  208. SubLogNames = item.SubLogNames
  209. };
  210. }
  211. else
  212. {
  213. if (config.SubLogNames is null)
  214. config.SubLogNames = new Dictionary<string, string>();
  215. foreach (var key in config.SubLogNames.Keys)
  216. {
  217. if (item.SubLogNames != null && item.SubLogNames.ContainsKey(key))
  218. continue;
  219. item.SubLogNames?.Add(key, config.SubLogNames[key]);
  220. }
  221. foreach (var key in item.SubLogNames.Keys)
  222. {
  223. if (config.SubLogNames.ContainsKey(key))
  224. continue;
  225. config.SubLogNames.Add(key, item.SubLogNames[key]);
  226. }
  227. }
  228. if (item.SubLogNames == null || item.SubLogNames.Count == 0)
  229. continue;
  230. CreateXml(xmlDoc, root, config);
  231. }
  232. configuration.AppendChild(root);
  233. xmlDoc.AppendChild(configuration);
  234. //InitRepository.LoggerRepository ??= LogManager.CreateRepository("NETCoreRepository");
  235. if (LoggerRepository == null)
  236. LoggerRepository = LogManager.CreateRepository("NETCoreRepository");
  237. XmlConfigurator.Configure(LoggerRepository, new StreamReader(new MemoryStream(Encoding.ASCII.GetBytes(xmlDoc.OuterXml))).BaseStream);
  238. if (!_cleanSet)
  239. {
  240. _cleanSet = true;
  241. _previousCleanDay = DateTime.Now.ToString("yyyyMMdd");
  242. // clean log
  243. _logCleanTimer = new Timer(1000 * 60);
  244. _logCleanTimer.Elapsed += LogCleanTimer_Elapsed;
  245. _logCleanTimer.Enabled = true;
  246. }
  247. }
  248. /// <summary>
  249. /// 创建XML节点
  250. /// </summary>
  251. /// <param name="xmlDoc">XML文档</param>
  252. /// <param name="root"></param>
  253. /// <param name="config"></param>
  254. private static void CreateXml(XmlDocument xmlDoc, XmlElement root, LogConfigModel config)
  255. {
  256. foreach (var key in config.SubLogNames.Keys)
  257. {
  258. // 创建 Logger
  259. XmlElement logger = xmlDoc.CreateElement("logger");
  260. logger.SetAttribute("name", config.SubLogNames[key]);
  261. XmlElement level = xmlDoc.CreateElement("level");
  262. level.SetAttribute("value", "ALL");
  263. XmlElement appender_ref = xmlDoc.CreateElement("appender-ref");
  264. appender_ref.SetAttribute("ref", $"{config.SubLogNames[key]}Appender");
  265. logger.AppendChild(level);
  266. logger.AppendChild(appender_ref);
  267. // 创建 Appender
  268. XmlElement appender = xmlDoc.CreateElement("appender");
  269. appender.SetAttribute("name", $"{config.SubLogNames[key]}Appender");
  270. appender.SetAttribute("type", "log4net.Appender.RollingFileAppender");
  271. XmlElement param = xmlDoc.CreateElement("param");
  272. param.SetAttribute("name", "Encoding");
  273. param.SetAttribute("value", "utf-8");
  274. appender.AppendChild(param);
  275. XmlElement file = xmlDoc.CreateElement("file");
  276. file.SetAttribute("value", Path.Combine(config.FileName, config.Name));
  277. appender.AppendChild(file);
  278. XmlElement appendToFile = xmlDoc.CreateElement("appendToFile");
  279. appendToFile.SetAttribute("value", "true");
  280. appender.AppendChild(appendToFile);
  281. XmlElement rollingStyle = xmlDoc.CreateElement("rollingStyle");
  282. rollingStyle.SetAttribute("value", "Composite");
  283. appender.AppendChild(rollingStyle);
  284. XmlElement maxSizeRollBackups = xmlDoc.CreateElement("maxSizeRollBackups");
  285. maxSizeRollBackups.SetAttribute("value", "-1");
  286. appender.AppendChild(maxSizeRollBackups);
  287. XmlElement maximumFileSize = xmlDoc.CreateElement("maximumFileSize");
  288. maximumFileSize.SetAttribute("value", $"{_fileSize}MB");
  289. appender.AppendChild(maximumFileSize);
  290. XmlElement lockingModel = xmlDoc.CreateElement("lockingModel");
  291. lockingModel.SetAttribute("type", "log4net.Appender.FileAppender+MinimalLock");
  292. appender.AppendChild(lockingModel);
  293. XmlElement staticLogFileName = xmlDoc.CreateElement("staticLogFileName");
  294. staticLogFileName.SetAttribute("value", "false");
  295. appender.AppendChild(staticLogFileName);
  296. XmlElement DatePattern = xmlDoc.CreateElement("DatePattern");
  297. DatePattern.SetAttribute("value", $"/yyyyMMdd/'{config.SubLogNames[key]}.log'");
  298. appender.AppendChild(DatePattern);
  299. XmlElement layout = xmlDoc.CreateElement("layout");
  300. layout.SetAttribute("type", "log4net.Layout.PatternLayout");
  301. XmlElement conversionPattern = xmlDoc.CreateElement("conversionPattern");
  302. conversionPattern.SetAttribute("value", "%date [%thread] %-5level - %message%newline");
  303. layout.AppendChild(conversionPattern);
  304. appender.AppendChild(layout);
  305. root.AppendChild(appender);
  306. root.AppendChild(logger);
  307. }
  308. }
  309. private static void LogCleanTimer_Elapsed(object sender, ElapsedEventArgs e)
  310. {
  311. try
  312. {
  313. if (_previousCleanDay.Equals(DateTime.Now.ToString("yyyyMMdd")))
  314. return;
  315. _previousCleanDay = DateTime.Now.ToString("yyyyMMdd");
  316. if (!Directory.Exists(_configPath))
  317. return;
  318. string[] typeDirs = Directory.GetDirectories(_configPath);
  319. for (int i = 0; i < typeDirs.Length; i++)
  320. {
  321. string[] dateDirs = Directory.GetDirectories(typeDirs[i]);
  322. for (int j = 0; j < dateDirs.Length; j++)
  323. {
  324. string dirName = dateDirs[j].Substring(dateDirs[j].LastIndexOf('\\') + 1);
  325. if (Convert.ToInt32(dirName) < Convert.ToInt32(DateTime.Now.AddDays(_cleanDays * -1).ToString("yyyyMMdd")))
  326. Directory.Delete(dateDirs[j], true);
  327. }
  328. }
  329. }
  330. catch (Exception ex)
  331. {
  332. //LogInfo.Log.Info(ex.Message, ex, "FATAL");
  333. }
  334. }
  335. #endregion 初始化日志
  336. }
  337. }