DatabaseLoggingWriter.cs 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  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) return;
  34. var loggingMonitor = JSON.Deserialize<dynamic>(jsonStr);
  35. // 不记录数据校验日志
  36. if (loggingMonitor.validation != null) return;
  37. // 获取当前操作者
  38. string account = "", realName = "", userId = "", tenantId = "";
  39. if (loggingMonitor.authorizationClaims != null)
  40. {
  41. foreach (var item in loggingMonitor.authorizationClaims)
  42. {
  43. if (item.type == ClaimConst.Account)
  44. account = item.value;
  45. if (item.type == ClaimConst.RealName)
  46. realName = item.value;
  47. if (item.type == ClaimConst.TenantId)
  48. tenantId = item.value;
  49. if (item.type == ClaimConst.UserId)
  50. userId = item.value;
  51. }
  52. }
  53. string remoteIPv4 = loggingMonitor.remoteIPv4;
  54. (string ipLocation, double? longitude, double? latitude) = GetIpAddress(remoteIPv4);
  55. var client = Parser.GetDefault().Parse(loggingMonitor.userAgent.ToString());
  56. var browser = $"{client.UA.Family} {client.UA.Major}.{client.UA.Minor} / {client.Device.Family}";
  57. var os = $"{client.OS.Family} {client.OS.Major} {client.OS.Minor}";
  58. // 捕捉异常,否则会由于 unhandled exception 导致程序崩溃
  59. try
  60. {
  61. // 记录异常日志并发送邮件
  62. if (logMsg.Exception != null || loggingMonitor.exception != null)
  63. {
  64. await _db.Insertable(new SysLogEx
  65. {
  66. ControllerName = loggingMonitor.controllerName,
  67. ActionName = loggingMonitor.actionTypeName,
  68. DisplayTitle = loggingMonitor.displayTitle,
  69. Status = loggingMonitor.returnInformation?.httpStatusCode,
  70. RemoteIp = remoteIPv4,
  71. Location = ipLocation,
  72. Longitude = longitude,
  73. Latitude = latitude,
  74. Browser = browser, // loggingMonitor.userAgent,
  75. Os = os, // loggingMonitor.osDescription + " " + loggingMonitor.osArchitecture,
  76. Elapsed = loggingMonitor.timeOperationElapsedMilliseconds,
  77. LogDateTime = logMsg.LogDateTime,
  78. Account = account,
  79. RealName = realName,
  80. HttpMethod = loggingMonitor.httpMethod,
  81. RequestUrl = loggingMonitor.requestUrl,
  82. RequestParam = (loggingMonitor.parameters == null || loggingMonitor.parameters.Count == 0) ? null : JSON.Serialize(loggingMonitor.parameters[0].value),
  83. ReturnResult = loggingMonitor.returnInformation == null ? null : JSON.Serialize(loggingMonitor.returnInformation),
  84. EventId = logMsg.EventId.Id,
  85. ThreadId = logMsg.ThreadId,
  86. TraceId = logMsg.TraceId,
  87. Exception = JSON.Serialize(loggingMonitor.exception),
  88. Message = logMsg.Message,
  89. CreateUserId = string.IsNullOrWhiteSpace(userId) ? 0 : long.Parse(userId),
  90. TenantId = string.IsNullOrWhiteSpace(tenantId) ? 0 : long.Parse(tenantId),
  91. LogLevel = logMsg.LogLevel
  92. }).ExecuteCommandAsync();
  93. // 将异常日志发送到邮件
  94. if (await _sysConfigService.GetConfigValue<bool>(CommonConst.SysErrorMail))
  95. {
  96. await App.GetRequiredService<IEventPublisher>().PublishAsync("Send:ErrorMail", loggingMonitor.exception);
  97. }
  98. return;
  99. }
  100. // 记录访问日志-登录退出
  101. if (loggingMonitor.actionName == "userInfo" || loggingMonitor.actionName == "logout")
  102. {
  103. await _db.Insertable(new SysLogVis
  104. {
  105. ControllerName = loggingMonitor.controllerName,
  106. ActionName = loggingMonitor.actionTypeName,
  107. DisplayTitle = loggingMonitor.displayTitle,
  108. Status = loggingMonitor.returnInformation?.httpStatusCode,
  109. RemoteIp = remoteIPv4,
  110. Location = ipLocation,
  111. Longitude = longitude,
  112. Latitude = latitude,
  113. Browser = browser, // loggingMonitor.userAgent,
  114. Os = os, // loggingMonitor.osDescription + " " + loggingMonitor.osArchitecture,
  115. Elapsed = loggingMonitor.timeOperationElapsedMilliseconds,
  116. LogDateTime = logMsg.LogDateTime,
  117. Account = account,
  118. RealName = realName,
  119. CreateUserId = string.IsNullOrWhiteSpace(userId) ? 0 : long.Parse(userId),
  120. TenantId = string.IsNullOrWhiteSpace(tenantId) ? 0 : long.Parse(tenantId),
  121. LogLevel = logMsg.LogLevel
  122. }).ExecuteCommandAsync();
  123. return;
  124. }
  125. // 记录操作日志
  126. if (!(await _sysConfigService.GetConfigValue<bool>(CommonConst.SysOpLog))) return;
  127. await _db.Insertable(new SysLogOp
  128. {
  129. ControllerName = loggingMonitor.controllerName,
  130. ActionName = loggingMonitor.actionTypeName,
  131. DisplayTitle = loggingMonitor.displayTitle,
  132. Status = loggingMonitor.returnInformation?.httpStatusCode,
  133. RemoteIp = remoteIPv4,
  134. Location = ipLocation,
  135. Longitude = longitude,
  136. Latitude = latitude,
  137. Browser = browser, // loggingMonitor.userAgent,
  138. Os = os, // loggingMonitor.osDescription + " " + loggingMonitor.osArchitecture,
  139. Elapsed = loggingMonitor.timeOperationElapsedMilliseconds,
  140. LogDateTime = logMsg.LogDateTime,
  141. Account = account,
  142. RealName = realName,
  143. HttpMethod = loggingMonitor.httpMethod,
  144. RequestUrl = loggingMonitor.requestUrl,
  145. RequestParam = (loggingMonitor.parameters == null || loggingMonitor.parameters.Count == 0) ? null : JSON.Serialize(loggingMonitor.parameters[0].value),
  146. ReturnResult = loggingMonitor.returnInformation == null ? null : JSON.Serialize(loggingMonitor.returnInformation),
  147. EventId = logMsg.EventId.Id,
  148. ThreadId = logMsg.ThreadId,
  149. TraceId = logMsg.TraceId,
  150. Exception = loggingMonitor.exception == null ? null : JSON.Serialize(loggingMonitor.exception),
  151. Message = logMsg.Message,
  152. CreateUserId = string.IsNullOrWhiteSpace(userId) ? 0 : long.Parse(userId),
  153. TenantId = string.IsNullOrWhiteSpace(tenantId) ? 0 : long.Parse(tenantId),
  154. LogLevel = logMsg.LogLevel
  155. }).ExecuteCommandAsync();
  156. await Task.Delay(50); // 延迟 0.05 秒写入数据库,有效减少高频写入数据库导致死锁问题
  157. }
  158. catch (Exception ex)
  159. {
  160. _logger.LogError(ex, ex.Message);
  161. }
  162. }
  163. /// <summary>
  164. /// 解析IP地址
  165. /// </summary>
  166. /// <param name="ip"></param>
  167. /// <returns></returns>
  168. internal static (string ipLocation, double? longitude, double? latitude) GetIpAddress(string ip)
  169. {
  170. try
  171. {
  172. var ipInfo = IpTool.SearchWithI18N(ip); // 国际化查询,默认中文 中文zh-CN、英文en
  173. var addressList = new List<string>() { ipInfo.Country, ipInfo.Province, ipInfo.City, ipInfo.NetworkOperator };
  174. return (string.Join(" ", addressList.Where(u => u != "0" && !string.IsNullOrWhiteSpace(u)).ToList()), ipInfo.Longitude, ipInfo.Latitude); // 去掉0及空并用空格连接
  175. }
  176. catch
  177. {
  178. // 不做处理
  179. }
  180. return ("未知", 0, 0);
  181. }
  182. /// <summary>
  183. /// 释放服务作用域
  184. /// </summary>
  185. public void Dispose()
  186. {
  187. _serviceScope.Dispose();
  188. }
  189. }