У меня есть регистратор, и я расширяю Winston
, чтобы добавить некоторую дополнительную информацию о промежуточном программном обеспечении в мои зарегистрированные запросы. У меня возникли проблемы с объектами, через которые я карри через, закончился как [object object]
вместо фактического JSON объекта.
Пример использования (тест. js)
let objectEntity = {test: 'test'}
logger.info(`This is a test: ${objectEntity}`)
В настоящее время это приводит к: This is a test: [object Object]
Каков наилучший способ получить красивую печать фактического объекта без необходимости Stringify всех параметров в моем коде? Пока что я могу исправить только
logger.info(`This is a test: ${JSON.stringify(objectEntity)}`)
Logger Class
const { transports, createLogger, format } = require('winston')
const httpContext = require('express-http-context')
const prettyJson = format.printf(info => {
if (info.message.constructor === Object) {
info.message = JSON.stringify(info.message, null, 4)
}
return `${info.level}\t(${info.time}):\t${info.message} ${info.reqId}`
})
const winstonLogger = createLogger({
level: process.env.LOG_LEVEL || 'debug',
format: format.combine(
format(info => {
info.level = '[' + info.level.toUpperCase() + ']'
info.reqId = info.reqId || ''
info.time = new Date().toISOString()
return info
})(),
format.colorize(),
format.prettyPrint(),
format.splat(),
format.simple(),
format.timestamp(),
prettyJson
),
transports: [new transports.Console()],
})
const logger = {
log: function(level, message, opts) {
winstonLogger.log(level, { reqId: httpContext.get('reqId'), message })
},
error: function(message) {
winstonLogger.error({ reqId: httpContext.get('reqId'), message })
},
warn: function(message) {
winstonLogger.warn({ reqId: httpContext.get('reqId'), message })
},
verbose: function(message) {
winstonLogger.verbose({ reqId: httpContext.get('reqId'), message })
},
info: function(message) {
winstonLogger.info({ reqId: httpContext.get('reqId'), message })
},
debug: function(message) {
winstonLogger.debug({
reqId: httpContext.get('reqId'),
message,
})
},
silly: function(message) {
winstonLogger.silly({ reqId: httpContext.get('reqId'), message })
},
}
module.exports = logger