I'm using nodejs with postgres database and a lot of schemas (and pm2 as process manager). Each schema is a user, so in every query i pass schema name as parameter. At the moment all console.logs are written on a single file, rotated by pm2. My goal is to have a separated log for every schema/user, for example user_1.log, user_2.log and so on. Is there a way/node module to make this?
thanks
What about passing custom log file path and environment variable when starting pm2 process?
SCHEMA_USER=user_1 pm2 start app.js -i 1 -o ./logs/user_1.log -e ./logs/user_1.err
SCHEMA_USER=user_2 pm2 start app.js -i 1 -o ./logs/user_2.log -e ./logs/user_2.err
or You can use simple-node-logger and make logger storage which will deliver objects that will log to Your desired location.
create log-manager.js
somewhere with such content:
const path = require('path');
const SimpleNodeLogger = require('simple-node-logger'),
class LogManager {
static instances = {};
static get(key) {
if (!key) return console;
if (Logger.instances[key]) return Logger.instances[key];
const opts = {
logFilePath: path.join(__dirname, 'logs', key+'.log'),
timestampFormat: 'YYYY-MM-DD HH:mm:ss.SSS'
},
return Logger.instances[key] = SimpleNodeLogger.createSimpleLogger(opts);
}
}
module.exports = LogManager;
and use it for example with express application:
const logManager = require('./log-manager');
request.get('/users/:id', (req, res) => {
const logger = logManager.get('user_' + req.params.id);
// doing somethings
logger.error('User not found');
req.status(404).send({});
});