I have several modules - let's say server.js, module1.js,...,moduleN.js.
I would like define the log file in my server.js:
winston.add(winston.transports.File, { filename: 'mylogfile.log' });
and then use it in all my modules.
What is the best way to do that? I could exports.winston=winston;
in each module and then set it in the server.js, but is there any better solution?
Thank you in advance!
I'm creating a new Winston logger.
log.js
a.js
b.js
if you want to make the logger a global variable- you have to do specifically by assign it to the global variable like so
logger.js
app.js
someController.js
Note: it's good practice to assign a prefix for every global variable so you will know that is a global one. i'm using __ as prefix (double low dash)
What I do ( which may not be the best way ) is use a 'global' module where I export all the stuff that I use through my applications. For instance:
Now just require this globally used module from your other modules
Because the file is cached after the first time it is loaded (which you can verify by including a log statement in your global; it will only log once), there's very little overhead in including it again. Putting it all into one file is also easier than requiring ALL your globally used modules on every page.
The default logger concept handles this nicely.
Winston defines a default logger that any straight require (and subsequent require) to winston will retrieve. Thus you simply configure this default logger once, and it's available for subsequent module use via vanilla require('winston') in its glorious tweaked multi-transport mode.
e.g. here is my complete logging setup that defines 3 transports. I swap Loggly for MongoDB sometimes.
server.js
all other .js files
log.js - this is a one time configuration of the DEFAULT logger
Alternatively for more complex scenarios you can use winston containers and retrieve the logger from a named container in other modules. I haven't used this.
My only issue with this was a missing logs directories on my deployment host which was easily fixed.
Hope this helps.
Slightly off topic (as the OP asks about Winston), but I like the 'child-logger' approach by Bunyan:
It solves the OP's problem as the logger is available through the req object (hence no need for 'require(log)' in each module). Additionally, all log entries belonging to a particular request will have a unique ID that connects them together.
I'm not sure if Winston supports this as well.
I am working on Winston 3.0.0 right now. And it seems the way to configure the default logger has changed a little bit. The way that works for me is folloing:
log.js// the setting for global logger
The other part is the same. In the beginning of you application,
require('log.js')
, and alsorequire ('winston'),
While in all other files, simplyrequire('winston')
.