Logging in nodejs using bunyan logger

11.4k Views Asked by At

I am initializing the bunyan logger in my nodejs code as below:

var log = bunyan.createLogger({
    name: 'myapp',
    stream: process.stdout,
    level: 'info'
});

This is from the bunyan docs at https://www.npmjs.org/package/bunyan

The docs mention:

By default, log output is to stdout and at the "info" level.

What I am wondering is: shouldn't the logger be asking me for a file name where I want things logged. Where is the logging happening?

3

There are 3 best solutions below

0
On

Try this ...

var Logger = require('bunyan');
var applogger = new Logger({
  name: 'helloapi',
  streams: [
    {
      level: 'info',
      path: './log/applogging.log'
    }
  ]
});

check their home page for further instructions https://github.com/trentm/node-bunyan#streams-introduction

Hope this has helped. :)

1
On

Steps to install bunyan logger:

npm install bunyan bunyan-rotating-file-stream --save

By bunyan-rotating-file-stream module we can set the logfile with datetime.

create logs folder manually.

    var bunyan  = require('bunyan');
    var RotatingFileStream = require('bunyan-rotating-file-stream');

    var applogger = new bunyan.createLogger({
        name: 'project name',            
        streams: [{
            stream: new RotatingFileStream({
                type: 'rotating-file',
                path: './logs/server-%Y%m%d.log',
                period: '1d',          // daily rotation 
                totalFiles: 2,        // keep up to 10 back copies 
                rotateExisting: true,  // Give ourselves a clean file when we start up, based on period 
                threshold: '10m',      // Rotate log files larger than 10 megabytes 
                totalSize: '20m',      // Don't keep more than 20mb of archived log files 
                gzip: true,             // Compress the archive log files to save space 
                template: 'server-%Y%m%d.log' //you can add. - _ before datestamp.
            })
        }]
    });
0
On
process.stdout is for Logging on Console.

If you want to log on a file you need to provide different streams.

var log = bunyan.createLogger({ 
                name: 'myapp',
                streams: [
                    {
                        level: 'trace',
                        stream: process.stdout
                    },
                    {
                        level: 'warn',
                        path: './filename.log'
                    }
                ]
            });