Last active
January 9, 2020 03:00
-
-
Save rudyhuynh/7e5dd6ca2fde1a3ff7d7ae89c0a3819f to your computer and use it in GitHub Desktop.
A logger that is similar to console.log but log to file, for NodeJS
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
/** | |
* Usage: | |
* const {logger} = require('./log-to-file') | |
* logger.log('something') | |
*/ | |
const path = require('path'); | |
const fs = require('fs'); | |
const FILE_PATH = path.resolve(__dirname, 'default.log'); | |
const stream = fs.createWriteStream(FILE_PATH, { flags: 'a', encoding: 'utf8' }); | |
function log(level, ...content) { | |
console[level](...content); | |
const timestamp = new Date().toISOString(); | |
const message = content | |
.map(contentItem => { | |
if (contentItem instanceof Error) { | |
return `${contentItem.message}\n${contentItem.stack}\n`; | |
} else if (typeof contentItem === 'string') { | |
return contentItem; | |
} else { | |
try { | |
return JSON.stringify(contentItem, null, 2); | |
} catch (e) { | |
return contentItem; | |
} | |
} | |
}) | |
.join(' '); | |
stream.write(`${timestamp} [${level}]: ${message}\n`); | |
} | |
module.exports = { | |
logger: { | |
log: log.bind(null, 'log'), | |
info: log.bind(null, 'info'), | |
warn: log.bind(null, 'warn'), | |
debug: log.bind(null, 'debug'), | |
error: log.bind(null, 'error'), | |
}, | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment