Fastify
ByteHide Logger integrates with Fastify applications through plugins and request/response hooks for comprehensive logging.
Installation
npm install @bytehide/logger fastify
Basic Setup
const fastify = require('fastify')({ logger: false });
const { Log } = require('@bytehide/logger');
// Configure logger
Log.configure({
projectToken: process.env.BYTEHIDE_PROJECT_TOKEN,
logLevel: 'info'
});
// Start server
const start = async () => {
try {
await fastify.listen({ port: 3000 });
Log.info('Fastify server started', {
context: { port: 3000 }
});
} catch (error) {
Log.error('Failed to start server', {}, error);
process.exit(1);
}
};
start();
Logger Plugin
// plugins/logger.js
const { Log } = require('@bytehide/logger');
async function loggerPlugin(fastify, options) {
Log.configure({
projectToken: options.projectToken,
logLevel: options.logLevel || 'info'
});
// Add logger to fastify instance
fastify.decorate('log', Log);
Log.info('ByteHide logger plugin registered');
}
module.exports = loggerPlugin;
Register Plugin
const fastify = require('fastify')();
// Register logger plugin
fastify.register(require('./plugins/logger'), {
projectToken: process.env.BYTEHIDE_PROJECT_TOKEN,
logLevel: 'info'
});
Request Logging Hooks
// Log all requests
fastify.addHook('onRequest', async (request, reply) => {
fastify.log.info('Request received', {
context: {
method: request.method,
url: request.url,
userAgent: request.headers['user-agent'],
ip: request.ip
}
});
});
// Log responses
fastify.addHook('onSend', async (request, reply, payload) => {
fastify.log.info('Response sent', {
context: {
method: request.method,
url: request.url,
statusCode: reply.statusCode
}
});
});
Route Handlers
// GET route with logging
fastify.get('/api/users', async (request, reply) => {
fastify.log.info('Fetching users');
try {
const users = await getUsersFromDatabase();
fastify.log.info('Users fetched successfully', {
context: { count: users.length }
});
return users;
} catch (error) {
fastify.log.error('Failed to fetch users', {
context: { endpoint: '/api/users' }
}, error);
reply.status(500).send({ error: 'Internal server error' });
}
});
// POST route with logging
fastify.post('/api/users', async (request, reply) => {
fastify.log.info('Creating user', {
context: { email: request.body.email }
});
try {
const user = await createUser(request.body);
fastify.log.info('User created successfully', {
context: { userId: user.id }
});
return user;
} catch (error) {
fastify.log.error('Failed to create user', {
context: { email: request.body.email }
}, error);
reply.status(400).send({ error: 'Failed to create user' });
}
});
Error Handling
// Global error handler
fastify.setErrorHandler((error, request, reply) => {
fastify.log.error('Unhandled error', {
context: {
method: request.method,
url: request.url,
statusCode: reply.statusCode
}
}, error);
reply.status(500).send({ error: 'Internal server error' });
});
User Identification
// Authentication hook
fastify.addHook('preHandler', async (request, reply) => {
if (request.user) {
fastify.log.identify(request.user.id, request.user.email);
}
});
Best Practices
Fastify Best Practices
- Use plugins for logger configuration and registration
- Implement request/response hooks for automatic logging
- Log both successful operations and errors
- Use global error handlers for unhandled exceptions