-
Notifications
You must be signed in to change notification settings - Fork 8.3k
/
Copy pathlog_format.ts
163 lines (146 loc) · 5.15 KB
/
log_format.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
161
162
163
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* and the Server Side Public License, v 1; you may not use this file except in
* compliance with, at your election, the Elastic License or the Server Side
* Public License, v 1.
*/
import Stream from 'stream';
import moment from 'moment-timezone';
import _ from 'lodash';
import queryString from 'query-string';
import numeral from '@elastic/numeral';
import chalk from 'chalk';
// @ts-expect-error missing type def
import stringify from 'json-stringify-safe';
import { inspect } from 'util';
import { applyFiltersToKeys } from './utils';
import { getLogEventData } from './metadata';
import { LegacyLoggingConfig } from './schema';
import {
AnyEvent,
isResponseEvent,
isOpsEvent,
isErrorEvent,
isLogEvent,
isUndeclaredErrorEvent,
} from './log_events';
export type LogFormatConfig = Pick<LegacyLoggingConfig, 'json' | 'dest' | 'timezone' | 'filter'>;
function serializeError(err: any = {}) {
return {
message: err.message,
name: err.name,
stack: err.stack,
code: err.code,
signal: err.signal,
};
}
const levelColor = function (code: number) {
if (code < 299) return chalk.green(String(code));
if (code < 399) return chalk.yellow(String(code));
if (code < 499) return chalk.magentaBright(String(code));
return chalk.red(String(code));
};
export abstract class BaseLogFormat extends Stream.Transform {
constructor(private readonly config: LogFormatConfig) {
super({
readableObjectMode: false,
writableObjectMode: true,
});
}
abstract format(data: Record<string, any>): string;
filter(data: Record<string, unknown>) {
if (!this.config.filter) {
return data;
}
return applyFiltersToKeys(data, this.config.filter);
}
_transform(event: AnyEvent, enc: string, next: Stream.TransformCallback) {
const data = this.filter(this.readEvent(event));
this.push(this.format(data) + '\n');
next();
}
extractAndFormatTimestamp(data: Record<string, any>, format?: string) {
const { timezone } = this.config;
const date = moment(data['@timestamp']);
if (timezone) {
date.tz(timezone);
}
return date.format(format);
}
readEvent(event: AnyEvent) {
const data: Record<string, any> = {
type: event.event,
'@timestamp': event.timestamp,
tags: [...(event.tags || [])],
pid: event.pid,
};
if (isResponseEvent(event)) {
_.defaults(data, _.pick(event, ['method', 'statusCode']));
const source = _.get(event, 'source', {});
data.req = {
url: event.path,
method: event.method || '',
headers: event.headers,
remoteAddress: source.remoteAddress,
userAgent: source.userAgent,
referer: source.referer,
};
const contentLength =
event.responsePayload === 'object'
? stringify(event.responsePayload).length
: String(event.responsePayload).length;
data.res = {
statusCode: event.statusCode,
responseTime: event.responseTime,
contentLength,
};
const query = queryString.stringify(event.query, { sort: false });
if (query) {
data.req.url += '?' + query;
}
data.message = data.req.method.toUpperCase() + ' ';
data.message += data.req.url;
data.message += ' ';
data.message += levelColor(data.res.statusCode);
data.message += ' ';
data.message += chalk.gray(data.res.responseTime + 'ms');
data.message += chalk.gray(' - ' + numeral(contentLength).format('0.0b'));
} else if (isOpsEvent(event)) {
_.defaults(data, _.pick(event, ['pid', 'os', 'proc', 'load']));
data.message = chalk.gray('memory: ');
data.message += numeral(_.get(data, 'proc.mem.heapUsed')).format('0.0b');
data.message += ' ';
data.message += chalk.gray('uptime: ');
data.message += numeral(_.get(data, 'proc.uptime')).format('00:00:00');
data.message += ' ';
data.message += chalk.gray('load: [');
data.message += _.get(data, 'os.load', [])
.map((val: number) => {
return numeral(val).format('0.00');
})
.join(' ');
data.message += chalk.gray(']');
data.message += ' ';
data.message += chalk.gray('delay: ');
data.message += numeral(_.get(data, 'proc.delay')).format('0.000');
} else if (isErrorEvent(event)) {
data.level = 'error';
data.error = serializeError(event.error);
data.url = event.url;
const message = _.get(event, 'error.message');
data.message = message || 'Unknown error (no message)';
} else if (isUndeclaredErrorEvent(event)) {
data.type = 'error';
data.level = _.includes(event.tags, 'fatal') ? 'fatal' : 'error';
data.error = serializeError(event.error);
const message = _.get(event, 'error.message');
data.message = message || 'Unknown error object (no message)';
} else if (isLogEvent(event)) {
_.assign(data, getLogEventData(event.data));
} else {
data.message = _.isString(event.data) ? event.data : inspect(event.data);
}
return data;
}
}