-
Notifications
You must be signed in to change notification settings - Fork 34
/
grpc-logger-interceptor.ts
160 lines (141 loc) · 5.34 KB
/
grpc-logger-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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
import { Inject, Injectable, InjectionToken, Optional } from '@angular/core';
import { GrpcDataEvent, GrpcEvent, GrpcMessage, GrpcRequest } from '@ngx-grpc/common';
import { isObservable, Observable, of } from 'rxjs';
import { share, tap } from 'rxjs/operators';
import { GrpcHandler } from './grpc-handler';
import { GrpcInterceptor } from './grpc-interceptor';
/**
* A configuration for GrpcLoggerInterceptor
*
* Example:
*
* ```
* providers: [
* { provide: GRPC_LOGGER_SETTINGS, useValue: { enabled: true } },
* ]
* ```
*
* or more complex:
*
* ```
* providers: [
* { provide: GRPC_LOGGER_SETTINGS, useFactory: () => { enabled: localStorage.getItem('GRPC_LOGGER_SETTINGS') === 'true' || !environment.prod } },
* ]
* ```
*/
export const GRPC_LOGGER_SETTINGS = new InjectionToken('GRPC_LOGGER_SETTINGS');
/**
* A configuration definition for GrpcLoggerInterceptor
*/
export interface GrpcLoggerSettings {
/**
* Enables / disables the output, default true
*/
enabled?: boolean;
/**
* Includes client settings into the logs, default true
*/
logClientSettings?: boolean;
/**
* Includes request metadata into the logs, default true
*/
logMetadata?: boolean;
/**
* Logs events with status code OK (0), default false
*/
logStatusCodeOk?: boolean;
/**
* Request mapper function, defines what output is generated for the given message.
* The default implementation is `(msg) => msg.toObject()`.
* According to your preferences you might choose e.g. `(msg) => msg.toProtobufJSON()` instead.
*/
requestMapper?: (msg: GrpcMessage) => any;
/**
* Response mapper function, defines what output is generated for the given message.
* The default implementation is `(msg) => msg.toObject()`.
* According to your preferences you might choose e.g. `(msg) => msg.toProtobufJSON()` instead.
*/
responseMapper?: (msg: GrpcMessage) => any;
}
/**
* Interceptor that implements logging of every request to the browser console
*
* Can be enabled / disabled by GRPC_LOGGER_ENABLED injection token
*/
@Injectable()
export class GrpcLoggerInterceptor implements GrpcInterceptor {
private static requestId = 0;
private clientDataStyle = 'color: #eb0edc;';
private dataStyle = 'color: #5c7ced;';
private errorStyle = 'color: #f00505;';
private statusOkStyle = 'color: #0ffcf5;';
private settings: GrpcLoggerSettings;
constructor(@Optional() @Inject(GRPC_LOGGER_SETTINGS) settings: GrpcLoggerSettings = {}) {
this.settings = {
enabled: settings.enabled ?? true,
logClientSettings: settings.logClientSettings ?? true,
logMetadata: settings.logMetadata ?? true,
logStatusCodeOk: settings.logStatusCodeOk ?? false,
requestMapper: settings.requestMapper ?? ((msg: GrpcMessage) => msg.toObject()),
responseMapper: settings.responseMapper ?? ((msg: GrpcMessage) => msg.toObject()),
};
}
intercept<Q extends GrpcMessage, S extends GrpcMessage>(request: GrpcRequest<Q, S>, next: GrpcHandler): Observable<GrpcEvent<S>> {
if (this.settings.enabled) {
const id = ++GrpcLoggerInterceptor.requestId;
const start = Date.now();
// check if client streaming, then push each value separately
if (isObservable(request.requestData)) {
request.requestData = request.requestData.pipe(
tap(msg => {
console.groupCollapsed(`%c#${id}: ${Date.now() - start}ms -> ${request.path}`, this.clientDataStyle);
console.log('%c>>', this.clientDataStyle, this.settings.requestMapper(msg));
console.groupEnd();
}),
);
}
// handle unary calls and server streaming in the same manner
return next.handle(request).pipe(
tap(event => {
const style = event instanceof GrpcDataEvent ? this.dataStyle : event.statusCode !== 0 ? this.errorStyle : this.statusOkStyle;
const openGroup = () => console.groupCollapsed(`%c#${id}: ${Date.now() - start}ms -> ${request.path}`, style);
const printSettings = () => {
if (this.settings.logClientSettings) {
console.log('%csc', style, request.client.getSettings());
}
};
const printMetadata = () => {
if (this.settings.logMetadata) {
console.log('%c**', style, request.requestMetadata.toObject());
}
};
const printRequest = () => console.log('%c>>', style, isObservable(request.requestData) ? '<see above>' : this.settings.requestMapper(request.requestData));
const closeGroup = () => console.groupEnd();
if (event instanceof GrpcDataEvent) {
openGroup();
printSettings();
printRequest();
printMetadata();
console.log('%c<<', style, this.settings.responseMapper(event.data));
closeGroup();
} else if (event.statusCode !== 0) {
openGroup();
printSettings();
printRequest();
printMetadata();
console.log('%c<<', style, event);
closeGroup();
} else if (event.statusCode === 0 && this.settings.logStatusCodeOk) {
openGroup();
printSettings();
printRequest();
printMetadata();
console.log('%c<<', style, event);
closeGroup();
}
}),
);
}
return next.handle(request);
}
}