Introduction to gelf-pro
gelf-pro
is a comprehensive Node.js library that simplifies sending logs to a Graylog server using the Graylog Extended Log Format (GELF). By using gelf-pro
, developers can easily structure their logs, enhance application monitoring, and improve system debugging processes.
Installation
Before diving into the API, it’s essential to install gelf-pro
in your project:
npm install gelf-pro
Configuration
First, configure gelf-pro
to set your Graylog server details:
const gelf = require('gelf-pro');
gelf.setConfig({
fields: { facility: 'Node.js app' },
adapterName: 'tcp',
adapterOptions: {
host: '127.0.0.1',
port: 12201
}
});
Basic Logging
Now you can log messages with different log levels:
gelf.info('This is an informational message.');
gelf.warn('This is a warning message.');
gelf.error('This is an error message.');
Custom Fields
You can add custom fields to your log messages:
gelf.info('Custom log message', { userId: 123, sessionId: 'abc123' });
Error Handling
Log structured errors for better debugging:
try {
throw new Error('Something went wrong!');
} catch (error) {
gelf.error('An error occurred', {
errorMessage: error.message,
stack: error.stack
});
}
Using in an Express Application
Integrate gelf-pro
in an Express.js application:
const express = require('express');
const gelf = require('gelf-pro');
gelf.setConfig({
fields: { facility: 'Express.js app' },
adapterOptions: {
host: '127.0.0.1',
port: 12201
}
});
const app = express();
app.use((req, res, next) => {
gelf.info('Incoming request', { method: req.method, url: req.url });
next();
});
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.post('/error', (req, res) => {
try {
throw new Error('Test error');
} catch (error) {
gelf.error('Caught error in POST /error', {
errorMessage: error.message,
stack: error.stack
});
res.status(500).send('Internal Server Error');
}
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
Conclusion
In this article, we’ve explored the capabilities of gelf-pro
in logging various types of messages and integrating with an Express.js application. Utilizing structured logs with gelf-pro
enhances monitoring and debugging, making it an excellent tool for modern application development.
Hash: ac8865644c71d1efc905b42792c2ee9c214870383c184892770ad9aaec6231e6