-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlogging.interceptor.ts
62 lines (59 loc) · 1.44 KB
/
logging.interceptor.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import {
CallHandler,
ExecutionContext,
Injectable,
Logger,
NestInterceptor
} from "@nestjs/common";
import { GqlExecutionContext } from "@nestjs/graphql";
import { Observable } from "rxjs";
import { tap } from "rxjs/operators";
/**
* Setup Custom Logging Interceptor
* https://docs.nestjs.com/interceptors#binding-interceptors
*
* @example
```ts
import { LoggingInterceptor } from "nestjs-dev-utilities";
app.useGlobalInterceptors(
new LoggingInterceptor(),
);
```
*/
@Injectable()
export class LoggingInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
const now = Date.now();
const req = context.switchToHttp().getRequest();
// if via http
if (req) {
const { method } = req;
const { url } = req;
return next
.handle()
.pipe(
tap(() =>
Logger.log(
`${method} ${url} ${Date.now() - now}ms`,
context.getClass().name
)
)
);
}
// if graphql
const ctx: any = GqlExecutionContext.create(context);
const resolverName = ctx.constructorRef.name;
const info = ctx.getInfo();
return next
.handle()
.pipe(
tap(() =>
Logger.log(
`${info.parentType} "${info.fieldName}" ${Date.now() - now}ms`,
resolverName
)
)
);
}
}
export default LoggingInterceptor;