Graylog: Sending Node.js logs to Graylog with the graylog2 package (recommended)

This documentation is part of the Using with Node.js guide. You can view the complete guide here: How to send logs from Node.js to Graylog.

👋 Welcome to the Stackhero documentation!

Stackhero offers a ready-to-use Graylog cloud solution that provides a host of benefits, including:

  • Unlimited and dedicated SMTP email server included.
  • Effortless updates with just a click.
  • Customizable domain name secured with HTTPS (for example, https://logs.your-company.com).
  • Optimal performance and robust security powered by a private and dedicated VM.

Save time and simplify your life: it only takes 5 minutes to try Stackhero's Graylog cloud hosting solution!

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.

To get started, install the package by running the following command:

npm install graylog2

Here’s 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 check out this GitHub repository.

warning Don’t forget to configure your Graylog input (see details below).