How to use LogDNA as a middleware logger in your NodeJS express app

Demiban Díaz Torres
Nov 3 · 2 min read

LogDNA is an enterprise-grade log management provider that offers a user-friendly UI and a simple pricing format. They provide multiple logging libraries that support multiple languages (e.g Nodejs, Python, Ruby, etc.) and integrations with 3rd party loggers like Winston, Bunyan, and Cloudwatch. In this case, I’m going to show you how to integrate express-winston with logdna-winston library to use it as a middleware logger with a Nodejs express application. Here is how you can implement it!

Let’s start by installing the dependencies:

npm install —-save winston logdna-winston express-winston

Create a file logger.js under a folder called middleware with the following code:

"use strict";
const os = require("os");
const winston = require("winston");
const LogdnaWinston = require("logdna-winston");
const expressWinston = require("express-winston");
const options = {
console: {
level: "debug",
handleExceptions: true,
format: winston.format.prettyPrint({ colorize: true })
},
logdna: {
key: {LOGDNA_INGESTION_KEY},
hostname: os.hostname(),
ip: os.networkInterfaces().lo0[0].address,
mac: os.networkInterfaces().lo0[0].mac,
app: "MyRestAPI",
handleExceptions: true
}
};
const logger = expressWinston.logger({
transports: [
new winston.transports.Console(options.console),
new LogdnaWinston(options.logdna)
],
exitOnError: false
});
module.exports = logger;

With this configuration, we created two transports: one for logging to the console and one for logging to your LogDNA account. If needed, a file logger transport can be enabled by adding the following construct:

new winston.transports.File(fileOptions)

Finally, let’s use the logger in the server.js file:

‘use strict’;
const express = require("express");
// rest of your imports ...
const logger = require(‘./middleware/logger’);
const app = express();
app.use(logger);
// Routes setup ...app.listen(8080, () => console.log("App listening on port 8080!"));

That’s all you need to implement for using logdna-winston as a middleware logger in an express application. I hope you enjoy using LogDNA!

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade