DatabaseLoggingWriter.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. // 大名科技(天津)有限公司 版权所有
  2. //
  3. // 此源代码遵循位于源代码树根目录中的 LICENSE 文件的许可证
  4. //
  5. // 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动
  6. //
  7. // 任何基于本项目二次开发而产生的一切法律纠纷和责任,均与作者无关
  8. using IPTools.Core;
  9. namespace Admin.NET.Core;
  10. /// <summary>
  11. /// 数据库日志写入器
  12. /// </summary>
  13. public class DatabaseLoggingWriter : IDatabaseLoggingWriter, IDisposable
  14. {
  15. private readonly IServiceScope _serviceScope;
  16. private readonly ISqlSugarClient _db;
  17. private readonly SysConfigService _sysConfigService; // 参数配置服务
  18. private readonly ILogger<DatabaseLoggingWriter> _logger; // 日志组件
  19. public DatabaseLoggingWriter(IServiceScopeFactory scopeFactory)
  20. {
  21. _serviceScope = scopeFactory.CreateScope();
  22. //_db = _serviceScope.ServiceProvider.GetRequiredService<ISqlSugarClient>();
  23. _sysConfigService = _serviceScope.ServiceProvider.GetRequiredService<SysConfigService>();
  24. _logger = _serviceScope.ServiceProvider.GetRequiredService<ILogger<DatabaseLoggingWriter>>();
  25. // 切换日志独立数据库
  26. _db = SqlSugarSetup.ITenant.IsAnyConnection(SqlSugarConst.LogConfigId)
  27. ? SqlSugarSetup.ITenant.GetConnectionScope(SqlSugarConst.LogConfigId)
  28. : SqlSugarSetup.ITenant.GetConnectionScope(SqlSugarConst.MainConfigId);
  29. }
  30. public async Task WriteAsync(LogMessage logMsg, bool flush)
  31. {
  32. var jsonStr = logMsg.Context?.Get("loggingMonitor")?.ToString();
  33. if (jsonStr == null)
  34. {
  35. await _db.Insertable(new SysLogOp
  36. {
  37. DisplayTitle = "自定义操作日志",
  38. LogDateTime = logMsg.LogDateTime,
  39. EventId = logMsg.EventId.Id,
  40. ThreadId = logMsg.ThreadId,
  41. TraceId = logMsg.TraceId,
  42. Exception = logMsg.Exception == null ? null : JSON.Serialize(logMsg.Exception),
  43. Message = logMsg.Message,
  44. LogLevel = logMsg.LogLevel
  45. }).ExecuteCommandAsync();
  46. return;
  47. }
  48. var loggingMonitor = JSON.Deserialize<dynamic>(jsonStr);
  49. // 不记录数据校验日志
  50. if (loggingMonitor.validation != null) return;
  51. // 获取当前操作者
  52. string account = "", realName = "", userId = "", tenantId = "";
  53. if (loggingMonitor.authorizationClaims != null)
  54. {
  55. foreach (var item in loggingMonitor.authorizationClaims)
  56. {
  57. if (item.type == ClaimConst.Account)
  58. account = item.value;
  59. if (item.type == ClaimConst.RealName)
  60. realName = item.value;
  61. if (item.type == ClaimConst.TenantId)
  62. tenantId = item.value;
  63. if (item.type == ClaimConst.UserId)
  64. userId = item.value;
  65. }
  66. }
  67. string remoteIPv4 = loggingMonitor.remoteIPv4;
  68. (string ipLocation, double? longitude, double? latitude) = GetIpAddress(remoteIPv4);
  69. var client = Parser.GetDefault().Parse(loggingMonitor.userAgent.ToString());
  70. var browser = $"{client.UA.Family} {client.UA.Major}.{client.UA.Minor} / {client.Device.Family}";
  71. var os = $"{client.OS.Family} {client.OS.Major} {client.OS.Minor}";
  72. // 捕捉异常,否则会由于 unhandled exception 导致程序崩溃
  73. try
  74. {
  75. // 记录异常日志-发送邮件
  76. if (logMsg.Exception != null || loggingMonitor.exception != null)
  77. {
  78. await _db.Insertable(new SysLogEx
  79. {
  80. ControllerName = loggingMonitor.controllerName,
  81. ActionName = loggingMonitor.actionTypeName,
  82. DisplayTitle = loggingMonitor.displayTitle,
  83. Status = loggingMonitor.returnInformation?.httpStatusCode,
  84. RemoteIp = remoteIPv4,
  85. Location = ipLocation,
  86. Longitude = longitude,
  87. Latitude = latitude,
  88. Browser = browser, // loggingMonitor.userAgent,
  89. Os = os, // loggingMonitor.osDescription + " " + loggingMonitor.osArchitecture,
  90. Elapsed = loggingMonitor.timeOperationElapsedMilliseconds,
  91. LogDateTime = logMsg.LogDateTime,
  92. Account = account,
  93. RealName = realName,
  94. HttpMethod = loggingMonitor.httpMethod,
  95. RequestUrl = loggingMonitor.requestUrl,
  96. RequestParam = (loggingMonitor.parameters == null || loggingMonitor.parameters.Count == 0) ? null : JSON.Serialize(loggingMonitor.parameters[0].value),
  97. ReturnResult = loggingMonitor.returnInformation == null ? null : JSON.Serialize(loggingMonitor.returnInformation),
  98. EventId = logMsg.EventId.Id,
  99. ThreadId = logMsg.ThreadId,
  100. TraceId = logMsg.TraceId,
  101. Exception = JSON.Serialize(loggingMonitor.exception),
  102. Message = logMsg.Message,
  103. CreateUserId = string.IsNullOrWhiteSpace(userId) ? 0 : long.Parse(userId),
  104. TenantId = string.IsNullOrWhiteSpace(tenantId) ? 0 : long.Parse(tenantId),
  105. LogLevel = logMsg.LogLevel
  106. }).ExecuteCommandAsync();
  107. // 将异常日志发送到邮件
  108. if (await _sysConfigService.GetConfigValue<bool>(CommonConst.SysErrorMail))
  109. {
  110. await App.GetRequiredService<IEventPublisher>().PublishAsync("Send:ErrorMail", loggingMonitor.exception);
  111. }
  112. return;
  113. }
  114. // 记录访问日志-登录退出
  115. if (loggingMonitor.actionName == "userInfo" || loggingMonitor.actionName == "logout")
  116. {
  117. await _db.Insertable(new SysLogVis
  118. {
  119. ControllerName = loggingMonitor.controllerName,
  120. ActionName = loggingMonitor.actionTypeName,
  121. DisplayTitle = loggingMonitor.displayTitle,
  122. Status = loggingMonitor.returnInformation?.httpStatusCode,
  123. RemoteIp = remoteIPv4,
  124. Location = ipLocation,
  125. Longitude = longitude,
  126. Latitude = latitude,
  127. Browser = browser, // loggingMonitor.userAgent,
  128. Os = os, // loggingMonitor.osDescription + " " + loggingMonitor.osArchitecture,
  129. Elapsed = loggingMonitor.timeOperationElapsedMilliseconds,
  130. LogDateTime = logMsg.LogDateTime,
  131. Account = account,
  132. RealName = realName,
  133. CreateUserId = string.IsNullOrWhiteSpace(userId) ? 0 : long.Parse(userId),
  134. TenantId = string.IsNullOrWhiteSpace(tenantId) ? 0 : long.Parse(tenantId),
  135. LogLevel = logMsg.LogLevel
  136. }).ExecuteCommandAsync();
  137. return;
  138. }
  139. // 记录操作日志
  140. if (!(await _sysConfigService.GetConfigValue<bool>(CommonConst.SysOpLog))) return;
  141. await _db.Insertable(new SysLogOp
  142. {
  143. ControllerName = loggingMonitor.controllerName,
  144. ActionName = loggingMonitor.actionTypeName,
  145. DisplayTitle = loggingMonitor.displayTitle,
  146. Status = loggingMonitor.returnInformation?.httpStatusCode,
  147. RemoteIp = remoteIPv4,
  148. Location = ipLocation,
  149. Longitude = longitude,
  150. Latitude = latitude,
  151. Browser = browser, // loggingMonitor.userAgent,
  152. Os = os, // loggingMonitor.osDescription + " " + loggingMonitor.osArchitecture,
  153. Elapsed = loggingMonitor.timeOperationElapsedMilliseconds,
  154. LogDateTime = logMsg.LogDateTime,
  155. Account = account,
  156. RealName = realName,
  157. HttpMethod = loggingMonitor.httpMethod,
  158. RequestUrl = loggingMonitor.requestUrl,
  159. RequestParam = (loggingMonitor.parameters == null || loggingMonitor.parameters.Count == 0) ? null : JSON.Serialize(loggingMonitor.parameters[0].value),
  160. ReturnResult = loggingMonitor.returnInformation == null ? null : JSON.Serialize(loggingMonitor.returnInformation),
  161. EventId = logMsg.EventId.Id,
  162. ThreadId = logMsg.ThreadId,
  163. TraceId = logMsg.TraceId,
  164. Exception = loggingMonitor.exception == null ? null : JSON.Serialize(loggingMonitor.exception),
  165. Message = logMsg.Message,
  166. CreateUserId = string.IsNullOrWhiteSpace(userId) ? 0 : long.Parse(userId),
  167. TenantId = string.IsNullOrWhiteSpace(tenantId) ? 0 : long.Parse(tenantId),
  168. LogLevel = logMsg.LogLevel
  169. }).ExecuteCommandAsync();
  170. await Task.Delay(50); // 延迟 0.05 秒写入数据库,有效减少高频写入数据库导致死锁问题
  171. }
  172. catch (Exception ex)
  173. {
  174. _logger.LogError(ex, "操作日志入库");
  175. }
  176. }
  177. /// <summary>
  178. /// 解析IP地址
  179. /// </summary>
  180. /// <param name="ip"></param>
  181. /// <returns></returns>
  182. internal static (string ipLocation, double? longitude, double? latitude) GetIpAddress(string ip)
  183. {
  184. try
  185. {
  186. var ipInfo = IpTool.SearchWithI18N(ip); // 国际化查询,默认中文 中文zh-CN、英文en
  187. var addressList = new List<string>() { ipInfo.Country, ipInfo.Province, ipInfo.City, ipInfo.NetworkOperator };
  188. return (string.Join(" ", addressList.Where(u => u != "0" && !string.IsNullOrWhiteSpace(u)).ToList()), ipInfo.Longitude, ipInfo.Latitude); // 去掉0及空并用空格连接
  189. }
  190. catch
  191. {
  192. // 不做处理
  193. }
  194. return ("未知", 0, 0);
  195. }
  196. /// <summary>
  197. /// 释放服务作用域
  198. /// </summary>
  199. public void Dispose()
  200. {
  201. _serviceScope.Dispose();
  202. }
  203. }