SlideShare a Scribd company logo
1 of 20
Logging your Node.js
Application
Md. SOHEL RANA
About Me
• Founder, NerdDevs
• Software Architect, TestReach
• Node.js Trainer
• Working in Software Development for 12 years
• Last 6 years only working in JavaScript
• Loves backbone.js
http://www.nerddevs.com
twitter : @sohel023010
skype : sohel023010
https://github.com/sohel-rana
What is Logger
• A device or computer program
• Creates a systematic recording of events, observations, or measurements.
• Application, System, OS etc
• Helps to debug/trace issues
What is Logger
• Timestamp
• Source
• Event Type(error, info, debug etc)
• Message
What is Logger
Mac Console
Logger in node.js
• node-bunyan
• Morgan
• Winston
• Debug
bunyan
• Logs as JSON
const bunyan = require('bunyan’);
const log = bunyan.createLogger({name: 'myapp'});
log.info('hi’);
log.warn({lang: 'fr'}, 'au revoir’);
{"name":"myapp","hostname":"banana.local","pid":40161,"level":30,"msg":"hi","time":"201
3-01-04T18:46:23.851Z","v":0}
morgan
• Logs http request
// create a write stream (in append mode)
let accessLogStream = fs.createWriteStream(path.join(__dirname, 'access.log'), { flags: 'a’ });
// setup the logger
app.use(morgan('combined', { stream: accessLogStream }));
app.get('/', function (req, res) { res.send('hello, world!') })l
Winston
• Universal logger
• Supports multiple transports
• Supports ELK/EFK
• Two way to use, own logger or default
Winston
const getLoggerInstance = (level, logType) => {
return winston.createLogger({
format: winston.format.combine(
winston.format.label({ label: logType }),
winston.format.timestamp(),
customFormat
),
exitOnError: false,
transports: [
new FluentTransport(`testreach.${logType}`, _.extend(logConfig, {level})),
new winston.transports.DailyRotateFile({
level: level,
filename: `logs/%DATE%/${logType}.log`
})
]
});
};
An Example
Winston
winston.exceptions.handle(
new FluentTransport('testreach.unhandledExceptions', _.extend(logConfig,
{level: 'error'})),
new winston.transports.DailyRotateFile({
level: 'error',
filename: 'logs/%DATE%/unhandledExceptions.log'
})
);
Exception Handling
Winston
exports.logRequests = function (request, response) {
let userName = 'N/A';
if (request.user && request.user.username) {
userName = request.user.username;
}
if (request.xhr && request.method.trim() !== 'GET') {
if (request.body && JSON.stringify(request.body).indexOf('password') === -1) {
let allTexts = '';
if (userName) {
allTexts = `[ ${userName} ]- ${request.method}: ${request.url}`;
} else {
allTexts = `[ unknownUser ]- ${request.method}: ${request.url}`;
}
allTexts += `, Payload: ${JSON.stringify(request.body)}`;
loggerXhr.debug(allTexts);
}
}
};
Logger.js
Usage in application
const LoggerService = require('./services/Logger.js');
app.use(function (request, response, next) {
LoggerService.logRequests(request, response);
next();
});
app.js
Fluentd
• Unified logger
• Act as log collector
• Structures the data as JSON
Winston and Fluentd
• Use fluent-logger module
• Create a transport with tag
• Use that transport in Winston
let fluentTransport = require('fluent-
logger').support.winstonTransport();
let fluent = new fluentTransport('mytag', config);
let logger = winston.createLogger({ transports: [fluent, new
(winston.transports.Console)()] });
//Fleuntd config
<source>
@type forward port 24224
</source>
<match mytag.*>
@type stdout
</match>
Using EFK
Key points
• EFK – stands for Elasticsearch,
Fluentd and Kibana
• Elasticsearch stores the data in a
structured way and manages the
indexes for efficient searching
• Kibana a tool, helps to visualize the
data
Steps
• Create fluentd transport in winston
• Forward the logs to Elasticsearch
• Configure kibana to connect with
Elasticsearch
• Install necessary plugins
Kibana
Useful Practices
• Only log error from top level
• There is enough info
• Name the steps properly in debug
Useful Practices
• Error log
LoggerService.errorLog(error, req.user, ‘myController: User.save()’);
• Debug
Logger.loggerUserCall(`[Rejecting Incoming Call] ${JSON.stringify(requestData)}`);
Logger.loggerNumber(`[Buy number request] ${JSON.stringify(userNumberToBeSaved)}`);
Questions

More Related Content

What's hot

Life in a Queue - Using Message Queue with django
Life in a Queue - Using Message Queue with djangoLife in a Queue - Using Message Queue with django
Life in a Queue - Using Message Queue with djangoTareque Hossain
 
Excel shortcut and function keys hindi notes
Excel shortcut and function keys hindi notesExcel shortcut and function keys hindi notes
Excel shortcut and function keys hindi notesSirajRock
 
Présentation Git & GitHub
Présentation Git & GitHubPrésentation Git & GitHub
Présentation Git & GitHubThibault Vlacich
 
An introduction to JVM performance
An introduction to JVM performanceAn introduction to JVM performance
An introduction to JVM performanceRafael Winterhalter
 
Tcp ip & io model
Tcp ip & io modelTcp ip & io model
Tcp ip & io modelNam Hyeonuk
 

What's hot (7)

Les bases de git
Les bases de gitLes bases de git
Les bases de git
 
Life in a Queue - Using Message Queue with django
Life in a Queue - Using Message Queue with djangoLife in a Queue - Using Message Queue with django
Life in a Queue - Using Message Queue with django
 
Excel shortcut and function keys hindi notes
Excel shortcut and function keys hindi notesExcel shortcut and function keys hindi notes
Excel shortcut and function keys hindi notes
 
Présentation Git & GitHub
Présentation Git & GitHubPrésentation Git & GitHub
Présentation Git & GitHub
 
An introduction to JVM performance
An introduction to JVM performanceAn introduction to JVM performance
An introduction to JVM performance
 
Tcp ip & io model
Tcp ip & io modelTcp ip & io model
Tcp ip & io model
 
Vi Editor
Vi EditorVi Editor
Vi Editor
 

Similar to Logging your node.js application

Build web application by express
Build web application by expressBuild web application by express
Build web application by expressShawn Meng
 
Building and Scaling Node.js Applications
Building and Scaling Node.js ApplicationsBuilding and Scaling Node.js Applications
Building and Scaling Node.js ApplicationsOhad Kravchick
 
soft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.jssoft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.jssoft-shake.ch
 
Going crazy with Node.JS and CakePHP
Going crazy with Node.JS and CakePHPGoing crazy with Node.JS and CakePHP
Going crazy with Node.JS and CakePHPMariano Iglesias
 
Developing Applications with MySQL and Java for beginners
Developing Applications with MySQL and Java for beginnersDeveloping Applications with MySQL and Java for beginners
Developing Applications with MySQL and Java for beginnersSaeid Zebardast
 
Building Web Apps with Express
Building Web Apps with ExpressBuilding Web Apps with Express
Building Web Apps with ExpressAaron Stannard
 
Make BDD great again
Make BDD great againMake BDD great again
Make BDD great againYana Gusti
 
540slidesofnodejsbackendhopeitworkforu.pdf
540slidesofnodejsbackendhopeitworkforu.pdf540slidesofnodejsbackendhopeitworkforu.pdf
540slidesofnodejsbackendhopeitworkforu.pdfhamzadamani7
 
Node js introduction
Node js introductionNode js introduction
Node js introductionAlex Su
 
CouchDB on Android
CouchDB on AndroidCouchDB on Android
CouchDB on AndroidSven Haiges
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applicationsTom Croucher
 
Intro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran MizrahiIntro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran MizrahiRan Mizrahi
 
node.js practical guide to serverside javascript
node.js practical guide to serverside javascriptnode.js practical guide to serverside javascript
node.js practical guide to serverside javascriptEldar Djafarov
 
Java script at backend nodejs
Java script at backend   nodejsJava script at backend   nodejs
Java script at backend nodejsAmit Thakkar
 
Cross Domain Web
Mashups with JQuery and Google App Engine
Cross Domain Web
Mashups with JQuery and Google App EngineCross Domain Web
Mashups with JQuery and Google App Engine
Cross Domain Web
Mashups with JQuery and Google App EngineAndy McKay
 

Similar to Logging your node.js application (20)

Build web application by express
Build web application by expressBuild web application by express
Build web application by express
 
Building and Scaling Node.js Applications
Building and Scaling Node.js ApplicationsBuilding and Scaling Node.js Applications
Building and Scaling Node.js Applications
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
Socket.io
Socket.ioSocket.io
Socket.io
 
soft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.jssoft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.js
 
Going crazy with Node.JS and CakePHP
Going crazy with Node.JS and CakePHPGoing crazy with Node.JS and CakePHP
Going crazy with Node.JS and CakePHP
 
Developing Applications with MySQL and Java for beginners
Developing Applications with MySQL and Java for beginnersDeveloping Applications with MySQL and Java for beginners
Developing Applications with MySQL and Java for beginners
 
Building Web Apps with Express
Building Web Apps with ExpressBuilding Web Apps with Express
Building Web Apps with Express
 
Make BDD great again
Make BDD great againMake BDD great again
Make BDD great again
 
540slidesofnodejsbackendhopeitworkforu.pdf
540slidesofnodejsbackendhopeitworkforu.pdf540slidesofnodejsbackendhopeitworkforu.pdf
540slidesofnodejsbackendhopeitworkforu.pdf
 
Node.js - A Quick Tour
Node.js - A Quick TourNode.js - A Quick Tour
Node.js - A Quick Tour
 
Node js introduction
Node js introductionNode js introduction
Node js introduction
 
CouchDB on Android
CouchDB on AndroidCouchDB on Android
CouchDB on Android
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
 
Intro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran MizrahiIntro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran Mizrahi
 
node.js practical guide to serverside javascript
node.js practical guide to serverside javascriptnode.js practical guide to serverside javascript
node.js practical guide to serverside javascript
 
Java script at backend nodejs
Java script at backend   nodejsJava script at backend   nodejs
Java script at backend nodejs
 
NodeJS
NodeJSNodeJS
NodeJS
 
Cross Domain Web
Mashups with JQuery and Google App Engine
Cross Domain Web
Mashups with JQuery and Google App EngineCross Domain Web
Mashups with JQuery and Google App Engine
Cross Domain Web
Mashups with JQuery and Google App Engine
 
Express JS
Express JSExpress JS
Express JS
 

Recently uploaded

Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)Intelisync
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...aditisharan08
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 

Recently uploaded (20)

Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 

Logging your node.js application

  • 2. About Me • Founder, NerdDevs • Software Architect, TestReach • Node.js Trainer • Working in Software Development for 12 years • Last 6 years only working in JavaScript • Loves backbone.js http://www.nerddevs.com twitter : @sohel023010 skype : sohel023010 https://github.com/sohel-rana
  • 3. What is Logger • A device or computer program • Creates a systematic recording of events, observations, or measurements. • Application, System, OS etc • Helps to debug/trace issues
  • 4. What is Logger • Timestamp • Source • Event Type(error, info, debug etc) • Message
  • 6. Logger in node.js • node-bunyan • Morgan • Winston • Debug
  • 7. bunyan • Logs as JSON const bunyan = require('bunyan’); const log = bunyan.createLogger({name: 'myapp'}); log.info('hi’); log.warn({lang: 'fr'}, 'au revoir’); {"name":"myapp","hostname":"banana.local","pid":40161,"level":30,"msg":"hi","time":"201 3-01-04T18:46:23.851Z","v":0}
  • 8. morgan • Logs http request // create a write stream (in append mode) let accessLogStream = fs.createWriteStream(path.join(__dirname, 'access.log'), { flags: 'a’ }); // setup the logger app.use(morgan('combined', { stream: accessLogStream })); app.get('/', function (req, res) { res.send('hello, world!') })l
  • 9. Winston • Universal logger • Supports multiple transports • Supports ELK/EFK • Two way to use, own logger or default
  • 10. Winston const getLoggerInstance = (level, logType) => { return winston.createLogger({ format: winston.format.combine( winston.format.label({ label: logType }), winston.format.timestamp(), customFormat ), exitOnError: false, transports: [ new FluentTransport(`testreach.${logType}`, _.extend(logConfig, {level})), new winston.transports.DailyRotateFile({ level: level, filename: `logs/%DATE%/${logType}.log` }) ] }); }; An Example
  • 11. Winston winston.exceptions.handle( new FluentTransport('testreach.unhandledExceptions', _.extend(logConfig, {level: 'error'})), new winston.transports.DailyRotateFile({ level: 'error', filename: 'logs/%DATE%/unhandledExceptions.log' }) ); Exception Handling
  • 12. Winston exports.logRequests = function (request, response) { let userName = 'N/A'; if (request.user && request.user.username) { userName = request.user.username; } if (request.xhr && request.method.trim() !== 'GET') { if (request.body && JSON.stringify(request.body).indexOf('password') === -1) { let allTexts = ''; if (userName) { allTexts = `[ ${userName} ]- ${request.method}: ${request.url}`; } else { allTexts = `[ unknownUser ]- ${request.method}: ${request.url}`; } allTexts += `, Payload: ${JSON.stringify(request.body)}`; loggerXhr.debug(allTexts); } } }; Logger.js
  • 13. Usage in application const LoggerService = require('./services/Logger.js'); app.use(function (request, response, next) { LoggerService.logRequests(request, response); next(); }); app.js
  • 14. Fluentd • Unified logger • Act as log collector • Structures the data as JSON
  • 15. Winston and Fluentd • Use fluent-logger module • Create a transport with tag • Use that transport in Winston let fluentTransport = require('fluent- logger').support.winstonTransport(); let fluent = new fluentTransport('mytag', config); let logger = winston.createLogger({ transports: [fluent, new (winston.transports.Console)()] }); //Fleuntd config <source> @type forward port 24224 </source> <match mytag.*> @type stdout </match>
  • 16. Using EFK Key points • EFK – stands for Elasticsearch, Fluentd and Kibana • Elasticsearch stores the data in a structured way and manages the indexes for efficient searching • Kibana a tool, helps to visualize the data Steps • Create fluentd transport in winston • Forward the logs to Elasticsearch • Configure kibana to connect with Elasticsearch • Install necessary plugins
  • 18. Useful Practices • Only log error from top level • There is enough info • Name the steps properly in debug
  • 19. Useful Practices • Error log LoggerService.errorLog(error, req.user, ‘myController: User.save()’); • Debug Logger.loggerUserCall(`[Rejecting Incoming Call] ${JSON.stringify(requestData)}`); Logger.loggerNumber(`[Buy number request] ${JSON.stringify(userNumberToBeSaved)}`);