diff --git a/SHH.CameraSdk/Controllers/MonitorController.cs b/SHH.CameraSdk/Controllers/MonitorController.cs index a14b243..3e6aa59 100644 --- a/SHH.CameraSdk/Controllers/MonitorController.cs +++ b/SHH.CameraSdk/Controllers/MonitorController.cs @@ -120,4 +120,31 @@ public class MonitorController : ControllerBase } #endregion + + /// + /// 获取系统操作日志(读取最新的 50 条) + /// + [HttpGet("system-logs")] + public IActionResult GetSystemLogs() + { + try + { + var logPath = "user_actions.log"; + if (!System.IO.File.Exists(logPath)) + { + return Ok(new List { "暂无操作记录" }); + } + + // 读取文件 -> 取最后50行 -> 倒序排列(最新在前) + var logs = System.IO.File.ReadLines(logPath) + .TakeLast(50) + .Reverse() + .ToList(); + return Ok(logs); + } + catch (Exception ex) + { + return StatusCode(500, $"读取日志失败: {ex.Message}"); + } + } } \ No newline at end of file diff --git a/SHH.CameraSdk/Program.cs b/SHH.CameraSdk/Program.cs index c3bd6d1..058ceee 100644 --- a/SHH.CameraSdk/Program.cs +++ b/SHH.CameraSdk/Program.cs @@ -91,7 +91,12 @@ public class Program builder.Logging.AddFilter("System", LogLevel.Warning); builder.Logging.AddFilter("Microsoft.AspNetCore.Hosting.Diagnostics", LogLevel.Warning); - builder.Services.AddControllers(); + builder.Services.AddControllers(options => + { + // 注册全局操作日志过滤器 + options.Filters.Add(); + }); + builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(c => { diff --git a/SHH.CameraSdk/Temp/UserActionFilter.cs b/SHH.CameraSdk/Temp/UserActionFilter.cs index 8d171cd..aa9ef05 100644 --- a/SHH.CameraSdk/Temp/UserActionFilter.cs +++ b/SHH.CameraSdk/Temp/UserActionFilter.cs @@ -1,18 +1,35 @@ using Microsoft.AspNetCore.Mvc.Filters; +namespace SHH.CameraSdk; + public class UserActionFilter : IActionFilter { + // 静态锁,防止多线程同时写文件报错 + private static readonly object _logLock = new object(); + public void OnActionExecuted(ActionExecutedContext context) { + // 只记录非 GET 请求(即修改性质的操作) if (context.HttpContext.Request.Method != "GET") { - var user = context.HttpContext.Connection.RemoteIpAddress; - var path = context.HttpContext.Request.Path; - var method = context.HttpContext.Request.Method; + try + { + var user = context.HttpContext.Connection.RemoteIpAddress?.ToString() ?? "Unknown"; + var path = context.HttpContext.Request.Path; + var method = context.HttpContext.Request.Method; + var time = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"); - // 写入全局操作日志文件或数据库 - File.AppendAllText("user_actions.log", $"{DateTime.Now} | {user} | {method} {path}\n"); + var logLine = $"{time} | IP: {user} | {method} {path}"; + + lock (_logLock) + { + // 追加写入到运行目录下的 user_actions.log + File.AppendAllText("user_actions.log", logLine + Environment.NewLine); + } + } + catch { /* 忽略日志写入错误,不要影响业务 */ } } } + public void OnActionExecuting(ActionExecutingContext context) { } } \ No newline at end of file