Objective: We create log file (Daily log file: info.log.2016-08-22) Source code github
- Show log in Console and in File
Implementation
- Create project using Express generator
Note: if you don't have express generator you can install via command lineexpress -e winstonjs-console-and-file
npm install express-generator -g
- Install Winston
npm install --save winston@0.8.3
- Open app.js write some code
var FileStreamRotator = require('file-stream-rotator'); var fs = require('fs'); var logDirectory = __dirname + '/logs' // ensure log directory exists fs.existsSync(logDirectory) || fs.mkdirSync(logDirectory); // create a rotating write stream var accessLogStream = FileStreamRotator.getStream({ filename: logDirectory + '/access-%DATE%.log', frequency: 'daily', verbose: false, date_format: 'YYYY-MM-DD' }); app.use(morgan('combined', {stream: accessLogStream}));
- Create folder logger then file index.js
var winston = require("winston"); if(process.env == 'production') { winston.level = 'info'; } else { winston.level = 'debug'; } winston.loggers.add('info', { console: { level: winston.level, colorize: true, label: 'category one' }, file: { level: winston.level, colorize: 'true', filename: __dirname + '/../logs/info/info.log', datePattern: '.yyyy-MM-dd', //maxsize: 20000, json: false }, DailyRotateFile: { level: winston.level, colorize: 'true', filename: __dirname + '/../logs/info/info.log', datePattern: '.yyyy-MM-dd', //maxsize: 20000, json: false } }); module.exports = winston.loggers.get('info');
- How to use: call file /logger/index.js
var logger = require("../logger"); logger.info("This is logger.");
- Result: It shows in Console and File
No comments:
Post a Comment