-
-
Notifications
You must be signed in to change notification settings - Fork 203
/
logger.ts
executable file
·70 lines (64 loc) · 1.79 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import Router from 'koa-router';
import pinoLogger from 'pino-multi-stream';
const cloudwatch = require('pino-cloudwatch'); //tslint:disable-line
import { config } from './config';
export interface ILog {
data?: any;
host: string;
method: string;
query: string;
remoteAddress: string;
status: number;
url: string;
userAgent: string;
userId?: string;
}
type ErrorObj = {
err: Partial<Error>;
};
export interface ILogger {
info(obj: object | string, ...params: any[]): void;
warn(obj: object | string, ...params: any[]): void;
error(obj: Error | ErrorObj | string, ...params: any[]): void;
child(options: { module: string; userId?: string }): ILogger;
}
export const loggerMiddleware = (externalLogger: ILogger) => async (
ctx: Router.RouterContext<any, { logger: ILogger }>,
next: () => Promise<any>,
) => {
const logger = externalLogger;
const data: Partial<ILog> = {
status: ctx.status,
method: ctx.method,
url: ctx.url,
query: ctx.query,
};
try {
ctx.logger = logger;
await next();
data.status = ctx.status;
} catch (e) {
logger.error(e);
data.status = e.status;
}
logger.info({
msg: 'Processed request',
...data,
userId: ctx.state && ctx.state.user ? ctx.state.user.id : undefined,
});
};
export function createDefaultLogger() {
const streams = [{ stream: process.stdout }];
const { accessKeyId, secretAccessKey, region } = config.aws;
if (process.env.NODE_ENV === 'production' && accessKeyId && secretAccessKey) {
const writeStream = cloudwatch({
interval: 2000,
aws_access_key_id: accessKeyId,
aws_secret_access_key: secretAccessKey,
aws_region: region,
group: '/app/rsschool-api',
});
streams.push(writeStream);
}
return pinoLogger({ streams, base: null }) as ILogger;
}