From 737620e2ca7920621275c4cf980e115297d7b2c4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ond=C5=99ej=20Syn=C3=A1=C4=8Dek?= Date: Sat, 12 Dec 2020 13:19:34 +0100 Subject: [PATCH] feature: add endpoint for logging instrumentation --- functions/logger.js | 4 ++-- lib/app/index.js | 2 ++ lib/routes/index.js | 2 ++ lib/routes/track.js | 24 ++++++++++++++++++++++++ lib/static/app/logger.js | 17 +++++++++++++++++ 5 files changed, 47 insertions(+), 2 deletions(-) create mode 100644 lib/routes/track.js diff --git a/functions/logger.js b/functions/logger.js index db59880..b3b189e 100644 --- a/functions/logger.js +++ b/functions/logger.js @@ -8,9 +8,9 @@ class FirebaseTransport extends Transport { this._db = options.db } - log(info, callback) { + async log(info, callback) { try { - this._db.ref(`log-${new Date().getTime()}`).set(info) + await this._db.ref(`log-${new Date().getTime()}`).set(info) callback(null, info) this.emit('logged', info) } catch (err) { diff --git a/lib/app/index.js b/lib/app/index.js index 4430848..a6413a1 100644 --- a/lib/app/index.js +++ b/lib/app/index.js @@ -10,6 +10,7 @@ const { notFound, download, downloadHTML, + track, } = require('../routes') const { @@ -92,6 +93,7 @@ const configureApplication = ({ app.post('/download/html', downloadHTML(appLogger || null)) app.post('/download', download(appLogger || null)) + app.post('/track', track(appLogger || null)) app.use(genericErrorHandler) diff --git a/lib/routes/index.js b/lib/routes/index.js index 30f31ac..3f9b9dd 100644 --- a/lib/routes/index.js +++ b/lib/routes/index.js @@ -1,9 +1,11 @@ const { error, notFound } = require('./error') const { download, downloadHTML } = require('./download') +const { track } = require('./track') module.exports = { error, notFound, download, downloadHTML, + track, } diff --git a/lib/routes/track.js b/lib/routes/track.js new file mode 100644 index 0000000..0399e2a --- /dev/null +++ b/lib/routes/track.js @@ -0,0 +1,24 @@ +const track = (logger) => async (req, res) => { + try { + if (!logger) { + return res.status(501) + } + + const { message, service, level, env } = req.body + + await logger.log({ + message, + level, + service, + env: process.env.NODE_APP || env || 'N/A', + }) + + res.status(200).send({ status: 'ok' }) + } catch (err) { + next(err) + } +} + +module.exports = { + track, +} diff --git a/lib/static/app/logger.js b/lib/static/app/logger.js index 95b8775..4ba5ad5 100644 --- a/lib/static/app/logger.js +++ b/lib/static/app/logger.js @@ -6,6 +6,23 @@ class Logger { 'color: grey', 'color: black' ) + + this._log({ message, level, service }) + } + + _log({ message, level, service }) { + return new Promise((resolve, reject) => { + fetch('/track', { + method: 'POST', + headers: { + 'Accept': 'text/html, application/json', + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ message, level, service, env: 'browser' }) + }) + .then(resolve) + .catch(reject) + }) } }