Skip to content

Commit

Permalink
build: query request logs
Browse files Browse the repository at this point in the history
  • Loading branch information
powerfulyang committed Dec 5, 2023
1 parent d5321c0 commit 5fe6118
Show file tree
Hide file tree
Showing 11 changed files with 143 additions and 6 deletions.
2 changes: 1 addition & 1 deletion src/common/logger/loggerInstance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ export const loggerInstance = winston.createLogger({
format: combine(
timestamp({
format: () => {
return dayjs().format('MM/DD/YYYY, h:mm:ss.SSS A');
return dayjs().format('MM/DD/YYYY, hh:mm:ss.SSS A');
},
}),
logFormat,
Expand Down
31 changes: 31 additions & 0 deletions src/common/swagger/ApiOkPaginateQueryResponse.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import type { Type } from '@nestjs/common';
import { applyDecorators } from '@nestjs/common';
import { ApiExtraModels, ApiOkResponse, getSchemaPath } from '@nestjs/swagger';

export const ApiOkPaginateQueryResponse = <T extends Type>(options: {
model: T;
description?: string;
}) => {
const { model, description } = options;
const ref = { $ref: getSchemaPath(model) };
return applyDecorators(
ApiExtraModels(model),
ApiOkResponse({
description,
schema: {
type: 'array',
items: {
oneOf: [
{
type: 'array',
items: ref,
},
{
type: 'number',
},
],
},
},
}),
);
};
2 changes: 1 addition & 1 deletion src/fastify/hook.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ export const createFastifyInstance = (): FastifyInstance => {

fastifyInstance.addHook('onSend', (_request, reply: FastifyReply, _payload, done) => {
// fix log.middleware.ts can't get response headers
reply.raw.setHeader('x-request-id', getRequestId());
reply.raw.setHeader('x-request-id', getRequestId() || '');
reply.header('x-process-time', `${reply.getResponseTime().toFixed(3)}ms`);
reply.header('x-server-id', HOSTNAME);
reply.header('x-server-time', DateTimeFormat());
Expand Down
2 changes: 1 addition & 1 deletion src/metadata.ts

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions src/post/post.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -271,7 +271,7 @@ export class PostService extends BaseService {
createdAt,
skip,
content,
public: _p,
public: isPublic,
updatedAt,
poster,
summary,
Expand All @@ -283,7 +283,7 @@ export class PostService extends BaseService {
title: super.iLike(title),
createdAt: super.convertDateRangeToBetween(createdAt),
content: super.iLike(content),
public: super.ignoreNilValue(_p),
public: isPublic,
updatedAt: super.convertDateRangeToBetween(updatedAt),
poster: {
id: super.ignoreFalsyValue(poster?.id),
Expand Down
20 changes: 20 additions & 0 deletions src/request-log/dto/query-request-log.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { PaginatedBaseQuery } from '@/common/decorator/pagination/PaginationQuery';
import { RequestLog } from '@/request-log/entities/request-log.entity';
import { ApiProperty, IntersectionType, OmitType } from '@nestjs/swagger';

export class QueryRequestLogDto extends IntersectionType(
PaginatedBaseQuery,
OmitType(RequestLog, ['createdAt', 'updatedAt']),
) {
@ApiProperty({
description: '创建时间',
type: [Date, Date],
})
createdAt: [Date, Date];

@ApiProperty({
description: '更新时间',
type: [Date, Date],
})
updatedAt: [Date, Date];
}
34 changes: 34 additions & 0 deletions src/request-log/request-log.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { AdminAuthGuard } from '@/common/decorator/auth-guard.decorator';
import { BodyPagination } from '@/common/decorator/pagination/pagination.decorator';
import { LoggerService } from '@/common/logger/logger.service';
import { ApiOkPaginateQueryResponse } from '@/common/swagger/ApiOkPaginateQueryResponse';
import { QueryRequestLogDto } from '@/request-log/dto/query-request-log.dto';
import { RequestLog } from '@/request-log/entities/request-log.entity';
import { RequestLogService } from '@/request-log/request-log.service';
import { Controller, Post } from '@nestjs/common';
import { ApiOperation, ApiTags } from '@nestjs/swagger';

@Controller('request-log-manage')
@ApiTags('request-log-manage')
@AdminAuthGuard()
export class RequestLogController {
constructor(
private readonly logger: LoggerService,
private readonly requestLogService: RequestLogService,
) {
this.logger.setContext(RequestLogController.name);
}

@Post('query-logs')
@ApiOperation({
summary: '分页查询请求日志',
operationId: 'queryLogs',
})
@ApiOkPaginateQueryResponse({
model: RequestLog,
description: '分页查询请求日志响应',
})
queryLogs(@BodyPagination() paginateQueryRequestLogDto: QueryRequestLogDto) {
return this.requestLogService.queryLogs(paginateQueryRequestLogDto);
}
}
2 changes: 2 additions & 0 deletions src/request-log/request-log.module.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { RequestLog } from '@/request-log/entities/request-log.entity';
import { RequestLogController } from '@/request-log/request-log.controller';
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { CacheModule } from '@/common/cache/cache.module';
Expand All @@ -10,5 +11,6 @@ import { RequestLogService } from '@/request-log/request-log.service';
imports: [OrmModule, TypeOrmModule.forFeature([RequestLog]), CacheModule, LoggerModule],
providers: [RequestLogService],
exports: [RequestLogService],
controllers: [RequestLogController],
})
export class RequestLogModule {}
47 changes: 46 additions & 1 deletion src/request-log/request-log.service.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,19 @@
import { LoggerService } from '@/common/logger/logger.service';
import type { QueryRequestLogDto } from '@/request-log/dto/query-request-log.dto';
import type { RequestLogDto } from '@/request-log/dto/request-log.dto';
import { RequestLog } from '@/request-log/entities/request-log.entity';
import { BaseService } from '@/service/base/BaseService';
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';

@Injectable()
export class RequestLogService {
export class RequestLogService extends BaseService {
constructor(
@InjectRepository(RequestLog) private readonly requestLogDao: Repository<RequestLog>,
private readonly logger: LoggerService,
) {
super();
this.logger.setContext(RequestLogService.name);
}

Expand All @@ -29,4 +32,46 @@ export class RequestLogService {
async log(requestLog: Omit<RequestLog, 'id' | 'createdAt' | 'updatedAt'>) {
return this.requestLogDao.save(requestLog);
}

queryLogs(paginateQueryRequestLogDto: QueryRequestLogDto) {
const {
id,
updatedAt,
createdAt,
skip,
take,
requestId,
statusCode,
path,
referer,
userAgent,
ip,
ipInfo,
contentLength,
method,
processTime,
} = paginateQueryRequestLogDto;
return this.requestLogDao.findAndCount({
where: {
id: super.ignoreFalsyValue(id),
createdAt: super.convertDateRangeToBetween(createdAt),
updatedAt: super.convertDateRangeToBetween(updatedAt),
requestId: super.ignoreFalsyValue(requestId),
statusCode: super.ignoreFalsyValue(statusCode),
path: super.iLike(path),
referer: super.iLike(referer),
userAgent: super.iLike(userAgent),
ip,
ipInfo: super.iLike(ipInfo),
contentLength: super.ignoreEmptyString(contentLength),
method: super.ignoreEmptyString(method),
processTime: super.iLike(processTime),
},
take,
skip,
order: {
id: 'DESC',
},
});
}
}
4 changes: 4 additions & 0 deletions src/service/base/BaseService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,10 @@ export class BaseService {
return isNotNil(value) ? value : undefined;
}

protected ignoreEmptyString(value?: string) {
return value === '' ? undefined : value;
}

protected ignoreEmptyArray<T>(value?: T[]) {
return value?.length ? In(value) : undefined;
}
Expand Down
1 change: 1 addition & 0 deletions src/user/user.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -385,6 +385,7 @@ export class UserService extends BaseService {
const user = await this.queryUserCascadeInfo(id);
user.lastIp = loginIp;
user.lastAddress = getIpInfo(loginIp);
user.updatedAt = new Date();
return this.saveUserAndCached(user);
}
}

0 comments on commit 5fe6118

Please sign in to comment.