Skip to content

Instantly share code, notes, and snippets.

@rajeshkumaravel
Forked from puzpuzpuz/cls-tracer-test-app.js
Created September 14, 2020 09:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rajeshkumaravel/7e034a29fa2a0cdc5c2aedd54c2196b7 to your computer and use it in GitHub Desktop.
Save rajeshkumaravel/7e034a29fa2a0cdc5c2aedd54c2196b7 to your computer and use it in GitHub Desktop.
'use strict'
const rTracer = require('cls-rtracer')
// first - configure winston logger
const { createLogger, format, transports } = require('winston')
const { combine, timestamp, printf } = format
// a custom format that outputs request id
const rTracerFormat = printf((info) => {
// HINT: change to the following to disable request ids/CLS usage
const rid = false
// const rid = rTracer.id()
return rid
? `${info.timestamp} [request-id:${rid}]: ${info.message}`
: `${info.timestamp}: ${info.message}`
})
const logger = createLogger({
format: combine(
timestamp(),
rTracerFormat
),
transports: [new transports.Console()]
})
// next - configure and start Express app
const express = require('express')
const app = express()
// HINT: comment the following line to disable request ids/CLS usage
// app.use(rTracer.expressMiddleware())
app.get('/', function (req, res) {
logger.info('Starting request handling')
fakeDbAccess()
.then((result) => res.json(result))
})
async function fakeDbAccess () {
return new Promise((resolve) => {
setTimeout(() => {
logger.info('Logs from fakeDbAccess')
resolve({ message: 'Hello from express-rtracer example' })
}, 0)
})
}
app.listen(3000, (err) => {
if (err) {
logger.err('The app could not start')
}
logger.info('The app is listening on 3000')
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment