简体   繁体   中英

log4js - how to specify log file name with an environment variable?

I am using log4js-node to log in my node js application. I want to specify the path to the log file name inside my log4js config json using an environment variable. Here is the config json I am using:

{
    "appenders": [{
        "type": "file",
        "filename": "${env.API_HOME}/logs/apiserver_log_file.log",
        "maxLogSize": 20480,
        "backups": 3,
        "category": "apiserver"
    }]
}

When the application starts, it can't find the specified path because the environment variable is not correctly read.

Error: ENOENT, open '${env.API_HOME}/logs/apiserver_log_file.log'

How do I use the environment variables correctly inside the log4js configuration json?

Example:

var log4js = require('log4js'); 
//console log is loaded by default, so you won't normally need to do this
//log4js.loadAppender('console');
log4js.loadAppender('file');
//log4js.addAppender(log4js.appenders.console());
log4js.addAppender(log4js.appenders.file('logs/cheese.log'), 'cheese');

var logger = log4js.getLogger('cheese');
logger.setLevel('ERROR');

logger.trace('Entering cheese testing');
logger.debug('Got cheese.');
logger.info('Cheese is Gouda.');
logger.warn('Cheese is quite smelly.');
logger.error('Cheese is too ripe!');
logger.fatal('Cheese was breeding ground for listeria.');

Output:

[2010-01-17 11:43:37.987] [ERROR] cheese - Cheese is too ripe! [2010-01-17 11:43:37.990] [FATAL] cheese - Cheese was breeding ground for listeria.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM