DatabaseLoggingWriter.cs 11 KB

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