DatabaseLoggingWriter.cs 11 KB

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