service-core/core/log.mjs

130 lines
2.9 KiB
JavaScript
Raw Normal View History

// import nodewindows from 'node-windows'
2020-09-01 17:31:38 +00:00
import bunyan from 'bunyan-lite'
import { setTimeout } from 'timers/promises'
2020-09-01 17:31:38 +00:00
export default function getLog(name, streams = null, opts = {}) {
2020-09-01 17:31:38 +00:00
let settings
let ringbuffer = new bunyan.RingBuffer({ limit: 100 })
let ringbufferwarn = new bunyan.RingBuffer({ limit: 100 })
2020-09-01 17:31:38 +00:00
if (streams) {
streams.forEach(function(stream) {
if (stream.stream === 'process.stdout') {
stream.stream = process.stdout
}
})
}
2020-09-01 17:31:38 +00:00
if (process.env.NODE_ENV === 'production') {
settings = {
"name": name,
"streams": streams || [{
2020-09-01 17:31:38 +00:00
path: 'log.log',
level: 'info',
}
]
}
} else {
settings = {
"name": name,
"streams": streams || [{
2020-09-01 17:31:38 +00:00
"stream": process.stdout,
"level": "debug"
}
]
}
}
let logger
settings.streams.push({
stream: ringbuffer,
type: 'raw',
level: 'info',
})
2020-09-07 00:47:53 +00:00
settings.streams.push({
stream: ringbufferwarn,
type: 'raw',
level: 'warn',
})
2020-09-01 17:31:38 +00:00
settings.streams.push({
stream: {
write: function(record) {
logger.emit('newlog', record)
},
end: function() {},
destroy: function() {},
destroySoon: function() {},
},
type: 'raw',
level: 'info',
})
let eventManager = null
let eventManagerLoading = false
async function safeLoadEvent(level, message, code) {
if (eventManager === false) {
return Promise.resolve()
}
if (!eventManager) {
if (eventManagerLoading) {
for (let i = 0; i < 10 && eventManagerLoading; i++) {
await setTimeout(50)
}
if (eventManagerLoading) {
eventManager = false
}
return safeLoadEvent(level, message, code)
}
eventManagerLoading = true
let prom
if (opts.import) {
prom = opts.import('node-windows')
} else {
prom = import('node-windows')
}
await prom.then(
function(res) { eventManager = new res.default.EventLogger(name) },
function() { eventManager = false },
)
eventManagerLoading = false
return safeLoadEvent(level, message, code)
}
return new Promise(function(res) {
try {
eventManager[level](message, code, function() { res() })
} catch {
res()
}
})
}
2020-09-01 17:31:38 +00:00
// Create our logger.
logger = bunyan.createLogger(settings)
2020-09-07 00:47:53 +00:00
if (process.env.NODE_ENV === 'production') {
logger.event = {
info: safeLoadEvent.bind(this, 'info'),
warn: safeLoadEvent.bind(this, 'warn'),
error: safeLoadEvent.bind(this, 'error'),
}
2020-09-07 00:47:53 +00:00
} else {
logger.event = {
info: function() { return Promise.resolve() },
warn: function() { return Promise.resolve() },
error: function() { return Promise.resolve() },
2020-09-07 00:47:53 +00:00
}
}
2020-09-01 17:31:38 +00:00
logger.ringbuffer = ringbuffer
2020-09-07 00:47:53 +00:00
logger.ringbufferwarn = ringbufferwarn
2020-09-01 17:31:38 +00:00
return logger
}