0
0
Expressframework~5 mins

Structured logging with JSON in Express

Choose your learning style9 modes available
Introduction

Structured logging with JSON helps you keep logs neat and easy to read by machines and people. It makes finding problems faster and sharing logs simpler.

When you want to track user actions in a web app clearly.
When you need to send logs to a monitoring system that reads JSON.
When debugging issues and you want detailed, organized log info.
When multiple developers or teams need to understand logs easily.
When logs must be searchable and filterable by keys like user ID or error type.
Syntax
Express
console.log(JSON.stringify({ key1: 'value1', key2: 'value2' }))

Use JSON.stringify() to convert an object into a JSON string for logging.

Include keys that describe the event, like level, message, and timestamp.

Examples
Logs a simple info message about the server starting.
Express
console.log(JSON.stringify({ level: 'info', message: 'Server started' }))
Logs an error with a code to help identify the problem.
Express
console.log(JSON.stringify({ level: 'error', message: 'Failed to connect', errorCode: 500 }))
Logs a debug message with user ID and timestamp for tracking.
Express
console.log(JSON.stringify({ level: 'debug', message: 'User login', userId: 123, time: new Date().toISOString() }))
Sample Program

This Express app logs every incoming request as a JSON string with details like method, URL, and time. It also logs when the server starts.

Express
const express = require('express');
const app = express();

app.use((req, res, next) => {
  const logEntry = {
    level: 'info',
    message: 'Request received',
    method: req.method,
    url: req.url,
    timestamp: new Date().toISOString()
  };
  console.log(JSON.stringify(logEntry));
  next();
});

app.get('/', (req, res) => {
  res.send('Hello World!');
});

app.listen(3000, () => {
  console.log(JSON.stringify({ level: 'info', message: 'Server listening on port 3000', timestamp: new Date().toISOString() }));
});
OutputSuccess
Important Notes

Make sure to include timestamps to know when events happen.

Use consistent keys in your JSON logs for easier searching and filtering.

Consider using logging libraries like winston or pino for more features.

Summary

Structured logging uses JSON to keep logs clear and organized.

It helps machines and people understand logs quickly.

Include useful info like level, message, and timestamp in every log.