Enhance Your Logging Capabilities with gelf-pro – The Ultimate Guide for Developers

Introduction to gelf-pro

gelf-pro is a popular Node.js library for sending log messages to a GELF (Graylog Extended Log Format) compatible server. It provides a flexible and easy-to-use API for developers to handle various logging levels and customize log messages. In this guide, we will introduce you to gelf-pro and explain its numerous APIs with code snippets. Additionally, we will provide a sample application using gelf-pro APIs.

Getting Started

First, you need to install gelf-pro via npm:

npm install gelf-pro --save

Basic Configuration

Here’s how to configure gelf-pro to send log messages to your Graylog server:

 const gelf = require('gelf-pro');
gelf.setConfig({
    fields: { facility: "my-app" }, // default fields for all messages
    adapterName: 'udp', // adapter name: udp (default), tcp, http
    adapterOptions: { // adapter options
        host: '127.0.0.1', // Graylog server IP address
        port: 12201 // Graylog server port
    }
}); 

Logging Messages

gelf-pro allows you to log messages with various severity levels. Here are some examples:

 // Log a debug message gelf.debug('This is a debug message');
// Log an informational message gelf.info('This is an informational message');
// Log a warning message gelf.warn('This is a warning message');
// Log an error message gelf.error('This is an error message');
// Log a critical message gelf.critical('This is a critical message'); 

Additional Fields

You can add additional fields to your log messages:

 gelf.info('User created', { userId: 123, username: 'johndoe' }); 

Sample Application

Let’s see gelf-pro in action with a sample application:

 const express = require('express'); const gelf = require('gelf-pro');
gelf.setConfig({
    fields: { facility: "my-app" },
    adapterName: 'udp',
    adapterOptions: {
        host: '127.0.0.1',
        port: 12201
    }
});
const app = express();
app.use((req, res, next) => {
    gelf.info('HTTP request received', { method: req.method, url: req.url });
    next();
});
app.get('/', (req, res) => {
    gelf.debug('Handling root route');
    res.send('Hello, World!');
});
app.get('/error', (req, res) => {
    gelf.error('Something went wrong');
    res.status(500).send('Internal Server Error');
});
app.listen(3000, () => {
    gelf.info('Server is running on port 3000');
}); 

Conclusion

gelf-pro is a powerful and flexible logging library for Node.js applications, making it easy to send structured log messages to a Graylog server. With its simple configuration and extensive API, gelf-pro can help you improve your application’s logging capabilities significantly.

Hash: ac8865644c71d1efc905b42792c2ee9c214870383c184892770ad9aaec6231e6

Leave a Reply

Your email address will not be published. Required fields are marked *