Uncategorized

How to set up Errsole Node.js Logger 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
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;
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}`);
});
4. Access the Log Viewer

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

http://localhost:3000/errsole

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:

Building Errsole. Worked in startups. Built products from scratch. Passionate about coding and innovation.

Write A Comment