0
0
Expressframework~5 mins

Log levels and when to use them in Express

Choose your learning style9 modes available
Introduction

Log levels help organize messages by importance. They make it easier to find problems and understand what your app is doing.

When you want to record normal app actions like user visits or data saved.
When you need to warn about something unusual but not breaking the app.
When an error happens that stops part of your app from working.
When debugging to see detailed info about how your app runs.
When tracking security or critical failures that need immediate attention.
Syntax
Express
logger.info('User logged in')
logger.warn('Disk space low')
logger.error('Database connection failed')
logger.debug('User data: %o', userData)

Replace level with the actual log level like info, warn, error, or debug.

Use placeholders like %o to insert objects or variables in logs.

Examples
Use info for general messages about app status.
Express
console.info('Server started on port 3000')
Use warn to alert about potential issues.
Express
console.warn('Memory usage is high')
Use error when something goes wrong.
Express
console.error('Failed to load user profile')
Use debug for detailed info useful during development.
Express
console.debug('Request headers: %o', req.headers)
Sample Program

This Express app uses different log levels to show how to log info, warnings, and errors. The morgan middleware logs HTTP requests automatically.

Express
import express from 'express';
import morgan from 'morgan';

const app = express();

// Use morgan middleware for logging HTTP requests
app.use(morgan('combined'));

app.get('/', (req, res) => {
  console.info('Info: Home page accessed');
  res.send('Hello, world!');
});

app.get('/warn', (req, res) => {
  console.warn('Warning: /warn route was called');
  res.send('This is a warning example');
});

app.get('/error', (req, res) => {
  console.error('Error: Something went wrong on /error');
  res.status(500).send('Error occurred');
});

app.listen(3000, () => {
  console.info('Server running on http://localhost:3000');
});
OutputSuccess
Important Notes

Use info for normal operations to keep track of app flow.

Use warn to highlight things that might cause problems later.

Use error to log serious issues that need fixing.

Use debug only during development to avoid cluttering logs in production.

Summary

Log levels help you organize messages by importance.

Use info, warn, error, and debug for different situations.

Good logging makes it easier to find and fix problems in your app.