// Admin.NET 项目的版æƒã€å•†æ ‡ã€ä¸“利和其他相关æƒåˆ©å‡å—ç›¸åº”æ³•å¾‹æ³•è§„çš„ä¿æŠ¤ã€‚ä½¿ç”¨æœ¬é¡¹ç›®åº”éµå®ˆç›¸å…³æ³•律法规和许å¯è¯çš„è¦æ±‚。 // // 本项目主è¦éµå¾ª MIT 许å¯è¯å’Œ Apache 许å¯è¯ï¼ˆç‰ˆæœ¬ 2.0)进行分å‘和使用。许å¯è¯ä½äºŽæºä»£ç æ ‘æ ¹ç›®å½•ä¸çš„ LICENSE-MIT å’Œ LICENSE-APACHE 文件。 // // ä¸å¾—利用本项目从事å±å®³å›½å®¶å®‰å…¨ã€æ‰°ä¹±ç¤¾ä¼šç§©åºã€ä¾µçŠ¯ä»–äººåˆæ³•æƒç›Šç‰æ³•å¾‹æ³•è§„ç¦æ¢çš„æ´»åЍï¼ä»»ä½•基于本项目二次开å‘è€Œäº§ç”Ÿçš„ä¸€åˆ‡æ³•å¾‹çº çº·å’Œè´£ä»»ï¼Œæˆ‘ä»¬ä¸æ‰¿æ‹…ä»»ä½•è´£ä»»ï¼ namespace Admin.NET.Core; /// <summary> /// æ•°æ®åº“日志写入器 /// </summary> public class DatabaseLoggingWriter : IDatabaseLoggingWriter, IDisposable { private readonly IServiceScope _serviceScope; private readonly ISqlSugarClient _db; private readonly SysConfigService _sysConfigService; // 傿•°é…ç½®æœåŠ¡ private readonly ILogger<DatabaseLoggingWriter> _logger; // 日志组件 public DatabaseLoggingWriter(IServiceScopeFactory scopeFactory) { _serviceScope = scopeFactory.CreateScope(); //_db = _serviceScope.ServiceProvider.GetRequiredService<ISqlSugarClient>(); _sysConfigService = _serviceScope.ServiceProvider.GetRequiredService<SysConfigService>(); _logger = _serviceScope.ServiceProvider.GetRequiredService<ILogger<DatabaseLoggingWriter>>(); // åˆ‡æ¢æ—¥å¿—独立数æ®åº“ _db = SqlSugarSetup.ITenant.IsAnyConnection(SqlSugarConst.LogConfigId) ? SqlSugarSetup.ITenant.GetConnectionScope(SqlSugarConst.LogConfigId) : SqlSugarSetup.ITenant.GetConnectionScope(SqlSugarConst.MainConfigId); } public async Task WriteAsync(LogMessage logMsg, bool flush) { var jsonStr = logMsg.Context?.Get("loggingMonitor")?.ToString(); if (string.IsNullOrWhiteSpace(jsonStr)) { await _db.Insertable(new SysLogOp { DisplayTitle = "自定义æ“作日志", LogDateTime = logMsg.LogDateTime, EventId = logMsg.EventId.Id, ThreadId = logMsg.ThreadId, TraceId = logMsg.TraceId, Exception = logMsg.Exception == null ? null : JSON.Serialize(logMsg.Exception), Message = logMsg.Message, LogLevel = logMsg.LogLevel, Status = "200", }).ExecuteCommandAsync(); return; } var loggingMonitor = JSON.Deserialize<dynamic>(jsonStr); // è®°å½•æ•°æ®æ ¡éªŒæ—¥å¿— if (loggingMonitor.validation != null && !await _sysConfigService.GetConfigValue<bool>(ConfigConst.SysValidationLog)) return; // 获å–当剿“作者 string account = "", realName = "", userId = "", tenantId = ""; if (loggingMonitor.authorizationClaims != null) { foreach (var item in loggingMonitor.authorizationClaims) { if (item.type == ClaimConst.Account) account = item.value; if (item.type == ClaimConst.RealName) realName = item.value; if (item.type == ClaimConst.TenantId) tenantId = item.value; if (item.type == ClaimConst.UserId) userId = item.value; } } // ä¼˜å…ˆèŽ·å– X-Forwarded-For å¤´éƒ¨ä¿¡æ¯æºå¸¦çš„IP地å€ï¼ˆå¦‚nginx代ç†é…置转å‘) var remoteIPv4 = ((JArray)loggingMonitor.requestHeaders).OfType<JObject>() .FirstOrDefault(header => (string)header["key"] == "X-Forwarded-For")?["value"]?.ToString(); if (string.IsNullOrEmpty(remoteIPv4)) remoteIPv4 = loggingMonitor.remoteIPv4; (string ipLocation, double? longitude, double? latitude) = CommonUtil.GetIpAddress(remoteIPv4); var browser = ""; var os = ""; if (loggingMonitor.userAgent != null) { var client = Parser.GetDefault().Parse(loggingMonitor.userAgent.ToString()); browser = $"{client.UA.Family} {client.UA.Major}.{client.UA.Minor} / {client.Device.Family}"; os = $"{client.OS.Family} {client.OS.Major} {client.OS.Minor}"; } // æ•æ‰å¼‚常,å¦åˆ™ä¼šç”±äºŽ unhandled exception 导致程åºå´©æºƒ try { // 记录异常日志-å‘é€é‚®ä»¶ if (logMsg.Exception != null || loggingMonitor.exception != null) { await _db.Insertable(new SysLogEx { ControllerName = loggingMonitor.controllerName, ActionName = loggingMonitor.actionTypeName, DisplayTitle = loggingMonitor.displayTitle, Status = loggingMonitor.returnInformation?.httpStatusCode, RemoteIp = remoteIPv4, Location = ipLocation, Longitude = longitude, Latitude = latitude, Browser = browser, // loggingMonitor.userAgent, Os = os, // loggingMonitor.osDescription + " " + loggingMonitor.osArchitecture, Elapsed = loggingMonitor.timeOperationElapsedMilliseconds, LogDateTime = logMsg.LogDateTime, Account = account, RealName = realName, HttpMethod = loggingMonitor.httpMethod, RequestUrl = loggingMonitor.requestUrl, RequestParam = (loggingMonitor.parameters == null || loggingMonitor.parameters.Count == 0) ? null : JSON.Serialize(loggingMonitor.parameters[0].value), ReturnResult = loggingMonitor.returnInformation == null ? null : JSON.Serialize(loggingMonitor.returnInformation), EventId = logMsg.EventId.Id, ThreadId = logMsg.ThreadId, TraceId = logMsg.TraceId, Exception = JSON.Serialize(loggingMonitor.exception), Message = logMsg.Message, CreateUserId = string.IsNullOrWhiteSpace(userId) ? 0 : long.Parse(userId), TenantId = string.IsNullOrWhiteSpace(tenantId) ? 0 : long.Parse(tenantId), LogLevel = logMsg.LogLevel }).ExecuteCommandAsync(); // 将异常日志å‘é€åˆ°é‚®ä»¶ if (await _sysConfigService.GetConfigValue<bool>(ConfigConst.SysErrorMail)) { await App.GetRequiredService<IEventPublisher>().PublishAsync(CommonConst.SendErrorMail, logMsg.Exception ?? loggingMonitor.exception); } return; } // 记录访问日志-登录退出 if (loggingMonitor.actionName == "userInfo" || loggingMonitor.actionName == "logout") { await _db.Insertable(new SysLogVis { ControllerName = loggingMonitor.controllerName, ActionName = loggingMonitor.actionTypeName, DisplayTitle = loggingMonitor.displayTitle, Status = loggingMonitor.returnInformation?.httpStatusCode, RemoteIp = remoteIPv4, Location = ipLocation, Longitude = longitude, Latitude = latitude, Browser = browser, // loggingMonitor.userAgent, Os = os, // loggingMonitor.osDescription + " " + loggingMonitor.osArchitecture, Elapsed = loggingMonitor.timeOperationElapsedMilliseconds, LogDateTime = logMsg.LogDateTime, Account = account, RealName = realName, CreateUserId = string.IsNullOrWhiteSpace(userId) ? 0 : long.Parse(userId), TenantId = string.IsNullOrWhiteSpace(tenantId) ? 0 : long.Parse(tenantId), LogLevel = logMsg.LogLevel }).ExecuteCommandAsync(); return; } // 记录æ“作日志 if (!await _sysConfigService.GetConfigValue<bool>(ConfigConst.SysOpLog)) return; await _db.Insertable(new SysLogOp { ControllerName = loggingMonitor.controllerName, ActionName = loggingMonitor.actionTypeName, DisplayTitle = loggingMonitor.displayTitle, Status = loggingMonitor.returnInformation?.httpStatusCode, RemoteIp = remoteIPv4, Location = ipLocation, Longitude = longitude, Latitude = latitude, Browser = browser, // loggingMonitor.userAgent, Os = os, // loggingMonitor.osDescription + " " + loggingMonitor.osArchitecture, Elapsed = loggingMonitor.timeOperationElapsedMilliseconds, LogDateTime = logMsg.LogDateTime, Account = account, RealName = realName, HttpMethod = loggingMonitor.httpMethod, RequestUrl = loggingMonitor.requestUrl, RequestParam = (loggingMonitor.parameters == null || loggingMonitor.parameters.Count == 0) ? null : JSON.Serialize(loggingMonitor.parameters[0].value), ReturnResult = loggingMonitor.returnInformation == null ? null : JSON.Serialize(loggingMonitor.returnInformation), EventId = logMsg.EventId.Id, ThreadId = logMsg.ThreadId, TraceId = logMsg.TraceId, Exception = loggingMonitor.exception == null ? null : JSON.Serialize(loggingMonitor.exception), Message = logMsg.Message, CreateUserId = string.IsNullOrWhiteSpace(userId) ? 0 : long.Parse(userId), TenantId = string.IsNullOrWhiteSpace(tenantId) ? 0 : long.Parse(tenantId), LogLevel = logMsg.LogLevel }).ExecuteCommandAsync(); await Task.Delay(50); // 延迟 0.05 秒写入数æ®åº“,有效å‡å°‘高频写入数æ®åº“导致æ»é”问题 } catch (Exception ex) { _logger.LogError(ex, "æ“作日志入库"); } } /// <summary> /// 释放æœåŠ¡ä½œç”¨åŸŸ /// </summary> public void Dispose() { _serviceScope.Dispose(); } }