DatabaseLoggingWriter.cs 10 KB

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