DatabaseLoggingWriter.cs 9.7 KB

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