log4js配置问题求解
发布于 13 天前 作者 vitozyf 381 次浏览 最后一次编辑是 10 天前 来自 问答

求解log4js这样配置为什么所有信息都会跑到两个文件,并没有分类?

附上代码:

配置如下:

// ALL < TRACE < DEBUG < INFO < WARN < ERROR < FATAL < MARK < OFF
const config = {
  appenders: {
    loginfo: {
      type: 'file',
      filename: 'Logs/application.log',
      pattern: "yyyy-MM-dd",
      level: 'DEBUG',
      maxLevel: 'WARN',
      layout: {
        type: 'json',
        separator: ','
      }
    },
    logerror: {
      type: 'dateFile',
      filename: 'Logs/error.log',
      pattern: "yyyy-MM-dd",
      level: 'error',
      maxLevel: 'error',
      layout: {
        type: 'json',
        separator: ','
      }
    }
  },
  categories: {
    default: {
      appenders: ['loginfo', 'logerror'],
      level: 'debug'
    },
    loginfo: {
      appenders: ['loginfo'],
      level: 'info'
    },
    logerror: {
      appenders: ['logerror'],
      level: 'error'
    }
  },
  pm2: true
}
module.exports = config

测试代码:

    Logger.error('0000000000000000000')
    Logger.info('111111111111111111111111')

日志文件application.log和error.log输出如下,都输出一样,没分类:

{"startTime":"2018-08-17T09:00:09.723Z","categoryName":"default","data":["0000000000000000000"],"level":{"level":40000,"levelStr":"ERROR","colour":"red"},"context":{},"pid":19936},
{"startTime":"2018-08-17T09:00:09.724Z","categoryName":"default","data":["111111111111111111111111"],"level":{"level":20000,"levelStr":"INFO","colour":"green"},"context":{},"pid":19936},
5 回复

顶下

categories你只设置了default,所以所有高于DEBUG的日志都会写入指定的appenders中

@peasonlee 如内容所示,把categories中配置改了下,单输出还是一样,想要记录error级别的那个文件还是输出了info内容

@vitozyf

'use strict';

const log4js = require('log4js');
const infoName = 'log-info.log', errorName = 'log-error.log';

const configOpts = {
    appenders: {
        info: {
            type: 'file',
            filename: infoName,
            category: 'info'
        },
        error: {
            type: 'file',
            filename: errorName,
            category: 'error'
        }
    },
    categories: {
        default: { appenders: ['info'], level: 'debug' },
        error: { appenders: ['error'], level: 'error' }
    }
};
log4js.configure(configOpts);

//info logger
const logger = log4js.getLogger();
//error logger
const errLogger = log4js.getLogger('error');

function testLogger() {
    logger.debug('this is debug');
    logger.info('this is info');
    logger.error('this is info');

    errLogger.debug('this is debug');
    errLogger.info('this is info');
    errLogger.error('this is info');
}
testLogger();

@peasonlee 感谢!解决了,主要是我这边getLogger之前没传参进去,导致都走的是default的配置。

回到顶部