DatabaseLoggingWriter.cs 10 KB

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