Discover the Power of gelf-pro for Efficient Logging in Node.js

Introduction to gelf-pro: Efficient Logging in Node.js

gelf-pro is a powerful logging library that allows developers to send logs to a Graylog server using the GELF (Graylog Extended Log Format). This API provides an efficient way to handle logging within your Node.js applications, making it easier to monitor, debug, and maintain your code. In this article, we will explore various APIs offered by gelf-pro and provide code snippets to demonstrate their usage.

Installation


npm install gelf-pro

Basic Configuration

Here is how you can set up gelf-pro with basic configurations:


const gelfPro = require('gelf-pro');

gelfPro.setConfig({
  fields: { facility: "myApp" },
  adapterName: 'udp',
  adapterOptions: {
    host: '127.0.0.1',
    port: 12201
  }
});

Logging Messages

You can log messages with different levels of severity:


gelfPro.info('This is an info message');
gelfPro.warn('This is a warning');
gelfPro.error('This is an error message');
gelfPro.debug('Debugging details');

Adding Custom Fields

It’s possible to add custom fields to your log messages:


gelfPro.setConfig({
  fields: { 
    facility: "myApp",
    environment: "production"
  },
  adapterName: 'udp',
  adapterOptions: { host: '127.0.0.1', port: 12201 }
});

gelfPro.info('Message with custom fields');

Sending Logs Over TCP

You can also use TCP instead of UDP:


gelfPro.setConfig({
  adapterName: 'tcp',
  adapterOptions: { host: '127.0.0.1', port: 12201 }
});

gelfPro.info('Log message over TCP');

Sending Logs Over HTTP

For an HTTP transport, set the adapter to HTTP:


gelfPro.setConfig({
  adapterName: 'http',
  adapterOptions: { host: '127.0.0.1', port: 12201 }
});

gelfPro.info('Log message over HTTP');

Full Application Example

Here’s a sample Node.js application using gelf-pro for logging:


const express = require('express');
const gelfPro = require('gelf-pro');

gelfPro.setConfig({
  fields: { facility: "myApp", environment: "production" },
  adapterName: 'udp',
  adapterOptions: { host: '127.0.0.1', port: 12201 }
});

const app = express();

app.get('/', (req, res) => {
  gelfPro.info('Homepage accessed');
  res.send('Hello World!');
});

app.get('/error', (req, res) => {
  try {
    throw new Error('Sample error');
  } catch (error) {
    gelfPro.error('Error occurred', { error: error.message });
    res.status(500).send('Something went wrong');
  }
});

app.listen(3000, () => {
  console.log('Server is running on port 3000');
  gelfPro.info('Server started on port 3000');
});

By leveraging gelf-pro, you can efficiently handle logging within your Node.js applications, making it easier to track and debug issues in your production environment.

Hash: ac8865644c71d1efc905b42792c2ee9c214870383c184892770ad9aaec6231e6

Leave a Reply

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