Skip to content

Commit

Permalink
Add Fastify sample
Browse files Browse the repository at this point in the history
  • Loading branch information
puzpuzpuz committed Jul 2, 2019
1 parent 4280ca8 commit 6592b5a
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 1 deletion.
2 changes: 1 addition & 1 deletion README.md
Expand Up @@ -201,7 +201,7 @@ const logger = createLogger({
})
```

Complete samples for Express and Koa are available in `/samples/` directory.
Complete samples for Express, Fastify and Koa are available in `/samples/` directory.

## Middleware configuration

Expand Down
53 changes: 53 additions & 0 deletions samples/fastify.winston.js
@@ -0,0 +1,53 @@
'use strict'

const rTracer = require('../index')

// 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) => {
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 Fastify app

const Fastify = require('fastify')
const app = new Fastify()

app.use(rTracer.fastifyMiddleware())

app.get('/', async (request, reply) => {
logger.info('Starting request handling')
const result = await fakeDbAccess()
reply.send(result)
})

async function fakeDbAccess () {
return new Promise((resolve) => {
setTimeout(() => {
logger.info('Logs from fakeDbAccess')
resolve({ message: 'Hello from cls-rtracer Fastify example' })
}, 0)
})
}

app.listen(3000, (err) => {
if (err) {
logger.err('The app could not start')
}
logger.info('The app is listening on 3000')
})

0 comments on commit 6592b5a

Please sign in to comment.