温斯顿不会登录颜色

时间:2017-10-10 15:17:17

标签: logging colors winston colorize

这不会以彩色打印到控制台。一切都是白色的。我一直在谷歌搜索几个小时。我正在运行Ubuntu 17。

// Logging with Winston
const os = require('os')
const fs = require('fs')
const path = require('path')
const config = require('../data/config/config')
const winston = require('winston')
const { createLogger, format, transports } = winston
const tsFormat = () => (new Date()).toLocaleTimeString()

const logDir = path.resolve(os.homedir(), '.test-logs')

if (!fs.existsSync(logDir)) {
  fs.mkdirSync(logDir)
}

const logger = createLogger({
  format: format.combine(
    format.splat(),
    format.simple()
  ),
  transports: [
    new transports.Console({ timestamp: tsFormat, level: config.logLevel, colorize: true }),
    new transports.File({ filename: path.resolve(logDir, 'info.log'), level: 'info' }),
    new transports.File({ filename: path.resolve(logDir, 'error.log'), level: 'error' })
  ]
})

module.exports = logger

我没有收到任何错误消息或任何内容。它只是白色。

1 个答案:

答案 0 :(得分:2)

  

修改:在回答了我自己的问题之后,通过他们github页面上的对话告诉我,您实际上可以将格式传递给传输本身。

const logger = createLogger({
  transports: [
    new transports.Console({ level: config.logLevel, format: customFormat, colorize: true, handleExceptions: true, humanReadableUnhandledException: true }),
    new transports.File({ filename: path.resolve(logDir, 'server.log'), level: 'silly' }),
    new transports.File({ filename: path.resolve(logDir, 'error.log'), level: 'error', handleExceptions: true })
  ]
})

原始答案

在实例化记录器时,您必须为格式添加colorize。他们的文档中没有这样的例子。他们对称为logForm的回购的引用完全像我刚才那样完成。它应该是一个超链接。我可能会做公关。回购是here

我必须转到他们的示例目录才能找到这个示例。

// Logging with Winston
const os = require('os')
const fs = require('fs')
const path = require('path')
const config = require('../data/config/config')
const winston = require('winston')
const { createLogger, format, transports } = winston
const { combine, timestamp, label, printf, colorize } = format
const myFormat = printf(info => {
  return `${info.timestamp} [${info.label}] ${info.level}: ${info.message}`
})

const logDir = path.resolve(os.homedir(), '.curator-server')

if (!fs.existsSync(logDir)) {
  fs.mkdirSync(logDir)
}

const logger = createLogger({
  format: combine(
    label({ label: 'Curator Server' }),
    colorize(), // Here is where the color happens
    timestamp(),
    myFormat
  ),
  transports: [
    new transports.Console({ level: config.logLevel, colorize: true, handleExceptions: true, humanReadableUnhandledException: true }),
    new transports.File({ filename: path.resolve(logDir, 'info.log'), level: 'info' }),
    new transports.File({ filename: path.resolve(logDir, 'error.log'), level: 'error', handleExceptions: true })
  ]
})

module.exports = logger