To use hapi-pino, register it as a plugin in your Hapi server configuration. Once registered, you can access the logger in three ways:
- Via
request.logger: The fastest way to log within a request handler. - Via
server.logger: A decorated API on the server instance for general logging. - Via Hapi's standard logging: Using
request.log() or server.log(), which hapi-pino will intercept and process into JSON.
You can also pass Pino-specific options (like redact) during registration.
'use strict'
const Hapi = require('@hapi/hapi')
async function start () {
// Create a server with a host and port
const server = Hapi.server({
host: 'localhost',
port: 3000,
debug: false, // disable Hapi debug console logging
})
// Add the route
server.route({
method: 'GET',
path: '/',
handler: async function (request, h) {
// request.log is HAPI standard way of logging
request.log(['a', 'b'], 'Request into hello world')
// you can also use a pino instance, which will be faster
request.logger.info('In handler %s', request.path)
return 'hello world'
}
})
await server.register({
plugin: require('hapi-pino'),
options: {
// Redact Authorization headers, see https://getpino.io/#/docs/redaction
redact: ['req.headers.authorization']
}
})
// also as a decorated API
server.logger.info('another way for accessing it')
// and through Hapi standard logging system
server.log(['subsystem'], 'third way for accessing it')
await server.start()
return server
}
start().catch((err) => {
console.log(err)
process.exit(1)
})