DatabaseLoggingWriter.cs 9.1 KB

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