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]