Winston文件传输日志转义字符

时间:2016-05-12 18:05:58

标签: logging sails.js winston

我正在使用winston登录Sails应用程序。这是我的配置:

var customLogger = new winston.Logger({
    transports: [
        new(winston.transports.File)({
            level: 'debug',
            filename: 'app.log',
            colorize: false,
            showLevel: false,
            prettyPrint: false,
            exitOnError: false,
            json: true,
            zippedArchive: true,
            maxsize: 1000000000,
            maxFiles: 30,
            tailable: true
        }),
        new(winston.transports.Console)({
            level: 'info',
            exitOnError: false,
            colorize: false,
            showLevel: false
        })
    ],
});

但是在输出文件中有奇数字符。

{"level":"info","message":"\u001b[32minfo: \u001b[39m","timestamp":"2016-05-12T17:58:03.281Z"}

2 个答案:

答案 0 :(得分:0)

目前在帆中,您无需使用customLogger来使用Winston。您可以安装sails-hook-winston。比你的config/log.js看起来像那样:

var path = require('path');
var pkgJSON = require(path.resolve('package.json'));

module.exports.log = {

    // This options are for Console transport that is used by default
    level: 'info', // you are familiar with this value, right?
    timestamp: true, // if you want to output the timestamp in the console transport
    colors: false,
    // Transports
    // more information: https://github.com/winstonjs/winston/blob/master/docs/transports.md
    transports: [{
        module: require('winston-daily-rotate-file'),
        config: {
            dirname: path.resolve('logs'),
            datePattern: '.yyyy-MM-dd.log',
            filename: pkgJSON.name,
            prettyPrint: true,
            timestamp: true,
            level: 'info',
            json: true,
            colors: false
        }
    }]
};

您可以在不同日志级别的同时使用少量transports

答案 1 :(得分:0)

我确实遇到了类似的问题,并通过从下面的代码中删除 winston.format.colorize() 语句来解决它,以删除作为日志文件一部分的奇怪或转义代码。< /p>

const logFormat = winston.format.combine (
winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss.SSS' }),
winston.format.colorize(),
winston.format.align(),
winston.format.printf(
    info => `${info.timestamp} ${info.level.toUpperCase()}: ${info.message}`    
));

虽然下面分享的是完整的工作代码,没有任何与奇数或转义代码相关的问题。

作为 /zipCode/config/default.json 文件的一部分捕获的默认配置

{
   "port":      3000,
   "logConfig": {
        "logFolder":    ".//logs//",
        "logFile":      "zip-code-%DATE%.log",
        "logLevel":     "info"
    }
}

将创建记录器实现合并为 /zipCode/logger/log.js 文件的一部分

/**
 * @author: dinesh.lomte
 */
const winston = require('winston');
const dailyRotateFile = require('winston-daily-rotate-file');
const config = require('config');
const logFormat = winston.format.combine (
    winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss.SSS' }),
    winston.format.align(),
    winston.format.printf(
        info => `${info.timestamp} ${info.level.toUpperCase()}: ${info.message}`    
    )
);
const transport = new dailyRotateFile({
    filename:       config.get('logConfig.logFolder') + config.get('logConfig.logFile'),
    datePattern:    'YYYY-MM-DD',
    zippedArchive:  true,
    maxSize:        '20m',
    maxFiles:       '14d',
    level:          config.get('logConfig.logLevel')        
});

transport.on('rotate', function(oldFile, newFile) {
    // Call function like upload to s3 or on cloud
});

const logger = winston.createLogger({
    format:     logFormat,
    transports: [
        transport,
        new winston.transports.Console({
            level:  config.get('logConfig.logLevel')
        })
    ]
});

module.exports = logger;

/zipCode/api/controller.js文件下面显示了记录器的用法

/**
 * @author: dinesh.lomte
 */
'use strict';

var distance = require('../service/distance');
var logger = require('../logger/log');

var controllers = {
    get_distance: function(req, res) {
        logger.info('Processing get_distance request...');
        distance.find(req, res, function(err, dist) {
            if (err) {
                logger.error('Failed to process distance request, due to: ' + err);
                res.send(err);
            }
            logger.debug('Processed get_distance request...');
            res.json(dist);
        });
    }
};

module.exports = controllers;