DatabaseLoggingWriter.cs 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  1. // 大名科技(天津)有限公司版权所有 电话:18020030720 QQ:515096995
  2. //
  3. // 此源代码遵循位于源代码树根目录中的 LICENSE 文件的许可证
  4. using IPTools.Core;
  5. namespace Admin.NET.Core;
  6. /// <summary>
  7. /// 数据库日志写入器
  8. /// </summary>
  9. public class DatabaseLoggingWriter : IDatabaseLoggingWriter, IDisposable
  10. {
  11. private readonly IServiceScope _serviceScope;
  12. private readonly SqlSugarRepository<SysLogVis> _sysLogVisRep; // 访问日志
  13. private readonly SqlSugarRepository<SysLogOp> _sysLogOpRep; // 操作日志
  14. private readonly SqlSugarRepository<SysLogEx> _sysLogExRep; // 异常日志
  15. private readonly SysConfigService _sysConfigService; // 参数配置服务
  16. private readonly ILogger<DatabaseLoggingWriter> _logger; // 日志组件
  17. public DatabaseLoggingWriter(IServiceScopeFactory scopeFactory)
  18. {
  19. _serviceScope = scopeFactory.CreateScope();
  20. _sysLogVisRep = _serviceScope.ServiceProvider.GetRequiredService<SqlSugarRepository<SysLogVis>>();
  21. _sysLogOpRep = _serviceScope.ServiceProvider.GetRequiredService<SqlSugarRepository<SysLogOp>>();
  22. _sysLogExRep = _serviceScope.ServiceProvider.GetRequiredService<SqlSugarRepository<SysLogEx>>();
  23. _sysConfigService = _serviceScope.ServiceProvider.GetRequiredService<SysConfigService>();
  24. _logger = _serviceScope.ServiceProvider.GetRequiredService<ILogger<DatabaseLoggingWriter>>();
  25. }
  26. public async void Write(LogMessage logMsg, bool flush)
  27. {
  28. var jsonStr = logMsg.Context?.Get("loggingMonitor")?.ToString();
  29. if (jsonStr == null) return;
  30. var loggingMonitor = JSON.Deserialize<dynamic>(jsonStr);
  31. // 不记录数据校验日志
  32. if (loggingMonitor.validation != null) return;
  33. // 获取当前操作者
  34. string account = "", realName = "", userId = "", tenantId = "";
  35. if (loggingMonitor.authorizationClaims != null)
  36. {
  37. foreach (var item in loggingMonitor.authorizationClaims)
  38. {
  39. if (item.type == ClaimConst.Account)
  40. account = item.value;
  41. if (item.type == ClaimConst.RealName)
  42. realName = item.value;
  43. if (item.type == ClaimConst.TenantId)
  44. tenantId = item.value;
  45. if (item.type == ClaimConst.UserId)
  46. userId = item.value;
  47. }
  48. }
  49. string remoteIPv4 = loggingMonitor.remoteIPv4;
  50. (string ipLocation, double? longitude, double? latitude) = GetIpAddress(remoteIPv4);
  51. var client = Parser.GetDefault().Parse(loggingMonitor.userAgent.ToString());
  52. var browser = $"{client.UA.Family} {client.UA.Major}.{client.UA.Minor} / {client.Device.Family}";
  53. var os = $"{client.OS.Family} {client.OS.Major} {client.OS.Minor}";
  54. // 捕捉异常,否则会由于 unhandled exception 导致程序崩溃
  55. try
  56. {
  57. // 记录异常日志并发送邮件
  58. if (logMsg.Exception != null || loggingMonitor.exception != null)
  59. {
  60. await _sysLogExRep.InsertAsync(new SysLogEx
  61. {
  62. ControllerName = loggingMonitor.controllerName,
  63. ActionName = loggingMonitor.actionTypeName,
  64. DisplayTitle = loggingMonitor.displayTitle,
  65. Status = loggingMonitor.returnInformation?.httpStatusCode,
  66. RemoteIp = remoteIPv4,
  67. Location = ipLocation,
  68. Longitude = longitude,
  69. Latitude = latitude,
  70. Browser = browser, // loggingMonitor.userAgent,
  71. Os = os, // loggingMonitor.osDescription + " " + loggingMonitor.osArchitecture,
  72. Elapsed = loggingMonitor.timeOperationElapsedMilliseconds,
  73. LogDateTime = logMsg.LogDateTime,
  74. Account = account,
  75. RealName = realName,
  76. HttpMethod = loggingMonitor.httpMethod,
  77. RequestUrl = loggingMonitor.requestUrl,
  78. RequestParam = (loggingMonitor.parameters == null || loggingMonitor.parameters.Count == 0) ? null : JSON.Serialize(loggingMonitor.parameters[0].value),
  79. ReturnResult = loggingMonitor.returnInformation == null ? null : JSON.Serialize(loggingMonitor.returnInformation),
  80. EventId = logMsg.EventId.Id,
  81. ThreadId = logMsg.ThreadId,
  82. TraceId = logMsg.TraceId,
  83. Exception = JSON.Serialize(loggingMonitor.exception),
  84. Message = logMsg.Message,
  85. CreateUserId = string.IsNullOrWhiteSpace(userId) ? 0 : long.Parse(userId),
  86. TenantId = string.IsNullOrWhiteSpace(tenantId) ? 0 : long.Parse(tenantId),
  87. LogLevel = logMsg.LogLevel
  88. });
  89. // 将异常日志发送到邮件
  90. await App.GetRequiredService<IEventPublisher>().PublishAsync("Send:ErrorMail", loggingMonitor.exception);
  91. return;
  92. }
  93. // 记录访问日志-登录登出
  94. if (loggingMonitor.actionName == "userInfo" || loggingMonitor.actionName == "logout")
  95. {
  96. await _sysLogVisRep.InsertAsync(new SysLogVis
  97. {
  98. ControllerName = loggingMonitor.controllerName,
  99. ActionName = loggingMonitor.actionTypeName,
  100. DisplayTitle = loggingMonitor.displayTitle,
  101. Status = loggingMonitor.returnInformation?.httpStatusCode,
  102. RemoteIp = remoteIPv4,
  103. Location = ipLocation,
  104. Longitude = longitude,
  105. Latitude = latitude,
  106. Browser = browser, // loggingMonitor.userAgent,
  107. Os = os, // loggingMonitor.osDescription + " " + loggingMonitor.osArchitecture,
  108. Elapsed = loggingMonitor.timeOperationElapsedMilliseconds,
  109. LogDateTime = logMsg.LogDateTime,
  110. Account = account,
  111. RealName = realName,
  112. CreateUserId = string.IsNullOrWhiteSpace(userId) ? 0 : long.Parse(userId),
  113. TenantId = string.IsNullOrWhiteSpace(tenantId) ? 0 : long.Parse(tenantId),
  114. LogLevel = logMsg.LogLevel
  115. });
  116. return;
  117. }
  118. // 记录操作日志
  119. var enabledSysOpLog = await _sysConfigService.GetConfigValue<bool>(CommonConst.SysOpLog);
  120. if (!enabledSysOpLog) return;
  121. await _sysLogOpRep.InsertAsync(new SysLogOp
  122. {
  123. ControllerName = loggingMonitor.controllerName,
  124. ActionName = loggingMonitor.actionTypeName,
  125. DisplayTitle = loggingMonitor.displayTitle,
  126. Status = loggingMonitor.returnInformation?.httpStatusCode,
  127. RemoteIp = remoteIPv4,
  128. Location = ipLocation,
  129. Longitude = longitude,
  130. Latitude = latitude,
  131. Browser = browser, // loggingMonitor.userAgent,
  132. Os = os, // loggingMonitor.osDescription + " " + loggingMonitor.osArchitecture,
  133. Elapsed = loggingMonitor.timeOperationElapsedMilliseconds,
  134. LogDateTime = logMsg.LogDateTime,
  135. Account = account,
  136. RealName = realName,
  137. HttpMethod = loggingMonitor.httpMethod,
  138. RequestUrl = loggingMonitor.requestUrl,
  139. RequestParam = (loggingMonitor.parameters == null || loggingMonitor.parameters.Count == 0) ? null : JSON.Serialize(loggingMonitor.parameters[0].value),
  140. ReturnResult = loggingMonitor.returnInformation == null ? null : JSON.Serialize(loggingMonitor.returnInformation),
  141. EventId = logMsg.EventId.Id,
  142. ThreadId = logMsg.ThreadId,
  143. TraceId = logMsg.TraceId,
  144. Exception = loggingMonitor.exception == null ? null : JSON.Serialize(loggingMonitor.exception),
  145. Message = logMsg.Message,
  146. CreateUserId = string.IsNullOrWhiteSpace(userId) ? 0 : long.Parse(userId),
  147. TenantId = string.IsNullOrWhiteSpace(tenantId) ? 0 : long.Parse(tenantId),
  148. LogLevel = logMsg.LogLevel
  149. });
  150. }
  151. catch (Exception ex)
  152. {
  153. _logger.LogError(ex, ex.Message);
  154. }
  155. }
  156. /// <summary>
  157. /// 解析IP地址
  158. /// </summary>
  159. /// <param name="ip"></param>
  160. /// <returns></returns>
  161. internal static (string ipLocation, double? longitude, double? latitude) GetIpAddress(string ip)
  162. {
  163. try
  164. {
  165. var ipInfo = IpTool.Search(ip);
  166. var addressList = new List<string>() { ipInfo.Country, ipInfo.Province, ipInfo.City, ipInfo.NetworkOperator };
  167. return (string.Join("|", addressList.Where(it => it != "0").ToList()), ipInfo.Longitude, ipInfo.Latitude); // 去掉0并用|连接
  168. }
  169. catch
  170. {
  171. // 不做处理
  172. }
  173. return ("未知", 0, 0);
  174. }
  175. /// <summary>
  176. /// 释放服务作用域
  177. /// </summary>
  178. public void Dispose()
  179. {
  180. _serviceScope.Dispose();
  181. }
  182. }