Skip to content

Instantly share code, notes, and snippets.

@pirate
Created March 12, 2021 01:40
Show Gist options
  • Save pirate/b190ece7fd3715653147400025d22620 to your computer and use it in GitHub Desktop.
Save pirate/b190ece7fd3715653147400025d22620 to your computer and use it in GitHub Desktop.
Show filename:lineno for every log message in node. Log the time, origin ip, method, and url for every express.js request.
// patch console.log to show filename and line number for every logged message
//
// ./src/index.js:68:9 √ Connected to Sentry
// ./src/index.js:72:9 √ Connected to Stripe
// ./src/index.js:82:9 √ Connected to Backblaze
// ./src/index.js:99:9 √ Connected to FireBase
// ./src/routes/paypal.js:68:17 Error: Request failed with status code 401
// at createError (./node_modules/axios/lib/core/createError.js:16:15)
// at settle (./node_modules/axios/lib/core/settle.js:17:12)
// at IncomingMessage.handleStreamEnd (./node_modules/axios/lib/adapters/http.js:236:11)
// ...
const original_log = console.log
console.log = function() {
const e = new Error()
const filepath_regex = /(\/.*):(\d+):(\d+)/
try {
const matches = filepath_regex.exec(e.stack.split("\n")[3]);
const filename = matches[1].replace(__dirname, '.')
const path = `${filename}:${matches[2]}:${matches[3]}`
original_log.apply(console, [path, ...arguments])
// console.trace()
} catch (e) {
original_log.apply(console, [path, '\n', e.stack])
}
};
// log every every request to console
//
// [2020-02-02 23:59] 127.127.127.127> GET /some/path/on/server
// [2020-02-04 00:01] 127.123.12.11> GET /some/other/path/on/server?with=params
// ...
const app = express()
...
app.use(function(req, res, next) {
const { method, url } = req
if (method !== 'OPTIONS') {
const ip = req.headers['cf-connecting-ip'] || req.headers['x-forwarded-for'] || req.connection.remoteAddress
const ts = new Date().toISOString().replace(/T/, ' ').replace(/\..+/, '')
log.apply(console, [`[${ts}]`, leftJustify(ip.slice(0, 20) + ">", 22), method, url])
}
next()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment