Skip to main content

Express Server Example

Set up beautiful, informative logging for your Express.js server.

Basic Setup

import express from 'express';
import { log, createLogger } from 'logluxe';

const app = express();
const PORT = process.env.PORT || 3000;

app.listen(PORT, () => {
log.success(`Server running on http://localhost:${PORT}`);
});
Server Output
✔ Server running on http://localhost:3000
🎮 Try Server Startup

Request Logging Middleware

Create a colorful request logger:

import express, { Request, Response, NextFunction } from 'express';
import { log } from 'logluxe';

// Request logger middleware
function requestLogger(req: Request, res: Response, next: NextFunction) {
const start = Date.now();

// Generate request ID
const requestId = Math.random().toString(36).substring(7);
req.requestId = requestId;

// Log on response finish
res.on('finish', () => {
const duration = Date.now() - start;
const status = res.statusCode;

// Color based on status code
const statusColor =
status < 300 ? 'green' :
status < 400 ? 'cyan' :
status < 500 ? 'yellow' : 'red';

// Method colors
const methodColors: Record<string, string> = {
GET: 'cyan',
POST: 'green',
PUT: 'yellow',
PATCH: 'yellow',
DELETE: 'red',
OPTIONS: 'gray'
};

const method = log.paint(req.method.padEnd(7))
.color(methodColors[req.method] || 'white')
.bold()
.toString();

const path = log.paint(req.path).white().toString();

const statusStr = log.paint(String(status))
.color(statusColor)
.bold()
.toString();

const time = log.paint(`${duration}ms`)
.color(duration > 1000 ? 'red' : duration > 500 ? 'yellow' : 'gray')
.toString();

console.log(`${method} ${path} ${statusStr} ${time}`);

// Warn on slow requests
if (duration > 1000) {
log.warn(`Slow request: ${req.method} ${req.path} took ${duration}ms`);
}
});

next();
}

app.use(requestLogger);
Request Logs
GET /api/users 200 45ms
POST /api/users 201 120ms
PUT /api/users/1 200 89ms
DELETE /api/users/99 404 12ms
GET /api/heavy-query 200 1523ms
⚠ Slow request: GET /api/heavy-query took 1523ms
🎮 Try Request Logging

Structured Server Logger

Create a production-ready logger:

import { createLogger, env } from 'logluxe';

// Create server-specific logger
const serverLog = createLogger({
prefix: 'SERVER',
timestamp: true,
level: process.env.LOG_LEVEL || (env.isProd ? 'info' : 'debug'),
format: env.isProd ? 'json' : 'pretty'
});

// Create module loggers
const dbLog = serverLog.child({ prefix: 'DB' });
const authLog = serverLog.child({ prefix: 'AUTH' });
const apiLog = serverLog.child({ prefix: 'API' });

export { serverLog, dbLog, authLog, apiLog };
Structured Logs
12:34:56 [SERVER]
Server starting...
12:34:56 [DB]
Connecting to database...
12:34:57 [DB]
Connected to PostgreSQL
12:34:57 [AUTH]
Loading auth middleware...
12:34:57 [SERVER]
Listening on port 3000

Complete Express Application

import express, { Request, Response, NextFunction } from 'express';
import { log, createLogger } from 'logluxe';

// ============ Configuration ============

const config = {
port: process.env.PORT || 3000,
env: process.env.NODE_ENV || 'development',
logLevel: process.env.LOG_LEVEL || 'debug'
};

// ============ Logger Setup ============

const serverLog = createLogger({
prefix: { text: 'SERVER', color: 'cyan', bold: true },
timestamp: true,
level: config.logLevel
});

// ============ Express App ============

const app = express();

// Body parser
app.use(express.json());

// Request logging
app.use((req: Request, res: Response, next: NextFunction) => {
const start = Date.now();
const reqId = generateId();

// Add to request
req.id = reqId;
req.startTime = start;

// Log request start
serverLog.debug(`${req.method} ${req.path} [${reqId}]`);

// Log response
res.on('finish', () => {
const duration = Date.now() - start;
logResponse(req, res, duration);
});

next();
});
Application Startup
╔═════════════════════════════════════════╗
║ 🚀 MY EXPRESS SERVER ║
║ v1.0.0 ║
╚═════════════════════════════════════════╝
┌ Startup
│ ℹ Connecting to database...
│ ⏱ Started: db-connect
│ ⏱ db-connect: 127ms
│ ✔ Database connected
│ ℹ Starting HTTP server...
│ ✔ Listening on port 3000

API Routes with Logging

// ============ Routes ============

app.get('/health', (req, res) => {
res.json({ status: 'healthy', timestamp: new Date().toISOString() });
});

app.get('/api/users', async (req, res, next) => {
try {
serverLog.perf(`fetch-users-${req.id}`);

// Simulate database call
const users = await fetchUsers();

serverLog.perfEnd(`fetch-users-${req.id}`);
res.json(users);
} catch (error) {
next(error);
}
});

app.post('/api/users', async (req, res, next) => {
try {
serverLog.info('Creating new user');
serverLog.debug('User data:', req.body);

const user = await createUser(req.body);

serverLog.success(`User created: ${user.id}`);
res.status(201).json(user);
} catch (error) {
next(error);
}
});
API Operations
→ GET /api/users [abc123]
⏱ Started: fetch-users-abc123
⏱ fetch-users-abc123: 52ms
GET /api/users 200 52ms [abc123]
→ POST /api/users [def456]
ℹ Creating new user
● User data: {"name":"John","email":"john@example.com"}
✔ User created: usr_789xyz
POST /api/users 201 89ms [def456]
🎮 Try API Logging

Error Handling

// 404 handler
app.use((req, res) => {
serverLog.warn(`Not found: ${req.method} ${req.path}`);
res.status(404).json({ error: 'Not found' });
});

// Error handler
app.use((err: Error, req: Request, res: Response, next: NextFunction) => {
serverLog.group(`Error [${req.id}]`);
serverLog.error(err.message);
serverLog.debug('Request:', {
method: req.method,
path: req.path,
body: req.body,
query: req.query
});
serverLog.dev(err.stack);
serverLog.end();

res.status(500).json({
error: config.env === 'production'
? 'Internal server error'
: err.message
});
});
Error Handling
⚠ Not found: GET /api/unknown
GET /api/unknown 404 5ms [xyz789]
┌ Error [abc456]
│ ✖ Database connection timeout
│ Request: {"method":"GET","path":"/api/users","query":{}}
│ at Database.query (db.ts:45:11)
│ at UserService.findAll (users.ts:23:5)
GET /api/users 500 3052ms [abc456]

Database Logging

import { createLogger } from 'logluxe';

const dbLog = createLogger({
prefix: { text: 'DB', color: 'magenta', bold: true },
timestamp: true
});

class Database {
async query(sql: string, params?: unknown[]) {
const queryId = Math.random().toString(36).substring(7);

dbLog.perf(`query-${queryId}`);
dbLog.debug(`SQL: ${sql.slice(0, 100)}...`);

try {
const result = await this.execute(sql, params);
const duration = dbLog.perfEnd(`query-${queryId}`);

// Log slow queries
if (duration > 100) {
dbLog.warn(`Slow query (${duration}ms): ${sql.slice(0, 50)}...`);
}

return result;
} catch (error) {
dbLog.perfEnd(`query-${queryId}`);
dbLog.error(`Query failed: ${error.message}`);
dbLog.debug('SQL:', sql);
dbLog.debug('Params:', params);
throw error;
}
}
}
Database Logs
12:35:10 [DB]
⏱ Started: query-xyz789
● SQL: SELECT * FROM users WHERE status = $1 ORDER BY created_at DESC...
⏱ query-xyz789: 45ms
12:35:11 [DB]
⏱ Started: query-abc123
● SQL: SELECT * FROM orders JOIN users ON orders.user_id = users.id...
⏱ query-abc123: 187ms
⚠ Slow query (187ms): SELECT * FROM orders JOIN users ON...
🎮 Try Database Logging

Authentication Logging

const authLog = createLogger({
prefix: { text: 'AUTH', color: 'yellow', bold: true },
timestamp: true
});

function loginHandler(req: Request, res: Response) {
const { email, password } = req.body;

authLog.info(`Login attempt: ${email}`);

try {
const user = authenticate(email, password);
const token = generateToken(user);

authLog.success(`Login successful: ${email}`);
res.json({ token });
} catch (error) {
authLog.warn(`Login failed: ${email} - ${error.message}`);
res.status(401).json({ error: 'Invalid credentials' });
}
}
Auth Logs
12:36:00 [AUTH]
Login attempt: john@example.com
12:36:00 [AUTH]
Login successful: john@example.com
12:36:15 [AUTH]
Login attempt: hacker@evil.com
12:36:15 [AUTH]
Login failed: hacker@evil.com - Invalid password
12:36:30 [AUTH]
No token: GET /api/protected

Graceful Shutdown

import { log } from 'logluxe';

let server: Server;

function setupGracefulShutdown() {
const signals = ['SIGTERM', 'SIGINT'];

signals.forEach(signal => {
process.on(signal, async () => {
console.log('');
log.warn(`Received ${signal}, shutting down gracefully...`);

log.group('Shutdown');

// Close server
log.info('Closing HTTP server...');
await new Promise(resolve => server.close(resolve));
log.success('HTTP server closed');

// Close database
log.info('Closing database connections...');
await db.close();
log.success('Database closed');

log.end();

log.success('Graceful shutdown complete');
process.exit(0);
});
});
}
Graceful Shutdown
⚠ Received SIGTERM, shutting down gracefully...
┌ Shutdown
│ ℹ Closing HTTP server...
│ ✔ HTTP server closed
│ ℹ Closing database connections...
│ ✔ Database closed
✔ Graceful shutdown complete
🎮 Try Shutdown Logging

Production JSON Logging

For production, switch to JSON format:

import { createLogger, env } from 'logluxe';

const log = createLogger({
format: env.isProd ? 'json' : 'pretty',
timestamp: true,
context: {
service: 'my-api',
version: process.env.npm_package_version,
environment: process.env.NODE_ENV
}
});

// In production, logs will be JSON:
// {"level":"info","message":"Server started","service":"my-api","version":"1.0.0","timestamp":"..."}
Production JSON Logs
{"level":"info","message":"Server starting...","service":"my-api","version":"1.0.0","environment":"production","timestamp":"2024-01-15T12:00:00.000Z"}
{"level":"info","message":"Database connected","service":"my-api","version":"1.0.0","environment":"production","timestamp":"2024-01-15T12:00:01.234Z"}
{"level":"info","message":"Listening on port 3000","service":"my-api","version":"1.0.0","environment":"production","timestamp":"2024-01-15T12:00:01.567Z"}

Next: React & Next.js Example