首页
/ 在AdminJS/NestJS项目中实现请求响应日志记录的方案

在AdminJS/NestJS项目中实现请求响应日志记录的方案

2025-05-27 16:27:42作者:廉彬冶Miranda

背景介绍

在基于AdminJS和NestJS构建的管理后台项目中,开发人员经常需要记录用户的操作行为,包括页面导航和API请求。这种日志记录对于安全审计、用户行为分析和故障排查都非常重要。

技术挑战

在AdminJS/NestJS架构中实现完整的请求响应日志记录面临几个技术难点:

  1. 混合架构特性:AdminJS同时包含前端路由和后端API
  2. 认证后的请求追踪:登录后的操作日志难以捕获
  3. 完整上下文记录:需要同时记录请求和响应数据

解决方案

1. API请求日志记录

对于后端API调用,可以通过NestJS中间件实现:

import { Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';

@Injectable()
export class ApiLoggerMiddleware implements NestMiddleware {
  use(req: Request, res: Response, next: NextFunction) {
    const { method, originalUrl, body, headers } = req;
    
    // 记录请求信息
    console.log({
      timestamp: new Date().toISOString(),
      method,
      path: originalUrl,
      body,
      headers
    });

    // 劫持原始响应方法以记录响应数据
    const originalSend = res.send;
    res.send = function (body) {
      console.log({
        timestamp: new Date().toISOString(),
        status: res.statusCode,
        response: body
      });
      return originalSend.call(this, body);
    };

    next();
  }
}

然后在模块中注册这个中间件:

export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer
      .apply(ApiLoggerMiddleware)
      .forRoutes('*');
  }
}

2. AdminJS资源操作日志

对于AdminJS的资源操作(CRUD),可以使用AdminJS的before钩子:

const adminJsOptions = {
  resources: [
    {
      resource: YourModel,
      options: {
        actions: {
          new: {
            before: async (request) => {
              console.log('Create action request:', request);
              return request;
            },
            after: async (response) => {
              console.log('Create action response:', response);
              return response;
            }
          },
          // 同样为edit, show, delete等操作添加钩子
        }
      }
    }
  ]
};

3. 前端路由变更日志

对于前端路由变化,有几种实现方案:

方案一:自定义TopBar组件

const customComponents = {
  TopBar: OriginalTopBar => {
    return props => {
      const location = useLocation();
      
      useEffect(() => {
        console.log('Route changed to:', location.pathname);
      }, [location.pathname]);

      return <OriginalTopBar {...props} />;
    };
  }
};

// 在AdminJS配置中注册
const adminJsOptions = {
  dashboard: {
    component: customComponents.TopBar
  }
};

方案二:使用全局事件监听

window.addEventListener('popstate', () => {
  console.log('Route changed:', window.location.pathname);
});

进阶优化建议

  1. 日志分级:区分DEBUG、INFO、WARN等级别
  2. 敏感信息过滤:在记录前过滤密码等敏感字段
  3. 持久化存储:将日志写入数据库或文件系统
  4. 性能优化:在高频操作处使用节流(throttle)技术
  5. 上下文关联:为每个请求生成唯一ID,便于追踪

实施注意事项

  1. 生产环境应考虑使用成熟的日志库如Winston或Pino
  2. 注意GDPR等隐私法规要求,避免记录个人敏感信息
  3. 对于高流量系统,日志记录应异步进行以避免阻塞主线程
  4. 考虑实现日志轮转机制防止磁盘空间耗尽

通过上述方案,开发者可以在AdminJS/NestJS项目中建立完整的操作日志系统,满足审计和分析需求。

登录后查看全文
热门项目推荐
相关项目推荐