Introduction to gelf-pro for Enhanced Logging in Node.js
Logging is an essential part of any application, especially for those running in production environments. The gelf-pro library is a powerful tool that simplifies logging in Node.js applications, allowing you to send logs to a Graylog server easily. In this guide, we cover various APIs provided by gelf-pro, complete with code snippets and an example application.
Getting Started with gelf-pro
const gelf = require('gelf-pro');
gelf.setConfig({
fields: {facility: "my-awesome-app"}, // Optional
filter: [], // Optional
transform: [], // Optional
broadcast: [], // Optional
levels: {
verbose: 7,
debug: 6,
info: 5,
warn: 4,
error: 3,
critical: 2,
alert: 1,
emergency: 0
},
adapterName: 'tcp', // Currently supported: udp, tcp or aws (default: udp)
adapterOptions: {
protocol: 'tcp', // Optional; Available for UDP
host: '127.0.0.1', // Optional
port: 12201 // Optional
}
});
Basic Logging with gelf-pro
gelf.info("This is an info message");
gelf.warn("This is a warning message");
gelf.error("This is an error message");
Using Custom Fields
gelf.setConfig({
fields: {facility: "my-awesome-app", customField: "customValue"}
});
gelf.info("Message with custom fields");
Advanced Logging: Filters and Transforms
const myFilter = (message) => message.short_message !== "ignore me";
const myTransform = (message) => {
if (message.short_message === "transform me") {
message.full_message = "This message was transformed!";
}
return message;
};
gelf.setConfig({
filter: [myFilter],
transform: [myTransform]
});
gelf.info("transform me");
gelf.info("ignore me");
Example Application: Logging HTTP Requests
Below is an example of an Express application that logs incoming HTTP requests using gelf-pro.
const express = require('express');
const gelf = require('gelf-pro');
gelf.setConfig({
fields: {facility: "my-awesome-app"},
adapterName: 'tcp',
adapterOptions: {host: '127.0.0.1', port: 12201}
});
const app = express();
app.use((req, res, next) => {
gelf.info(`Incoming request: ${req.method} ${req.url}`);
next();
});
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
In this application, every incoming HTTP request is logged as an info message to the Graylog server, making it easier to monitor and debug your application.
With these powerful features, gelf-pro can greatly enhance the logging capabilities of your Node.js applications, providing better insights and easier debugging.
Hash: ac8865644c71d1efc905b42792c2ee9c214870383c184892770ad9aaec6231e6