Skip to content

Commit

Permalink
feat: logging interceptor
Browse files Browse the repository at this point in the history
  • Loading branch information
kuizuo committed Aug 3, 2023
1 parent 7e9c8b5 commit b2bcb0f
Show file tree
Hide file tree
Showing 3 changed files with 64 additions and 10 deletions.
3 changes: 2 additions & 1 deletion apps/api/.eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ module.exports = {
'no-restricted-syntax': 'off',
'no-await-in-loop': 'off',

'radix': 'off'
'radix': 'off',
'no-bitwise': 'off'
},
};
36 changes: 36 additions & 0 deletions apps/api/src/interceptors/logging.interceptor.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import {
CallHandler,
ExecutionContext,
Injectable,
Logger,
NestInterceptor,
} from '@nestjs/common';
import { Observable, tap } from 'rxjs';

@Injectable()
export class LoggingInterceptor implements NestInterceptor {
private logger: Logger;

constructor() {
this.logger = new Logger(LoggingInterceptor.name, { timestamp: false });
}

intercept(
context: ExecutionContext,
next: CallHandler<any>,
): Observable<any> {
const call$ = next.handle();
const request = context.switchToHttp().getRequest();
const content = `${request.method} -> ${request.url}`;
this.logger.debug(`+++ 请求:${content}`);
const now = Date.now();

return call$.pipe(
tap(() =>
this.logger.debug(
`--- 响应请求:${content}${` +${Date.now() - now}ms`}`,
),
),
);
}
}
35 changes: 26 additions & 9 deletions apps/api/src/main.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import cluster from 'cluster';
import path from 'path';
import { performance } from 'perf_hooks';

import {
ClassSerializerInterceptor,
Expand All @@ -22,6 +24,8 @@ import { AppModule } from './app.module';

import { IAppConfig } from './config';
import { AppFilter } from './filters/app.filter';
import { isDev, isMainProcess } from './global/env';
import { LoggingInterceptor } from './interceptors/logging.interceptor';
import { TimeoutInterceptor } from './interceptors/timeout.interceptor';
import { TransformInterceptor } from './interceptors/transform.interceptor';
import { AppLoggerService } from './modules/shared/services/app-logger.service';
Expand Down Expand Up @@ -68,11 +72,13 @@ async function bootstrap() {
app.useGlobalFilters(new AppFilter());

app.useGlobalInterceptors(
// 请求超时处理
// 请求超时
new TimeoutInterceptor(30000),
// 序列化处理
// 序列化
new ClassSerializerInterceptor(reflector),
// 返回数据处理
// Logging
isDev ? new LoggingInterceptor() : null,
// 返回数据转换
new TransformInterceptor(new Reflector()),
);

Expand Down Expand Up @@ -105,14 +111,25 @@ async function bootstrap() {

setupSwagger(app, configService);

await app.listen(port, '0.0.0.0');
await app.listen(port, '0.0.0.0', async () => {
const url = await app.getUrl();
const { pid } = process;
const env = cluster.isPrimary;
const prefix = env ? 'P' : 'W';

// started log
const logger = new Logger('NestApplication');
logger.log(`Server running on ${await app.getUrl()}`);
if (!isMainProcess) {
return;
}

const logger = new Logger('NestApplication');
logger.log(`[${prefix + pid}] Server running on ${url}`);

if (isDev) {
logger.log(`[${prefix + pid}] OpenApi: ${url}/api-docs`);
}
logger.log(`Server is up. ${`+${performance.now() | 0}ms`}`);
});

// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
if (module.hot) {
module.hot.accept();
module.hot.dispose(() => app.close());
Expand Down

0 comments on commit b2bcb0f

Please sign in to comment.