mirror of
https://github.com/SyncrowIOT/backend.git
synced 2026-10-25 18:27:55 +00:00
- add winston logger
- updated HTTP logging interceptor
This commit is contained in:
@@ -3,39 +3,65 @@ import {
|
||||
NestInterceptor,
|
||||
ExecutionContext,
|
||||
CallHandler,
|
||||
Inject,
|
||||
} from '@nestjs/common';
|
||||
import { Observable, throwError } from 'rxjs';
|
||||
import { map, catchError } from 'rxjs/operators';
|
||||
import { WINSTON_MODULE_PROVIDER } from 'nest-winston';
|
||||
import { Logger } from 'winston';
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
|
||||
@Injectable()
|
||||
export class LoggingInterceptor implements NestInterceptor {
|
||||
constructor(
|
||||
@Inject(WINSTON_MODULE_PROVIDER)
|
||||
private readonly logger: Logger,
|
||||
) {}
|
||||
|
||||
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
|
||||
const request = context.switchToHttp().getRequest();
|
||||
const res = context.switchToHttp().getResponse();
|
||||
|
||||
const { method, url, body } = request;
|
||||
const requestId = uuidv4();
|
||||
const now = Date.now();
|
||||
|
||||
res.setHeader('X-Request-Id', requestId);
|
||||
|
||||
return next.handle().pipe(
|
||||
map((response) => {
|
||||
// Filter out sensitive fields from the request body for logging
|
||||
const duration = Date.now() - now;
|
||||
const filteredRequestBody = this.filterSensitiveFields(body);
|
||||
console.log(
|
||||
'-------------------------------------------------------------------',
|
||||
);
|
||||
console.log(`Request Method: ${method}`);
|
||||
console.log(`Request URL: ${url}`);
|
||||
if (
|
||||
filteredRequestBody &&
|
||||
Object.keys(filteredRequestBody).length > 0
|
||||
) {
|
||||
console.log(`Request Body: ${JSON.stringify(filteredRequestBody)}`);
|
||||
}
|
||||
// Filter out sensitive fields from the response for logging
|
||||
const filteredResponse = this.filterSensitiveFields(response);
|
||||
console.log(`Response: ${JSON.stringify(filteredResponse)}`);
|
||||
return response; // Return the actual response unmodified
|
||||
|
||||
this.logger.info('--- Incoming Request ---', {
|
||||
method,
|
||||
url,
|
||||
duration: `${duration}ms`,
|
||||
requestBody: filteredRequestBody,
|
||||
responseBody: filteredResponse,
|
||||
});
|
||||
|
||||
this.logger.info('--- Outgoing Response ---', {
|
||||
method,
|
||||
url,
|
||||
response: filteredResponse,
|
||||
});
|
||||
|
||||
return response;
|
||||
}),
|
||||
catchError((error) => {
|
||||
// Do not log anything if there is an error
|
||||
return throwError(error);
|
||||
const duration = Date.now() - now;
|
||||
|
||||
this.logger.error('--- Request Error ---', {
|
||||
requestId,
|
||||
method,
|
||||
url,
|
||||
message: error.message,
|
||||
duration: `${duration}ms`,
|
||||
stack: error.stack,
|
||||
});
|
||||
return throwError(() => error);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user