在Node.js中,可以使用一些流行的日志库和工具来有效地提取异常信息。以下是一些建议:
例如,使用Winston:
const winston = require('winston');
const logger = winston.createLogger({
level: 'info',
format: winston.format.json(),
transports: [
new winston.transports.File({ filename: 'error.log', level: 'error' }),
new winston.transports.File({ filename: 'combined.log' }),
],
});
// 捕获异常
process.on('uncaughtException', (err) => {
logger.error('Uncaught Exception:', err);
});
// 捕获未处理的Promise拒绝
process.on('unhandledRejection', (reason, promise) => {
logger.error('Unhandled Rejection at:', promise, 'reason:', reason);
});
try {
// 你的代码
} catch (error) {
console.error('Error:', error);
}
async function myFunction() {
try {
// 你的代码
} catch (error) {
console.error('Error:', error);
}
}
process.on('error', (err) => {
console.error('Error:', err);
});
通过使用这些方法和工具,你可以有效地提取Node.js日志中的异常信息,并采取适当的措施来解决问题。