Using Winston Logger in Node.js
Winston logger is commonly used logger in Node.js. Most of the case, I use winston logger and also integration outputs of morgan into winston. I recalled that the first time I used winston, I followed some of the online tutorials regarding how to config and use it, but there are always problems here and there for my scenarios. Therefore, I decide to write this to blog to introduce how I config winston logger in my projects.
Project Structure
I normally put the configuration file of winston logger like the following:
1 | Project |
Then in *.js files, it will use the winston config file like the following:
1 | const winstonLogger = require('./config/winston'); |
Winston Configuration File Explained
The conent of the configuration file winston.js mentioned in the previous section is shown below:
1 | const appRoot = require('app-root-path'); |
To explain the above sourcecode in details:
Set Colors for Logger Levels
1 | const colors = { |
Config Other Settings of Winston
For the following settings, please refer to the official site of winston logger. I would emphasize two things:
On the transports part. In the following configuration, I put loggers into files under the directory /log/*.log files. That is a very basic settings, you can of course adding settings like, generate new log files after the current log file reach to certain size, and further config organizing log files according to their generated date.
If not in “production” environment, I set the logger still output on the console for facilitating debugging.
1 | // define the custom settings for each transport (file, console) |
Merge Morgan into Winston
The following code will merge morgan into winston.
1 | logger.stream = { |
Config Morgan
To make winston working with morgan, we will need to add the following morgan settings:
- File directory:
1
2
3
4
5
6
7
8Project
| ...
├───middleware
│ ├───morgan.js
│ ...
├───app.js
├───package.json
| ... - Config morgan:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16const morgan = require('morgan');
const logger = require('../config/winston');
const morganMiddleware = morgan(
// Define message format string (this is the default one).
// The message format is made from tokens, and each token is
// defined inside the Morgan library.
// You can create your custom token to show what do you want from a request.
'combined',
// Options: in this case, I overwrote the stream and the skip logic.
// See the methods above.
{ stream: logger.stream },
);
module.exports = morganMiddleware; - Use in app.js
1
2
3
4
5
6...
const morganMiddleware = require('./middleware/morgan');
...
app.use(morganMiddleware);
...
If things go well …
You should be able to see logger in the console like the following:
And also the same records can be find in the log files: /log/*.log files.