kokobob.com

Enhancing Fastify with Custom Logging and Route Configuration

Written on

Introduction to Fastify

Fastify is a lightweight framework for Node.js that facilitates the development of back-end web applications. In this article, we will explore how to effectively create back-end services using Fastify.

Custom Log Levels

One of the key features of Fastify is the ability to customize the log levels in your application. For example, you can initiate your Fastify app with logging enabled like this:

const fastify = require('fastify')({

logger: true

});

fastify.register(require('./routes/v1/users'), { prefix: '/v1' });

fastify.register(require('./routes/v2/users'), { prefix: '/v2' });

const start = async () => {

try {

await fastify.listen(3000, '0.0.0.0');

} catch (err) {

fastify.log.error(err);

process.exit(1);

}

}

start();

The above code sets the logger option to true. You can also specify different logging levels for individual routes, for instance:

const fastify = require('fastify')();

fastify.get('/', { logLevel: 'warn' }, (request, reply) => {

reply.send({ hello: 'world' });

});

const start = async () => {

try {

await fastify.listen(3000, '0.0.0.0');

} catch (err) {

fastify.log.error(err);

process.exit(1);

}

}

start();

In this scenario, the log level for the root route is set to 'warn'.

Custom Log Serializer

Fastify allows for customization of log serialization. Here’s an example of how to do it:

const fastify = require('fastify')({

logger: {

level: 'info',

serializers: {

user(req) {

return {

method: req.method,

url: req.url,

headers: req.headers,

hostname: req.hostname,

remoteAddress: req.ip,

remotePort: req.socket.remotePort

};

}

}

}

});

fastify.register(context1, {

logSerializers: {

user: value => My serializer father - ${value}

}

});

async function context1(fastify, opts) {

fastify.get('/', (req, reply) => {

req.log.info({ user: 'call father serializer', key: 'another key' });

reply.send({});

});

}

const start = async () => {

try {

await fastify.listen(3000, '0.0.0.0');

} catch (err) {

fastify.log.error(err);

process.exit(1);

}

}

start();

In this code, we configure the logger with a custom serializer that extracts specific information from the request, such as the method, URL, headers, hostname, IP address, and remote port.

Route Configuration

Fastify also allows you to pass a configuration object for each route. For example:

const fastify = require('fastify')();

function handler(req, reply) {

reply.send(reply.context.config.output);

}

fastify.get('/en', { config: { output: 'hello world!' } }, handler);

fastify.get('/fr', { config: { output: 'bonjour' } }, handler);

const start = async () => {

try {

await fastify.listen(3000, '0.0.0.0');

} catch (err) {

fastify.log.error(err);

process.exit(1);

}

}

start();

Here, an object containing the configuration property is passed as the second argument, allowing us to retrieve that value via reply.context.

Conclusion

Fastify provides a robust platform for custom logging and route configurations, enhancing the development of back-end applications. By leveraging these features, developers can create more maintainable and efficient services.

Share the page:

Twitter Facebook Reddit LinkIn

-----------------------

Recent Post:

# Five Key Principles of Digital Productivity for a Balanced Workflow

Explore five essential principles of digital productivity that promote a balanced approach to managing tasks and personal knowledge.

Enhancing Charisma: Keys to Leadership and Interview Success

Discover how to amplify your charisma for greater success in leadership and interviews, focusing on warmth and competence.

Unraveling Misconceptions: 3 Common Myths in American History

Explore three prevalent myths about American history and uncover the truths behind them.