This repository has been archived by the owner on May 19, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.js
66 lines (52 loc) · 1.84 KB
/
index.js
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
const logger = (writer, ...initTags) => {
const write = getWriteFn(writer)
const logFn = (message = '', fields = {}, ...callTags) =>
typeof fields === 'string'
? write({ message, tags: [...initTags, fields, ...callTags], fields: {} })
: write({ message, tags: [...initTags, ...callTags], fields })
const tag = (...additionalTags) => logger(writer, ...initTags, ...additionalTags)
return Object.assign(logFn, { tag })
}
const ratlog = Object.assign((writer, ...initTags) => {
const write = getWriteFn(writer)
return logger(log => write(stringify(log)), ...initTags)
}, { logger, stringify })
const getWriteFn = writer => writer.write ? writer.write.bind(writer) : writer
function stringify ({ tags, message, fields }) {
const joinedTags = tags.map(formatTag).join('|')
const tagString = joinedTags && `[${joinedTags}] `
const messageString = formatMessage(message)
const fieldString = Object.entries(fields || {})
.map(([k, v]) => {
const key = formatField(k)
const value = formatField(v)
return ` | ${key}${value && ': ' + value}`
}
)
.join('')
return tagString + messageString + fieldString + '\n'
}
const formatTag = val => toString(val).replace(/[|\]]/g, '\\$&')
const formatMessage = val => toString(val).replace(/[|[]/g, '\\$&')
const formatField = val => toString(val).replace(/[|:]/g, '\\$&')
const escapeNewLines = val => val.replace(/\n/g, '\\n')
function toString (val) {
if (val == null) {
return ''
}
if (typeof val === 'string') {
return escapeNewLines(val)
}
try {
return escapeNewLines(val.toString())
} catch (e) {
try {
return 'logger failed calling .toString(): ' + escapeNewLines(e.toString())
} catch (e) {
return ''
}
}
}
module.exports = ratlog
// For Typescript and other ES module use cases
module.exports.default = ratlog