Skip to content

Instantly share code, notes, and snippets.

@richardartoul
Created December 4, 2018 23:38
Show Gist options
  • Save richardartoul/663be279c35e160d510091a2b06d4173 to your computer and use it in GitHub Desktop.
Save richardartoul/663be279c35e160d510091a2b06d4173 to your computer and use it in GitHub Desktop.
NodeJS Observability demo
const prometheus = require('prom-client');
const winston = require('winston');
const express = require('express');
const app = express();
const port = 3000;
const logTransports = {
console: new winston.transports.Console({ level: 'info' }),
// Could also configure logging to a file at a different level here.
};
const logger = winston.createLogger({
format: winston.format.combine(
winston.format.timestamp(),
winston.format.prettyPrint()
),
transports: [logTransports.console]
});
(function simulateUnicorn() {
const salesCounter = new prometheus.Counter({
name: 'vc_dollars_burned',
help: 'spend money to earn money'
});
const salesTimer = new prometheus.Summary({
name: 'time_between_sales',
help: 'ring the bell'
});
const lossPerWidget = 3; // "growth hacking"
const timeBetweenSalesMillis = 400;
var measureSaleTime = salesTimer.startTimer()
setInterval(() => {
logger.debug("simulation tick!");
measureSaleTime();
salesCounter.inc(lossPerWidget);
}, timeBetweenSalesMillis);
})()
const landingPageHits = new prometheus.Counter({
name: 'landing_page_hits',
help: 'number of user who hit the landing page'
});
app.get('/', (req, res) => {
landingPageHits.inc(1);
res.send("Hello world!");
});
// Register an endpoint that satisfies the Prometheus scrape interface.
app.get('/metrics', (req, res) => {
res.set('Content-Type', prometheus.register.contentType)
res.end(prometheus.register.metrics())
});
// Register two endpoints that allow us to swap the log level back and forth
// between debug and info. Note: Don't ever do stateful actions like this
// in the context of a GET request, I'm just being lazy.
//
// Trivia: Why is this a bad idea?
app.get('/logs/debug', (req, res) => {
logTransports.console.level = 'debug';
res.send("log level set to: debug");
});
app.get('/logs/info', (req, res) => {
logTransports.console.level = 'info';
res.send("log level set to: info");
});
console.log("look at this ugly unstructured log :( \n\n");
app.listen(port, () => logger.info(`Listening on port: ${port}!`));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment