Last active
May 14, 2020 03:44
-
-
Save AhmedElMetwally/1110642f5a93ca2ef00ffe0220fbe865 to your computer and use it in GitHub Desktop.
Simple Node.js Logger With Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* eslint-disable no-console */ | |
const _errorFormat = (error) => { | |
return { | |
name: error.name, | |
message: error.message, | |
stack: error.stack.split('\n').map((ele) => ele.trim()), | |
}; | |
}; | |
const _prepareMetaData = (metaData) => { | |
for (const i in metaData) { | |
if (metaData[i] instanceof Error) { | |
metaData[i] = _errorFormat(metaData[i]); | |
} | |
} | |
return metaData; | |
}; | |
const _write = (opts) => { | |
const { logFunc, tag, level, message, metaData } = opts; | |
const date = new Date(); | |
if (process.env.NODE_ENV !== 'test') { | |
logFunc( | |
JSON.stringify({ | |
tag: `${tag} <${level}>`, | |
level, | |
message, | |
formattedDate: date.toISOString(), | |
env: process.env.NODE_ENV, | |
processId: process.pid, | |
clusterType: process.env.CLUSTER_TYPE, | |
timestamp: date.getTime(), | |
metaData: _prepareMetaData(metaData), | |
}), | |
); | |
logFunc(' '); | |
} | |
}; | |
const logger = (tag) => { | |
return { | |
log: (message, metaData = {}) => { | |
_write({ | |
logFunc: console.log, | |
level: 'log', | |
tag, | |
message, | |
metaData, | |
}); | |
}, | |
error: (message, metaData = {}) => { | |
_write({ | |
logFunc: console.error, | |
level: 'error', | |
tag, | |
message, | |
metaData, | |
}); | |
}, | |
}; | |
}; | |
module.exports = logger; | |
/* | |
// server.js | |
const express = require('express'); | |
const logger = require('./src/utils/logger.util.js')('server'); | |
const app = express(); | |
server.use((req, res, next) => { | |
logger.log('request', { | |
body: req.body, | |
query: req.query, | |
params: req.params, | |
token: req.headers.authorization || null, | |
path: req.path, | |
}); | |
next(); | |
}); | |
app.listen(process.env.PORT, () => { | |
logger.log(`Example app listening at http://localhost:${process.env.PORT}`); | |
}); | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment