From f8e877e5473233c41bb9c9e34f8f3617465b078b Mon Sep 17 00:00:00 2001 From: snowgitea Date: Wed, 1 Jul 2026 17:56:14 +0800 Subject: [PATCH] chore: src/modules/base/service/sys/log.ts --- src/modules/base/service/sys/log.ts | 62 +++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 src/modules/base/service/sys/log.ts diff --git a/src/modules/base/service/sys/log.ts b/src/modules/base/service/sys/log.ts new file mode 100644 index 0000000..e2e4195 --- /dev/null +++ b/src/modules/base/service/sys/log.ts @@ -0,0 +1,62 @@ +import { Inject, Provide } from '@midwayjs/core'; +import { BaseService } from '@cool-midway/core'; +import { InjectEntityModel } from '@midwayjs/typeorm'; +import { LessThan, Repository } from 'typeorm'; +import * as _ from 'lodash'; +import { BaseSysLogEntity } from '../../entity/sys/log'; +import * as moment from 'moment'; +import { Utils } from '../../../../comm/utils'; +import { BaseSysConfService } from './conf'; +import { Context } from '@midwayjs/koa'; + +/** + * 描述 + */ +@Provide() +export class BaseSysLogService extends BaseService { + @Inject() + ctx; + + @Inject() + utils: Utils; + + @InjectEntityModel(BaseSysLogEntity) + baseSysLogEntity: Repository; + + @Inject() + baseSysConfService: BaseSysConfService; + + /** + * 记录 + * @param url URL地址 + * @param params 参数 + * @param userId 用户ID + */ + async record(context: Context, url, params, userId) { + const ip = await this.utils.getReqIP(context); + const sysLog = new BaseSysLogEntity(); + sysLog.userId = userId; + sysLog.ip = typeof ip === 'string' ? ip : ip.join(','); + sysLog.action = url.split('?')[0]; + sysLog.params = params; + await this.baseSysLogEntity.insert(sysLog); + } + + /** + * 日志 + * @param isAll 是否清除全部 + */ + async clear(isAll?) { + if (isAll) { + await this.baseSysLogEntity.clear(); + return; + } + const keepDay = await this.baseSysConfService.getValue('logKeep'); + if (keepDay) { + const beforeDate = moment().add(-keepDay, 'days').startOf('day').format('YYYY-MM-DD HH:mm:ss'); + await this.baseSysLogEntity.createQueryBuilder().delete().where('createTime < :beforeDate', { beforeDate }).execute(); + } else { + await this.baseSysLogEntity.clear(); + } + } +}