log4js-node / log4js-node

A port of log4js to node.js
https://log4js-node.github.io/log4js-node/
Other
5.79k stars 774 forks source link

How to write logs in a file? #556

Closed saeta-eth closed 6 years ago

saeta-eth commented 6 years ago

Hi all.

I want to do something like it: https://stackoverflow.com/a/26731285/1741027 But I dont know why it return log4js.loadAppender is not a function

I added in each js file this code: const path = require('path') const log4js = require('log4js') const fileName = path.basename(__filename, path.extname(__filename))

log4js.loadAppender('file') log4js.addAppender(log4js.appenders.file('logs/'+ fileName +'.log'), fileName)

const logger = log4js.getLogger(fileName)

Is there a way to get the same behavior? Thanks.

nomiddlename commented 6 years ago

The stack overflow answer will work fine for version 1.x and older of log4js. Version 2.x has a different API. You can't add appenders programmatically. You'd need to do something like this:

log4js.configure({
  appenders: { 'file': { type: 'file', filename: 'logs/file.log' } },
  categories: { default: { appenders: ['file'], level: 'debug' }
});

If you want to dynamically create files based on properties in the log message (like filename above), then take a look at the multiFile appender.

saeta-eth commented 6 years ago

Really cool! Thanks @nomiddlename

saeta-eth commented 6 years ago

Hi @nomiddlename!

I implemented your suggestion. When I added these lines to 12 files appears the following error:

(node:53001) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 SIGHUP listeners added. Use emitter.setMaxListeners() to increase limit

Do you know what happens?

nomiddlename commented 6 years ago

I'd have to see a sample of the code you're using. Are you calling log4js.configure multiple times? It is only supposed to be called once in an application.

saeta-eth commented 6 years ago

Yes, I called log4js.configure multiple times. If I config the module in my main file, the config is propagated in each js file? I ask it because I have to require the module in each file if I wanna use it or is there any better way?

nomiddlename commented 6 years ago

Yes, you can call configure once in your main file. Then just require it in the other files, without calling configure, and it will use the same configuration.

saeta-eth commented 6 years ago

Cool! Thanks @nomiddlename!!