DEV Community

Venki
Venki

Posted on

How to set up Errsole Node.js Logger across all environments

What is Errsole?

Errsole is an open-source logging library for Node.js applications. What sets Errsole apart is its built-in log viewer, which allows you to view, filter, and search your application logs. If you are scrolling through raw log files or SSHing into servers to access your logs, Errsole is a must-include library in your codebase.

How to set up Errsole across all environments

In this setup, logs in the development environment are stored locally in an SQLite file. In the production environment, logs are stored in a centralized MongoDB database.

1. Install Errsole and the required storage modules

Run the following commands to install Errsole and its storage adapters:

npm install errsole errsole-sqlite errsole-mongodb
Enter fullscreen mode Exit fullscreen mode

2. Create the logger file

Create a file named logger.js to handle Errsole’s initialization for all environments.

const errsole = require('errsole');
const ErrsoleMongoDB = require('errsole-mongodb');
const ErrsoleSQLite = require('errsole-sqlite');
const os = require('os');
const path = require('path');

if (process.env.NODE_ENV === 'production') {
  // Production Environment: Centralized logging with MongoDB
  errsole.initialize({
    storage: new ErrsoleMongoDB('<Connection URL>', '<Collection Name>', { collectionPrefix: '<App Name>' }),
    appName: '<App Name>',
    environmentName: process.env.NODE_ENV,
  });
} else {
  // Development/Other Environments: Local logging with SQLite
  const logsFile = path.join(os.tmpdir(), '<App Name>.log.sqlite');
  errsole.initialize({
    storage: new ErrsoleSQLite(logsFile),
    appName: '<App Name>',
    environmentName: process.env.NODE_ENV,
  });
}

module.exports = errsole;
Enter fullscreen mode Exit fullscreen mode

3. Use Errsole in your application

Include the logger in your application to start capturing logs.

const express = require('express');
const logger = require('./logger'); // Import Errsole logger

const app = express();

// Middleware to access Errsole log viewer
app.use('/errsole', logger.expressProxyMiddleware());

app.get('/', (req, res) => {
  logger.info('Home route accessed'); // Log an info message
  res.send('Hello, World!');
});

const port = 3000;
app.listen(port, () => {
  logger.info(`Server running on port ${port}`);
});
Enter fullscreen mode Exit fullscreen mode

4. Access the Log Viewer

With the above configuration, you can access the Errsole Web Dashboard by visiting:

http://localhost:3000/errsole
Enter fullscreen mode Exit fullscreen mode

Errsole with Other Storages

This guide uses MongoDB for centralized logging in production. However, Errsole supports other databases like MySQL and PostgreSQL. For detailed instructions, refer to the following documentation:

Top comments (0)