-
-
Notifications
You must be signed in to change notification settings - Fork 11.4k
Expand file tree
/
Copy pathlogging-utils.js
More file actions
84 lines (74 loc) · 2.21 KB
/
logging-utils.js
File metadata and controls
84 lines (74 loc) · 2.21 KB
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
const bunyan = require('bunyan');
const {PassThrough} = require('stream');
const logging = require('@tryghost/logging');
/**
* Parse newline-delimited JSON log records from a buffered string.
*
* @param {string} buffer - Buffered log text that may contain multiple records.
* @param {Array<object>} output - Collected parsed log records.
* @returns {string} Remaining partial record that did not end with a newline.
*/
function parseBufferedJsonLogs(buffer, output) {
const lines = buffer.split('\n');
const remaining = lines.pop();
for (const line of lines) {
if (!line.trim()) {
continue;
}
output.push(JSON.parse(line));
}
return remaining;
}
/**
* Temporarily redirects Ghost logger streams to an in-memory Bunyan stream.
*
* This allows tests to assert on real serialized JSON output from
* `@tryghost/logging` without stubbing logger methods.
*
* @returns {{output: Array<object>, restore: () => void}} Capture handle.
*/
function captureLoggerOutput() {
const output = [];
const stream = new PassThrough();
let buffered = '';
stream.on('data', (chunk) => {
buffered += chunk.toString();
buffered = parseBufferedJsonLogs(buffered, output);
});
const originalStreams = logging.streams;
logging.streams = {
capture: {
name: 'capture',
log: bunyan.createLogger({
name: 'test-logger',
streams: [{
type: 'stream',
stream,
level: 'trace'
}]
})
}
};
return {
output,
restore() {
buffered = parseBufferedJsonLogs(buffered, output);
logging.streams = originalStreams;
stream.destroy();
}
};
}
/**
* Find the first structured log record matching a system event.
*
* @param {Array<object>} output - Captured log records.
* @param {string} event - Structured event name to match.
* @returns {object|undefined} First matching log record.
*/
function findByEvent(output, event) {
return output.find(log => log.system?.event === event);
}
module.exports = {
captureLoggerOutput,
findByEvent
};