如何使用像 Bunyan 这样的记录器捕获错误?
How to catch errors with loggers like Bunyan?
我是 运行 Docker 容器内的 NodeJS 脚本,它位于 Google 计算实例内的容器优化 OS 内。
简单 console.log()
未到达 Google Cloud Logger。因此我正在使用 bunyan
库。
但是,我有两个问题:
- 我使用的一些库只是将日志写入
stdout
,我无法看到它们,除非通过 SSH 连接到 GCE 实例并在那里四处寻找。
- 我是一个人,可能会搞砸线程或其他事情。在这种情况下,可能会发生错误,该错误也不会显示在 Cloud Logger 中。
所以,问题是:如何让 NodeJS 将 stdout
和 stderr
日志发送到 Cloud Logger?
这是一个例子:
import { createLogger } from 'bunyan'
const { LoggingBunyan } = require('@google-cloud/logging-bunyan')
import sourceMap from 'source-map-support'
sourceMap.install()
function startLogger () {
let streams: any[] = []
if (process.env.__DEV__) {
streams.push({ stream: process.stdout, level: 'debug' })
} else {
const loggingBunyan = new LoggingBunyan()
streams.push(loggingBunyan.stream('debug'))
}
return createLogger({ name: 'my-script', streams })
}
const logger = startLogger()
process.on('unhandledRejection', logger.error)
const start = async () => {
logger.info(`hello`)
try {
logger.info(`start`)
setTimeout(() => {
throw Error('error from timeout') // <= this must be caught by bunyan and sent to Clodu Logger
}, 1000)
sleep(5000)
logger.info(`finish`)
} catch (e) {
logger.error('crash:', e)
}
}
start()
function sleep (time: number) {
return new Promise(function (resolve) {
setTimeout(resolve, time)
})
}
通过这个(可能过多的)例子,我试图展示一个意外的未处理错误。我知道我可以将 try-catch 放在 setTimout
回调中。这只是一个例子。
不要让你的服务器崩溃:
process.setUncaughtExceptionCaptureCallback(logger.error);
process.on('unhandledRejection', e => logger.error(e));
我是 运行 Docker 容器内的 NodeJS 脚本,它位于 Google 计算实例内的容器优化 OS 内。
简单 console.log()
未到达 Google Cloud Logger。因此我正在使用 bunyan
库。
但是,我有两个问题:
- 我使用的一些库只是将日志写入
stdout
,我无法看到它们,除非通过 SSH 连接到 GCE 实例并在那里四处寻找。 - 我是一个人,可能会搞砸线程或其他事情。在这种情况下,可能会发生错误,该错误也不会显示在 Cloud Logger 中。
所以,问题是:如何让 NodeJS 将 stdout
和 stderr
日志发送到 Cloud Logger?
这是一个例子:
import { createLogger } from 'bunyan'
const { LoggingBunyan } = require('@google-cloud/logging-bunyan')
import sourceMap from 'source-map-support'
sourceMap.install()
function startLogger () {
let streams: any[] = []
if (process.env.__DEV__) {
streams.push({ stream: process.stdout, level: 'debug' })
} else {
const loggingBunyan = new LoggingBunyan()
streams.push(loggingBunyan.stream('debug'))
}
return createLogger({ name: 'my-script', streams })
}
const logger = startLogger()
process.on('unhandledRejection', logger.error)
const start = async () => {
logger.info(`hello`)
try {
logger.info(`start`)
setTimeout(() => {
throw Error('error from timeout') // <= this must be caught by bunyan and sent to Clodu Logger
}, 1000)
sleep(5000)
logger.info(`finish`)
} catch (e) {
logger.error('crash:', e)
}
}
start()
function sleep (time: number) {
return new Promise(function (resolve) {
setTimeout(resolve, time)
})
}
通过这个(可能过多的)例子,我试图展示一个意外的未处理错误。我知道我可以将 try-catch 放在 setTimout
回调中。这只是一个例子。
不要让你的服务器崩溃:
process.setUncaughtExceptionCaptureCallback(logger.error);
process.on('unhandledRejection', e => logger.error(e));