-
Notifications
You must be signed in to change notification settings - Fork 1
/
logger.ts
53 lines (39 loc) · 1.14 KB
/
logger.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
import { Layer, Middleware } from '../types';
const RE_HOSTNAME = /^https?:\/\/[\w-\.:]+/;
type LoggerOptions = {
verbose: boolean;
};
export function createLogger({ verbose }: LoggerOptions) {
return (next: Layer) => async (request: Request) => {
const req = request.clone();
const response = await next(request);
const res = response.clone();
const pathname = req.url.replace(RE_HOSTNAME, '');
let contents = `${req.method} ${pathname ?? '/'} (${res.status})`;
if (verbose && res.headers.get('Content-Type') === 'application/json') {
// Log request data
try {
contents += '\n';
contents += prettify(await req.json());
} catch (err) {
// Ignore
}
const data = await res.json();
// Log response data
if (data) {
contents += '\n';
contents += prettify(data);
}
}
if (res.status >= 300) {
console.error(contents);
} else {
console.log(contents);
}
return response;
};
}
export const logger: Middleware = createLogger({ verbose: true });
function prettify(data: any) {
return JSON.stringify(data, null, 2);
}