DatabaseLoggingWriter.cs 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. // 麻省理工学院许可证
  2. //
  3. // 版权所有 (c) 2021-2023 zuohuaijun,大名科技(天津)有限公司 联系电话/微信:18020030720 QQ:515096995
  4. //
  5. // 特此免费授予获得本软件的任何人以处理本软件的权利,但须遵守以下条件:在所有副本或重要部分的软件中必须包括上述版权声明和本许可声明。
  6. //
  7. // 软件按“原样”提供,不提供任何形式的明示或暗示的保证,包括但不限于对适销性、适用性和非侵权的保证。
  8. // 在任何情况下,作者或版权持有人均不对任何索赔、损害或其他责任负责,无论是因合同、侵权或其他方式引起的,与软件或其使用或其他交易有关。
  9. using IPTools.Core;
  10. namespace Admin.NET.Core;
  11. /// <summary>
  12. /// 数据库日志写入器
  13. /// </summary>
  14. public class DatabaseLoggingWriter : IDatabaseLoggingWriter, IDisposable
  15. {
  16. private readonly IServiceScope _serviceScope;
  17. private readonly SqlSugarRepository<SysLogVis> _sysLogVisRep; // 访问日志
  18. private readonly SqlSugarRepository<SysLogOp> _sysLogOpRep; // 操作日志
  19. private readonly SqlSugarRepository<SysLogEx> _sysLogExRep; // 异常日志
  20. private readonly SysConfigService _sysConfigService; // 参数配置服务
  21. private readonly ILogger<DatabaseLoggingWriter> _logger; // 日志组件
  22. public DatabaseLoggingWriter(IServiceScopeFactory scopeFactory)
  23. {
  24. _serviceScope = scopeFactory.CreateScope();
  25. _sysLogVisRep = _serviceScope.ServiceProvider.GetRequiredService<SqlSugarRepository<SysLogVis>>();
  26. _sysLogOpRep = _serviceScope.ServiceProvider.GetRequiredService<SqlSugarRepository<SysLogOp>>();
  27. _sysLogExRep = _serviceScope.ServiceProvider.GetRequiredService<SqlSugarRepository<SysLogEx>>();
  28. _sysConfigService = _serviceScope.ServiceProvider.GetRequiredService<SysConfigService>();
  29. _logger = _serviceScope.ServiceProvider.GetRequiredService<ILogger<DatabaseLoggingWriter>>();
  30. }
  31. public async void Write(LogMessage logMsg, bool flush)
  32. {
  33. var jsonStr = logMsg.Context?.Get("loggingMonitor")?.ToString();
  34. if (jsonStr == null) return;
  35. var loggingMonitor = JSON.Deserialize<dynamic>(jsonStr);
  36. // 不记录数据校验日志
  37. if (loggingMonitor.validation != null) return;
  38. // 获取当前操作者
  39. string account = "", realName = "", userId = "", tenantId = "";
  40. if (loggingMonitor.authorizationClaims != null)
  41. {
  42. foreach (var item in loggingMonitor.authorizationClaims)
  43. {
  44. if (item.type == ClaimConst.Account)
  45. account = item.value;
  46. if (item.type == ClaimConst.RealName)
  47. realName = item.value;
  48. if (item.type == ClaimConst.TenantId)
  49. tenantId = item.value;
  50. if (item.type == ClaimConst.UserId)
  51. userId = item.value;
  52. }
  53. }
  54. string remoteIPv4 = loggingMonitor.remoteIPv4;
  55. (string ipLocation, double? longitude, double? latitude) = GetIpAddress(remoteIPv4);
  56. var client = Parser.GetDefault().Parse(loggingMonitor.userAgent.ToString());
  57. var browser = $"{client.UA.Family} {client.UA.Major}.{client.UA.Minor} / {client.Device.Family}";
  58. var os = $"{client.OS.Family} {client.OS.Major} {client.OS.Minor}";
  59. // 捕捉异常,否则会由于 unhandled exception 导致程序崩溃
  60. try
  61. {
  62. // 记录异常日志并发送邮件
  63. if (logMsg.Exception != null || loggingMonitor.exception != null)
  64. {
  65. await _sysLogExRep.InsertAsync(new SysLogEx
  66. {
  67. ControllerName = loggingMonitor.controllerName,
  68. ActionName = loggingMonitor.actionTypeName,
  69. DisplayTitle = loggingMonitor.displayTitle,
  70. Status = loggingMonitor.returnInformation?.httpStatusCode,
  71. RemoteIp = remoteIPv4,
  72. Location = ipLocation,
  73. Longitude = longitude,
  74. Latitude = latitude,
  75. Browser = browser, // loggingMonitor.userAgent,
  76. Os = os, // loggingMonitor.osDescription + " " + loggingMonitor.osArchitecture,
  77. Elapsed = loggingMonitor.timeOperationElapsedMilliseconds,
  78. LogDateTime = logMsg.LogDateTime,
  79. Account = account,
  80. RealName = realName,
  81. HttpMethod = loggingMonitor.httpMethod,
  82. RequestUrl = loggingMonitor.requestUrl,
  83. RequestParam = (loggingMonitor.parameters == null || loggingMonitor.parameters.Count == 0) ? null : JSON.Serialize(loggingMonitor.parameters[0].value),
  84. ReturnResult = loggingMonitor.returnInformation == null ? null : JSON.Serialize(loggingMonitor.returnInformation),
  85. EventId = logMsg.EventId.Id,
  86. ThreadId = logMsg.ThreadId,
  87. TraceId = logMsg.TraceId,
  88. Exception = JSON.Serialize(loggingMonitor.exception),
  89. Message = logMsg.Message,
  90. CreateUserId = string.IsNullOrWhiteSpace(userId) ? 0 : long.Parse(userId),
  91. TenantId = string.IsNullOrWhiteSpace(tenantId) ? 0 : long.Parse(tenantId),
  92. LogLevel = logMsg.LogLevel
  93. });
  94. // 将异常日志发送到邮件
  95. await App.GetRequiredService<IEventPublisher>().PublishAsync("Send:ErrorMail", loggingMonitor.exception);
  96. return;
  97. }
  98. // 记录访问日志-登录登出
  99. if (loggingMonitor.actionName == "userInfo" || loggingMonitor.actionName == "logout")
  100. {
  101. await _sysLogVisRep.InsertAsync(new SysLogVis
  102. {
  103. ControllerName = loggingMonitor.controllerName,
  104. ActionName = loggingMonitor.actionTypeName,
  105. DisplayTitle = loggingMonitor.displayTitle,
  106. Status = loggingMonitor.returnInformation?.httpStatusCode,
  107. RemoteIp = remoteIPv4,
  108. Location = ipLocation,
  109. Longitude = longitude,
  110. Latitude = latitude,
  111. Browser = browser, // loggingMonitor.userAgent,
  112. Os = os, // loggingMonitor.osDescription + " " + loggingMonitor.osArchitecture,
  113. Elapsed = loggingMonitor.timeOperationElapsedMilliseconds,
  114. LogDateTime = logMsg.LogDateTime,
  115. Account = account,
  116. RealName = realName,
  117. CreateUserId = string.IsNullOrWhiteSpace(userId) ? 0 : long.Parse(userId),
  118. TenantId = string.IsNullOrWhiteSpace(tenantId) ? 0 : long.Parse(tenantId),
  119. LogLevel = logMsg.LogLevel
  120. });
  121. return;
  122. }
  123. // 记录操作日志
  124. var enabledSysOpLog = await _sysConfigService.GetConfigValue<bool>(CommonConst.SysOpLog);
  125. if (!enabledSysOpLog) return;
  126. await _sysLogOpRep.InsertAsync(new SysLogOp
  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. HttpMethod = loggingMonitor.httpMethod,
  143. RequestUrl = loggingMonitor.requestUrl,
  144. RequestParam = (loggingMonitor.parameters == null || loggingMonitor.parameters.Count == 0) ? null : JSON.Serialize(loggingMonitor.parameters[0].value),
  145. ReturnResult = loggingMonitor.returnInformation == null ? null : JSON.Serialize(loggingMonitor.returnInformation),
  146. EventId = logMsg.EventId.Id,
  147. ThreadId = logMsg.ThreadId,
  148. TraceId = logMsg.TraceId,
  149. Exception = loggingMonitor.exception == null ? null : JSON.Serialize(loggingMonitor.exception),
  150. Message = logMsg.Message,
  151. CreateUserId = string.IsNullOrWhiteSpace(userId) ? 0 : long.Parse(userId),
  152. TenantId = string.IsNullOrWhiteSpace(tenantId) ? 0 : long.Parse(tenantId),
  153. LogLevel = logMsg.LogLevel
  154. });
  155. }
  156. catch (Exception ex)
  157. {
  158. _logger.LogError(ex, ex.Message);
  159. }
  160. }
  161. /// <summary>
  162. /// 解析IP地址
  163. /// </summary>
  164. /// <param name="ip"></param>
  165. /// <returns></returns>
  166. internal static (string ipLocation, double? longitude, double? latitude) GetIpAddress(string ip)
  167. {
  168. try
  169. {
  170. var ipInfo = IpTool.Search(ip);
  171. var addressList = new List<string>() { ipInfo.Country, ipInfo.Province, ipInfo.City, ipInfo.NetworkOperator };
  172. return (string.Join("|", addressList.Where(it => it != "0").ToList()), ipInfo.Longitude, ipInfo.Latitude); // 去掉0并用|连接
  173. }
  174. catch
  175. {
  176. // 不做处理
  177. }
  178. return ("未知", 0, 0);
  179. }
  180. /// <summary>
  181. /// 释放服务作用域
  182. /// </summary>
  183. public void Dispose()
  184. {
  185. _serviceScope.Dispose();
  186. }
  187. }