Graylog: Using with Node.js

How to send logs from Node.js to Graylog

👋 Welcome to Stackhero documentation

Stackhero offers a fully managed Graylog cloud solution designed for speed and simplicity. You can:

  • Rely on an unlimited, dedicated SMTP email server included with your service.
  • Apply updates effortlessly with a single click, with no manual intervention required.
  • Use a custom domain name secured by HTTPS (for example, https://logs.your-company.com), providing your team with secure, direct access.
  • Benefit from strong performance and security on a private, dedicated infrastructure, with no shared resources or noisy neighbours.

Focus on your data, not your tools: you can get started with Stackhero's Graylog cloud hosting solution in just a few minutes.

Sending logs from Node.js to Graylog is very straightforward. In this example, you will see how to use the graylog2 package to make this process smooth and efficient.

To begin, install the package by running the following command:

npm install graylog2

Here is how you can use it to log messages:

const graylog2 = require('graylog2');
const crypto = require('crypto');

const logger = new graylog2.graylog({
  servers: [{ host: '<XXXXXX>.stackhero-network.com', port: 12201 }] // Be sure to replace "host" with your Graylog domain
});

// Send a simple message to Graylog
logger.log('Simple message example');

// Attach data to a message
logger.log(
  'Password recovery email', // Message
  // A JSON object with additional details
  {
    subject: 'Password recovery',
    language: 'en_US',
    domain: 'gmail.com'
  }
);

// Advanced example
const ip = '1.2.3.4';
const ipHash = crypto.createHash('md5').update(ip).digest('hex');

const userId = '1234';
const userIdHash = crypto.createHash('md5').update(userId).digest('hex');

logger.log(
  'API request', // Message
  // A JSON object with more details
  {
    route: '/v1/messages/1234/',
    method: 'POST',

    responseTime: 12, // ms
    responseCode: 200,

    ipHash,
    userIdHash
  }
);

// Log uncaught exceptions in Node.js
process.on(
  'uncaughtException',
  err => {
    logger.log(
      err,
      { type: 'uncaughtException' }
    );
  }
);

For more examples, you can refer to this GitHub repository.

warning Do not forget to configure your Graylog input (see details below).

warning It is preferable to use the graylog2 package unless Winston is already part of your project. In that case, you can replace it with winston-gelf.

To install the Winston GELF package, run:

npm install winston-gelf

If Winston is not already included in your project, add it with:

npm install winston

Here is a basic configuration:

const winston = require('winston');
const winstonGelf = require('winston-gelf');
const process = require('process');

const logger = winston.createLogger({
  transports: [
    new winston.transports.Console(),
    new winstonGelf({
      // See all gelfPro options here: https://www.npmjs.com/package/gelf-pro
      gelfPro: {
        fields: {
          env: process.env.NODE_ENV || 'development'
        },
        adapterName: 'udp',
        adapterOptions: {
          host: '<XXXXXX>.stackhero-network.com', // Replace with your Graylog domain
          port: 12201,
        }
      }
    })
  ]
});

// Example of an informational log
logger.info('This is a log information');

// Example of an error log
try {
  throw Error('This is an example error');
}
catch(error) {
  logger.warn({ message: 'Error triggered', error });
}

Do not forget to configure your Graylog input (see details below).

On the Graylog interface, go to System/Inputs, create a new input of type "GELF UDP," and click on "Launch new input." In the window that appears, tick "Global," add a title, and confirm without changing any other settings.

That's all there is to it! Your Graylog is now ready to receive logs from your Node.js application.

To enhance security, consider filtering the IP addresses allowed to send data to port 12201. To do this, go to the Stackhero dashboard, select your Graylog service, and configure the "Firewall" to allow only your IP addresses.