express-easy-logger 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,180 @@
1
- # Temporary Holding Version
1
+ # express-easy-logger 🚀
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ > A beginner-friendly, zero-dependency HTTP request logger for Express with beautiful console colors, automatic file logging, sensitive data masking, and a built-in real-time web dashboard.
4
+
5
+ ---
6
+
7
+ ## 🌟 Why express-easy-logger?
8
+
9
+ - **One-line setup:** Just `app.use(logger())` and you are ready.
10
+ - **Color-coded statuses:** Instantly spot errors in the terminal (2xx Green, 3xx Cyan, 4xx Yellow, 5xx Red).
11
+ - **Automatic file saving:** Saves clean, uncolored logs to disk without crashing your app.
12
+ - **Built-in Web Dashboard:** View the last 100 requests in a clean HTML table that auto-refreshes every 5 seconds.
13
+ - **Safe by default:** Automatically hides sensitive fields like `password`, `token`, and `authorization` if body logging is enabled.
14
+ - **Zero heavy dependencies:** Built using pure Node.js standard modules (`fs`, `path`).
15
+
16
+ ---
17
+
18
+ ## 📦 Installation
19
+
20
+ ```bash
21
+ npm install express-easy-logger
22
+ ```
23
+
24
+ *(Express 4.x or 5.x is required as a peer dependency)*
25
+
26
+ ---
27
+
28
+ ## ⚡ 1-Line Quick Start
29
+
30
+ ```javascript
31
+ const express = require('express');
32
+ const logger = require('express-easy-logger');
33
+
34
+ const app = express();
35
+
36
+ // 1. Add the logger middleware (that's it!)
37
+ app.use(logger());
38
+
39
+ app.get('/', (req, res) => {
40
+ res.send('Hello World!');
41
+ });
42
+
43
+ app.listen(3000, () => {
44
+ console.log('Server is running on http://localhost:3000');
45
+ });
46
+ ```
47
+
48
+ ### Terminal Output Preview:
49
+ ```text
50
+ [2026-11-22 10:30:15] GET /users 200 12ms
51
+ [2026-11-22 10:30:18] GET /redirect 302 2ms
52
+ [2026-11-22 10:30:20] GET /missing 404 1ms
53
+ [2026-11-22 10:30:25] GET /crash 500 15ms
54
+ ```
55
+
56
+ ---
57
+
58
+ ## ⚙️ Options Reference
59
+
60
+ You can pass an optional options object to `logger(options)`:
61
+
62
+ ```javascript
63
+ app.use(
64
+ logger({
65
+ colors: true,
66
+ file: './logs/app.log',
67
+ format: 'simple',
68
+ skip: ['/favicon.ico'],
69
+ showBody: false,
70
+ })
71
+ );
72
+ ```
73
+
74
+ | Option | Type | Default | Description |
75
+ | :--- | :--- | :--- | :--- |
76
+ | `colors` | `boolean` | `true` | Enables color-coded status codes in terminal output. |
77
+ | `file` | `string` or `null` | `null` | Path to log file. If set, logs are appended to this file. Folders are created automatically. |
78
+ | `format` | `'simple'` \| `'json'` | `'simple'` | Log format. `'simple'` writes plain text lines; `'json'` writes structured JSON. |
79
+ | `skip` | `Array<string\|RegExp>` | `[]` | List of URL paths or regex patterns to ignore (e.g. `['/favicon.ico', '/health']`). |
80
+ | `showBody` | `boolean` | `false` | When `true`, logs the incoming `req.body` with sensitive fields masked. |
81
+
82
+ ---
83
+
84
+ ## 🛡️ Sensitive Data Protection
85
+
86
+ When `showBody: true` is enabled, `express-easy-logger` automatically scans the request body and replaces sensitive values with `***`:
87
+
88
+ - `password`
89
+ - `token`
90
+ - `authorization`
91
+
92
+ ```javascript
93
+ // Example request body:
94
+ // { "username": "alice", "password": "supersecret123", "token": "jwt-token-here" }
95
+
96
+ // Logged output:
97
+ // [2026-11-22 10:30:15] POST /login 200 5ms - Body: {"username":"alice","password":"***","token":"***"}
98
+ ```
99
+
100
+ ---
101
+
102
+ ## 📊 Built-in Web Log Viewer
103
+
104
+ Want a graphical dashboard to view your application logs in real time? `express-easy-logger` includes an interactive HTML viewer out of the box!
105
+
106
+ ```javascript
107
+ const express = require('express');
108
+ const logger = require('express-easy-logger');
109
+
110
+ const app = express();
111
+
112
+ // Log to file
113
+ app.use(logger({ file: './logs/app.log' }));
114
+
115
+ // Mount the live log viewer at /logs
116
+ app.use('/logs', logger.viewer({ file: './logs/app.log' }));
117
+
118
+ app.listen(3000);
119
+ ```
120
+
121
+ ### Dashboard Features:
122
+ 1. **Live Table:** Shows the last 100 requests (Timestamp, Method, URL, Status, Response Time).
123
+ 2. **Auto-Refresh:** Updates every 5 seconds with a visual countdown and Pause/Resume controls.
124
+ 3. **Instant Filter:** Live search by Method (`GET`, `POST`, etc.), Status (`200`, `404`, `500`), or URL.
125
+ 4. **Zero Configuration:** Self-contained HTML and CSS, no external CDNs or databases needed.
126
+
127
+ ---
128
+
129
+ ## 💻 Full Example App
130
+
131
+ Check out the [`example/server.js`](file:///Users/adityayadav/npm_package%20/example/server.js) file included in this repository:
132
+
133
+ ```javascript
134
+ const express = require('express');
135
+ const logger = require('express-easy-logger');
136
+
137
+ const app = express();
138
+
139
+ app.use(express.json());
140
+
141
+ // Logger configuration
142
+ app.use(
143
+ logger({
144
+ colors: true,
145
+ file: './logs/app.log',
146
+ showBody: true,
147
+ skip: ['/favicon.ico'],
148
+ })
149
+ );
150
+
151
+ // Built-in dashboard
152
+ app.use('/logs', logger.viewer({ file: './logs/app.log' }));
153
+
154
+ // Routes
155
+ app.get('/', (req, res) => res.send('Welcome! Visit /logs to see the viewer.'));
156
+ app.get('/users', (req, res) => res.json([{ id: 1, name: 'Student' }]));
157
+ app.get('/error', (req, res) => res.status(500).send('Error'));
158
+ app.post('/login', (req, res) => res.json({ status: 'ok' }));
159
+
160
+ app.listen(3000, () => {
161
+ console.log('App running on http://localhost:3000');
162
+ console.log('Viewer running on http://localhost:3000/logs');
163
+ });
164
+ ```
165
+
166
+ ---
167
+
168
+ ## 🧪 Testing
169
+
170
+ We use Node's built-in native test runner (`node --test`). No external test packages required!
171
+
172
+ ```bash
173
+ npm test
174
+ ```
175
+
176
+ ---
177
+
178
+ ## 📄 License
179
+
180
+ MIT ©
package/index.js ADDED
@@ -0,0 +1,20 @@
1
+ /**
2
+ * express-easy-logger
3
+ * An easy-to-use, beginner-friendly request logger for Express applications.
4
+ *
5
+ * Usage:
6
+ * const express = require('express');
7
+ * const logger = require('express-easy-logger');
8
+ *
9
+ * const app = express();
10
+ * app.use(logger());
11
+ * app.use('/logs', logger.viewer({ file: './logs/app.log' }));
12
+ */
13
+
14
+ const createLogger = require('./src/logger');
15
+ const createViewer = require('./src/viewer');
16
+
17
+ // Attach the viewer function directly to the main logger function
18
+ createLogger.viewer = createViewer;
19
+
20
+ module.exports = createLogger;
package/package.json CHANGED
@@ -1,6 +1,31 @@
1
1
  {
2
2
  "name": "express-easy-logger",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "description": "A beginner-friendly Express request logger with colors, file saving, and a built-in web viewer.",
5
+ "main": "index.js",
6
+ "files": [
7
+ "index.js",
8
+ "src/"
9
+ ],
10
+ "scripts": {
11
+ "test": "node --test test/**/*.test.js",
12
+ "example": "node example/server.js"
13
+ },
14
+ "keywords": [
15
+ "express",
16
+ "logger",
17
+ "middleware",
18
+ "http-logger",
19
+ "easy",
20
+ "beginner-friendly",
21
+ "log-viewer"
22
+ ],
23
+ "author": "",
24
+ "license": "MIT",
25
+ "peerDependencies": {
26
+ "express": ">=4.0.0"
27
+ },
28
+ "devDependencies": {
29
+ "express": "^4.21.2"
30
+ }
31
+ }
@@ -0,0 +1,129 @@
1
+ /**
2
+ * src/fileWriter.js
3
+ * Safely writes logs to files and reads recent entries for the viewer.
4
+ */
5
+
6
+ const fs = require('fs');
7
+ const path = require('path');
8
+
9
+ /**
10
+ * Appends a log line to the specified file.
11
+ * Automatically creates any missing parent folders.
12
+ * Uses try/catch to ensure logging errors never crash the user's application.
13
+ *
14
+ * @param {string} filePath - Path to the log file (e.g. './logs/app.log')
15
+ * @param {string} logLine - Plain text log entry to append
16
+ */
17
+ function writeLog(filePath, logLine) {
18
+ if (!filePath || typeof filePath !== 'string') return;
19
+
20
+ try {
21
+ const resolvedPath = path.resolve(filePath);
22
+ const directory = path.dirname(resolvedPath);
23
+
24
+ // Create the directory recursively if it doesn't exist
25
+ if (!fs.existsSync(directory)) {
26
+ fs.mkdirSync(directory, { recursive: true });
27
+ }
28
+
29
+ // Append log line with a newline character
30
+ fs.appendFileSync(resolvedPath, logLine + '\n', 'utf8');
31
+ } catch (error) {
32
+ // Fail silently so the main Express application is never disrupted
33
+ }
34
+ }
35
+
36
+ /**
37
+ * Parses a single raw log string into structured components.
38
+ * Supports both standard simple format and JSON format.
39
+ *
40
+ * @param {string} line - A single line from the log file
41
+ * @returns {object} Parsed log entry
42
+ */
43
+ function parseLogLine(line) {
44
+ const trimmed = line.trim();
45
+ if (!trimmed) return null;
46
+
47
+ // Attempt to parse as JSON first
48
+ if (trimmed.startsWith('{') && trimmed.endsWith('}')) {
49
+ try {
50
+ const obj = JSON.parse(trimmed);
51
+ return {
52
+ timestamp: obj.timestamp || '-',
53
+ method: obj.method || 'GET',
54
+ url: obj.url || '/',
55
+ status: obj.status ? Number(obj.status) : 200,
56
+ duration: obj.duration || '-',
57
+ body: obj.body ? JSON.stringify(obj.body) : '',
58
+ raw: trimmed,
59
+ };
60
+ } catch (_) {
61
+ // Fall through to simple text parser
62
+ }
63
+ }
64
+
65
+ // Parse simple format: [2026-11-22 10:30:15] GET /users 200 12ms - Body: {...}
66
+ const simpleRegex = /^\[([^\]]+)\]\s+([A-Z]+)\s+([^\s]+)\s+(\d{3})\s+([^\s]+)(?:\s+-\s+Body:\s+(.*))?$/;
67
+ const match = trimmed.match(simpleRegex);
68
+
69
+ if (match) {
70
+ return {
71
+ timestamp: match[1],
72
+ method: match[2],
73
+ url: match[3],
74
+ status: Number(match[4]),
75
+ duration: match[5],
76
+ body: match[6] || '',
77
+ raw: trimmed,
78
+ };
79
+ }
80
+
81
+ // Fallback for unstructured log entries
82
+ return {
83
+ timestamp: '-',
84
+ method: 'LOG',
85
+ url: trimmed,
86
+ status: 200,
87
+ duration: '-',
88
+ body: '',
89
+ raw: trimmed,
90
+ };
91
+ }
92
+
93
+ /**
94
+ * Reads the last N logs from a file.
95
+ * Returns an empty array if the file doesn't exist yet.
96
+ *
97
+ * @param {string} filePath - Path to log file
98
+ * @param {number} [maxCount=100] - Maximum number of lines to return
99
+ * @returns {Array<object>} Array of parsed log objects (most recent first)
100
+ */
101
+ function readLastLogs(filePath, maxCount = 100) {
102
+ if (!filePath || typeof filePath !== 'string') return [];
103
+
104
+ try {
105
+ const resolvedPath = path.resolve(filePath);
106
+ if (!fs.existsSync(resolvedPath)) {
107
+ return [];
108
+ }
109
+
110
+ const content = fs.readFileSync(resolvedPath, 'utf8');
111
+ const lines = content.split('\n').filter((l) => l.trim().length > 0);
112
+
113
+ // Get the last `maxCount` lines and reverse them so the newest logs appear first
114
+ const recentLines = lines.slice(-maxCount).reverse();
115
+
116
+ return recentLines
117
+ .map((line) => parseLogLine(line))
118
+ .filter(Boolean);
119
+ } catch (error) {
120
+ // Return empty list if reading fails
121
+ return [];
122
+ }
123
+ }
124
+
125
+ module.exports = {
126
+ writeLog,
127
+ parseLogLine,
128
+ readLastLogs,
129
+ };
@@ -0,0 +1,151 @@
1
+ /**
2
+ * src/formatter.js
3
+ * Formats log messages, handles ANSI colors, and sanitizes sensitive data.
4
+ */
5
+
6
+ // ANSI color escape codes (standard terminal colors)
7
+ const COLORS = {
8
+ reset: '\x1b[0m',
9
+ green: '\x1b[32m', // 2xx Success
10
+ cyan: '\x1b[36m', // 3xx Redirection
11
+ yellow: '\x1b[33m', // 4xx Client Error
12
+ red: '\x1b[31m', // 5xx Server Error
13
+ dim: '\x1b[90m', // Dim / Gray
14
+ bold: '\x1b[1m',
15
+ };
16
+
17
+ // Sensitive field names to automatically mask
18
+ const SENSITIVE_KEYS = new Set(['password', 'token', 'authorization']);
19
+
20
+ /**
21
+ * Returns the current timestamp in 'YYYY-MM-DD HH:mm:ss' format.
22
+ * @param {Date} [date] - Optional Date object
23
+ * @returns {string} Formatted timestamp
24
+ */
25
+ function getTimestamp(date = new Date()) {
26
+ const pad = (num) => String(num).padStart(2, '0');
27
+ const year = date.getFullYear();
28
+ const month = pad(date.getMonth() + 1);
29
+ const day = pad(date.getDate());
30
+ const hours = pad(date.getHours());
31
+ const minutes = pad(date.getMinutes());
32
+ const seconds = pad(date.getSeconds());
33
+ return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
34
+ }
35
+
36
+ /**
37
+ * Returns the ANSI color code matching the HTTP status code.
38
+ * 2xx = Green, 3xx = Cyan, 4xx = Yellow, 5xx = Red
39
+ * @param {number} status - HTTP status code
40
+ * @returns {string} ANSI color code
41
+ */
42
+ function getStatusColor(status) {
43
+ if (status >= 200 && status < 300) return COLORS.green;
44
+ if (status >= 300 && status < 400) return COLORS.cyan;
45
+ if (status >= 400 && status < 500) return COLORS.yellow;
46
+ if (status >= 500) return COLORS.red;
47
+ return COLORS.reset;
48
+ }
49
+
50
+ /**
51
+ * Recursively masks sensitive fields (password, token, authorization) in request body.
52
+ * @param {any} data - Request body
53
+ * @returns {any} Cleaned data with sensitive keys replaced by '***'
54
+ */
55
+ function sanitizeBody(data) {
56
+ if (!data || typeof data !== 'object') {
57
+ return data;
58
+ }
59
+
60
+ // Handle arrays
61
+ if (Array.isArray(data)) {
62
+ return data.map((item) => sanitizeBody(item));
63
+ }
64
+
65
+ // Handle objects
66
+ const sanitized = {};
67
+ for (const [key, value] of Object.entries(data)) {
68
+ if (SENSITIVE_KEYS.has(key.toLowerCase())) {
69
+ sanitized[key] = '***';
70
+ } else if (typeof value === 'object' && value !== null) {
71
+ sanitized[key] = sanitizeBody(value);
72
+ } else {
73
+ sanitized[key] = value;
74
+ }
75
+ }
76
+ return sanitized;
77
+ }
78
+
79
+ /**
80
+ * Formats request details into console and file strings.
81
+ * @param {object} info - Request info: { timestamp, method, url, status, duration, body }
82
+ * @param {object} options - User options: { colors, format, showBody }
83
+ * @returns {{ consoleOutput: string, fileOutput: string }}
84
+ */
85
+ function formatLog(info, options = {}) {
86
+ const {
87
+ timestamp = getTimestamp(),
88
+ method = 'GET',
89
+ url = '/',
90
+ status = 200,
91
+ duration = 0,
92
+ body = null,
93
+ } = info;
94
+
95
+ const {
96
+ colors = true,
97
+ format = 'simple',
98
+ showBody = false,
99
+ } = options;
100
+
101
+ // JSON format
102
+ if (format === 'json') {
103
+ const logObject = {
104
+ timestamp,
105
+ method,
106
+ url,
107
+ status,
108
+ duration: `${duration}ms`,
109
+ };
110
+
111
+ if (showBody && body && Object.keys(body).length > 0) {
112
+ logObject.body = sanitizeBody(body);
113
+ }
114
+
115
+ const jsonString = JSON.stringify(logObject);
116
+ return {
117
+ consoleOutput: jsonString,
118
+ fileOutput: jsonString,
119
+ };
120
+ }
121
+
122
+ // Simple format: [YYYY-MM-DD HH:mm:ss] METHOD URL STATUS DURATIONms
123
+ let bodyPart = '';
124
+ if (showBody && body && Object.keys(body).length > 0) {
125
+ const cleanBody = sanitizeBody(body);
126
+ bodyPart = ` - Body: ${JSON.stringify(cleanBody)}`;
127
+ }
128
+
129
+ // Plain text (used for log files so no ugly ANSI characters are written)
130
+ const plainText = `[${timestamp}] ${method} ${url} ${status} ${duration}ms${bodyPart}`;
131
+
132
+ // Colored text for terminal console output
133
+ let consoleOutput = plainText;
134
+ if (colors) {
135
+ const statusColor = getStatusColor(status);
136
+ consoleOutput = `[${timestamp}] ${method} ${url} ${statusColor}${status}${COLORS.reset} ${duration}ms${bodyPart}`;
137
+ }
138
+
139
+ return {
140
+ consoleOutput,
141
+ fileOutput: plainText,
142
+ };
143
+ }
144
+
145
+ module.exports = {
146
+ COLORS,
147
+ getTimestamp,
148
+ getStatusColor,
149
+ sanitizeBody,
150
+ formatLog,
151
+ };
package/src/logger.js ADDED
@@ -0,0 +1,87 @@
1
+ /**
2
+ * src/logger.js
3
+ * Express middleware that logs every incoming HTTP request.
4
+ */
5
+
6
+ const { getTimestamp, formatLog } = require('./formatter');
7
+ const { writeLog } = require('./fileWriter');
8
+
9
+ /**
10
+ * Creates the express-easy-logger middleware.
11
+ *
12
+ * @param {object} [options]
13
+ * @param {boolean} [options.colors=true] - Enable colored terminal output
14
+ * @param {string|null} [options.file=null] - File path to save logs (e.g. './logs/app.log')
15
+ * @param {'simple'|'json'} [options.format='simple'] - Output format
16
+ * @param {Array<string|RegExp>} [options.skip=[]] - Routes or patterns to ignore (e.g. ['/favicon.ico'])
17
+ * @param {boolean} [options.showBody=false] - Log request body (sensitive keys automatically masked)
18
+ * @returns {Function} Express middleware (req, res, next)
19
+ */
20
+ function createLogger(options = {}) {
21
+ // Merge user options with sensible defaults
22
+ const config = {
23
+ colors: options.colors !== undefined ? Boolean(options.colors) : true,
24
+ file: typeof options.file === 'string' ? options.file : null,
25
+ format: options.format === 'json' ? 'json' : 'simple',
26
+ skip: Array.isArray(options.skip) ? options.skip : [],
27
+ showBody: Boolean(options.showBody),
28
+ };
29
+
30
+ return function easyLoggerMiddleware(req, res, next) {
31
+ try {
32
+ const requestUrl = req.originalUrl || req.url || '/';
33
+
34
+ // Check if this request URL should be skipped
35
+ const shouldSkip = config.skip.some((pattern) => {
36
+ if (typeof pattern === 'string') {
37
+ return requestUrl === pattern || req.path === pattern;
38
+ }
39
+ if (pattern instanceof RegExp) {
40
+ return pattern.test(requestUrl);
41
+ }
42
+ return false;
43
+ });
44
+
45
+ if (shouldSkip) {
46
+ return next();
47
+ }
48
+
49
+ // Record request start timestamp for response time calculation
50
+ const startTime = Date.now();
51
+
52
+ // Listen for when the response finishes sending to client
53
+ res.on('finish', () => {
54
+ try {
55
+ const duration = Math.max(0, Date.now() - startTime);
56
+
57
+ const logData = {
58
+ timestamp: getTimestamp(),
59
+ method: req.method || 'GET',
60
+ url: requestUrl,
61
+ status: res.statusCode || 200,
62
+ duration,
63
+ body: config.showBody ? req.body : null,
64
+ };
65
+
66
+ const formatted = formatLog(logData, config);
67
+
68
+ // 1. Output to console
69
+ console.log(formatted.consoleOutput);
70
+
71
+ // 2. Append to log file if a file path is configured
72
+ if (config.file) {
73
+ writeLog(config.file, formatted.fileOutput);
74
+ }
75
+ } catch (innerError) {
76
+ // Never crash the application if logging encounters an issue
77
+ }
78
+ });
79
+ } catch (outerError) {
80
+ // Never crash the application if middleware setup fails
81
+ }
82
+
83
+ next();
84
+ };
85
+ }
86
+
87
+ module.exports = createLogger;
package/src/viewer.js ADDED
@@ -0,0 +1,518 @@
1
+ /**
2
+ * src/viewer.js
3
+ * Built-in log viewer dashboard serving a clean HTML + CSS table.
4
+ */
5
+
6
+ const { readLastLogs } = require('./fileWriter');
7
+
8
+ /**
9
+ * Escapes HTML special characters to prevent any XSS issues.
10
+ * @param {string} str - Raw string
11
+ * @returns {string} Escaped string
12
+ */
13
+ function escapeHtml(str) {
14
+ if (typeof str !== 'string') return String(str || '');
15
+ return str
16
+ .replace(/&/g, '&amp;')
17
+ .replace(/</g, '&lt;')
18
+ .replace(/>/g, '&gt;')
19
+ .replace(/"/g, '&quot;')
20
+ .replace(/'/g, '&#39;');
21
+ }
22
+
23
+ /**
24
+ * Generates the CSS badge class for HTTP status codes.
25
+ * @param {number} status - HTTP status code
26
+ * @returns {string} CSS class name
27
+ */
28
+ function getStatusClass(status) {
29
+ if (status >= 200 && status < 300) return 'status-2xx';
30
+ if (status >= 300 && status < 400) return 'status-3xx';
31
+ if (status >= 400 && status < 500) return 'status-4xx';
32
+ if (status >= 500) return 'status-5xx';
33
+ return 'status-other';
34
+ }
35
+
36
+ /**
37
+ * Generates the full HTML markup for the log viewer dashboard.
38
+ * @param {Array<object>} logs - Array of parsed log objects
39
+ * @param {string} dataUrl - URL endpoint to fetch JSON logs
40
+ * @returns {string} HTML page string
41
+ */
42
+ function renderHtml(logs, dataUrl) {
43
+ const rowsHtml = logs.length === 0
44
+ ? `<tr class="empty-row"><td colspan="6">No logs recorded yet. Make some requests to your app and they will show up here!</td></tr>`
45
+ : logs.map((log, index) => {
46
+ const statusClass = getStatusClass(log.status);
47
+ const methodClass = `method-${(log.method || 'GET').toLowerCase()}`;
48
+ const bodyHtml = log.body ? `<span class="log-body" title="${escapeHtml(log.body)}">${escapeHtml(log.body)}</span>` : '<span class="text-muted">-</span>';
49
+
50
+ return `
51
+ <tr data-method="${escapeHtml(log.method)}" data-status="${escapeHtml(String(log.status))}" data-url="${escapeHtml(log.url)}">
52
+ <td class="text-muted">#${logs.length - index}</td>
53
+ <td class="font-mono">${escapeHtml(log.timestamp)}</td>
54
+ <td><span class="badge ${methodClass}">${escapeHtml(log.method)}</span></td>
55
+ <td class="font-mono text-url">${escapeHtml(log.url)}</td>
56
+ <td><span class="badge ${statusClass}">${escapeHtml(String(log.status))}</span></td>
57
+ <td class="font-mono text-duration">${escapeHtml(log.duration)}</td>
58
+ <td>${bodyHtml}</td>
59
+ </tr>
60
+ `;
61
+ }).join('\n');
62
+
63
+ return `<!DOCTYPE html>
64
+ <html lang="en">
65
+ <head>
66
+ <meta charset="UTF-8">
67
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
68
+ <title>Express Easy Logger - Viewer</title>
69
+ <style>
70
+ :root {
71
+ --bg: #0f172a;
72
+ --card-bg: #1e293b;
73
+ --border: #334155;
74
+ --text: #f8fafc;
75
+ --text-muted: #94a3b8;
76
+ --primary: #38bdf8;
77
+ --green-bg: #064e3b;
78
+ --green-text: #34d399;
79
+ --cyan-bg: #164e63;
80
+ --cyan-text: #22d3ee;
81
+ --yellow-bg: #78350f;
82
+ --yellow-text: #fbbf24;
83
+ --red-bg: #7f1d1d;
84
+ --red-text: #f87171;
85
+ }
86
+
87
+ * { box-sizing: border-box; margin: 0; padding: 0; }
88
+ body {
89
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", sans-serif;
90
+ background-color: var(--bg);
91
+ color: var(--text);
92
+ padding: 24px;
93
+ line-height: 1.5;
94
+ }
95
+
96
+ .container {
97
+ max-width: 1200px;
98
+ margin: 0 auto;
99
+ }
100
+
101
+ header {
102
+ display: flex;
103
+ flex-wrap: wrap;
104
+ justify-content: space-between;
105
+ align-items: center;
106
+ gap: 16px;
107
+ margin-bottom: 24px;
108
+ padding-bottom: 16px;
109
+ border-bottom: 1px solid var(--border);
110
+ }
111
+
112
+ .title-group h1 {
113
+ font-size: 22px;
114
+ font-weight: 700;
115
+ color: #ffffff;
116
+ display: flex;
117
+ align-items: center;
118
+ gap: 10px;
119
+ }
120
+
121
+ .title-group h1 span.pill {
122
+ font-size: 12px;
123
+ background: #0284c7;
124
+ color: white;
125
+ padding: 2px 8px;
126
+ border-radius: 9999px;
127
+ font-weight: 500;
128
+ }
129
+
130
+ .title-group p {
131
+ font-size: 13px;
132
+ color: var(--text-muted);
133
+ margin-top: 4px;
134
+ }
135
+
136
+ .controls-panel {
137
+ display: flex;
138
+ flex-wrap: wrap;
139
+ gap: 12px;
140
+ align-items: center;
141
+ background: var(--card-bg);
142
+ padding: 14px 18px;
143
+ border-radius: 8px;
144
+ border: 1px solid var(--border);
145
+ margin-bottom: 20px;
146
+ }
147
+
148
+ .search-input {
149
+ flex: 1;
150
+ min-width: 220px;
151
+ background: #0f172a;
152
+ border: 1px solid var(--border);
153
+ color: #fff;
154
+ padding: 8px 12px;
155
+ border-radius: 6px;
156
+ font-size: 14px;
157
+ }
158
+ .search-input:focus {
159
+ outline: none;
160
+ border-color: var(--primary);
161
+ }
162
+
163
+ select {
164
+ background: #0f172a;
165
+ border: 1px solid var(--border);
166
+ color: #fff;
167
+ padding: 8px 12px;
168
+ border-radius: 6px;
169
+ font-size: 13px;
170
+ cursor: pointer;
171
+ }
172
+
173
+ .btn {
174
+ background: #2563eb;
175
+ color: #fff;
176
+ border: none;
177
+ padding: 8px 14px;
178
+ border-radius: 6px;
179
+ font-size: 13px;
180
+ font-weight: 500;
181
+ cursor: pointer;
182
+ display: inline-flex;
183
+ align-items: center;
184
+ gap: 6px;
185
+ transition: background 0.2s;
186
+ }
187
+ .btn:hover { background: #1d4ed8; }
188
+
189
+ .btn-secondary {
190
+ background: #334155;
191
+ }
192
+ .btn-secondary:hover { background: #475569; }
193
+
194
+ .refresh-status {
195
+ font-size: 12px;
196
+ color: var(--text-muted);
197
+ margin-left: auto;
198
+ }
199
+
200
+ .table-card {
201
+ background: var(--card-bg);
202
+ border-radius: 8px;
203
+ border: 1px solid var(--border);
204
+ overflow-x: auto;
205
+ box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.2);
206
+ }
207
+
208
+ table {
209
+ width: 100%;
210
+ border-collapse: collapse;
211
+ text-align: left;
212
+ font-size: 13px;
213
+ }
214
+
215
+ th {
216
+ background: #1e293b;
217
+ padding: 12px 16px;
218
+ font-weight: 600;
219
+ color: var(--text-muted);
220
+ text-transform: uppercase;
221
+ font-size: 11px;
222
+ letter-spacing: 0.05em;
223
+ border-bottom: 1px solid var(--border);
224
+ }
225
+
226
+ td {
227
+ padding: 12px 16px;
228
+ border-bottom: 1px solid var(--border);
229
+ vertical-align: middle;
230
+ }
231
+
232
+ tr:last-child td { border-bottom: none; }
233
+ tbody tr:hover { background: rgba(255, 255, 255, 0.02); }
234
+
235
+ .font-mono { font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace; font-size: 12px; }
236
+ .text-muted { color: var(--text-muted); }
237
+ .text-url { color: #e2e8f0; font-weight: 500; }
238
+ .text-duration { color: #cbd5e1; }
239
+
240
+ .badge {
241
+ display: inline-block;
242
+ padding: 3px 8px;
243
+ border-radius: 4px;
244
+ font-weight: 600;
245
+ font-size: 11px;
246
+ font-family: ui-monospace, monospace;
247
+ }
248
+
249
+ .status-2xx { background: var(--green-bg); color: var(--green-text); border: 1px solid #047857; }
250
+ .status-3xx { background: var(--cyan-bg); color: var(--cyan-text); border: 1px solid #0891b2; }
251
+ .status-4xx { background: var(--yellow-bg); color: var(--yellow-text); border: 1px solid #d97706; }
252
+ .status-5xx { background: var(--red-bg); color: var(--red-text); border: 1px solid #dc2626; }
253
+ .status-other { background: #374151; color: #d1d5db; }
254
+
255
+ .method-get { background: #1e3a8a; color: #93c5fd; }
256
+ .method-post { background: #14532d; color: #86efac; }
257
+ .method-put { background: #713f12; color: #fde047; }
258
+ .method-delete { background: #7f1d1d; color: #fca5a5; }
259
+ .method-patch { background: #581c87; color: #d8b4fe; }
260
+
261
+ .log-body {
262
+ display: inline-block;
263
+ max-width: 280px;
264
+ overflow: hidden;
265
+ text-overflow: ellipsis;
266
+ white-space: nowrap;
267
+ color: #cbd5e1;
268
+ font-family: monospace;
269
+ font-size: 11px;
270
+ background: #0f172a;
271
+ padding: 2px 6px;
272
+ border-radius: 4px;
273
+ border: 1px solid #334155;
274
+ }
275
+
276
+ .empty-row td {
277
+ text-align: center;
278
+ padding: 40px;
279
+ color: var(--text-muted);
280
+ }
281
+ </style>
282
+ </head>
283
+ <body>
284
+ <div class="container">
285
+ <header>
286
+ <div class="title-group">
287
+ <h1>Express Easy Logger <span class="pill">Live Viewer</span></h1>
288
+ <p>Showing the last 100 HTTP requests in real-time (auto-refreshes every 5s)</p>
289
+ </div>
290
+ <div>
291
+ <button id="refreshBtn" class="btn">🔄 Refresh Now</button>
292
+ <button id="toggleAutoBtn" class="btn btn-secondary">⏸ Pause Auto-Refresh</button>
293
+ </div>
294
+ </header>
295
+
296
+ <div class="controls-panel">
297
+ <input type="text" id="filterInput" class="search-input" placeholder="🔍 Filter by method, status (e.g. 200, 404), or URL...">
298
+
299
+ <select id="methodFilter">
300
+ <option value="">All Methods</option>
301
+ <option value="GET">GET</option>
302
+ <option value="POST">POST</option>
303
+ <option value="PUT">PUT</option>
304
+ <option value="DELETE">DELETE</option>
305
+ <option value="PATCH">PATCH</option>
306
+ </select>
307
+
308
+ <select id="statusFilter">
309
+ <option value="">All Statuses</option>
310
+ <option value="2">2xx (Success)</option>
311
+ <option value="3">3xx (Redirect)</option>
312
+ <option value="4">4xx (Client Error)</option>
313
+ <option value="5">5xx (Server Error)</option>
314
+ </select>
315
+
316
+ <span class="refresh-status" id="refreshStatus">Next update in: 5s</span>
317
+ </div>
318
+
319
+ <div class="table-card">
320
+ <table>
321
+ <thead>
322
+ <tr>
323
+ <th style="width: 50px;">#</th>
324
+ <th style="width: 170px;">Timestamp</th>
325
+ <th style="width: 90px;">Method</th>
326
+ <th>URL</th>
327
+ <th style="width: 90px;">Status</th>
328
+ <th style="width: 110px;">Response Time</th>
329
+ <th>Body / Details</th>
330
+ </tr>
331
+ </thead>
332
+ <tbody id="logsBody">
333
+ ${rowsHtml}
334
+ </tbody>
335
+ </table>
336
+ </div>
337
+ </div>
338
+
339
+ <script>
340
+ const dataEndpoint = ${JSON.stringify(dataUrl)};
341
+ let autoRefreshActive = true;
342
+ let countdown = 5;
343
+ let timerId = null;
344
+
345
+ const filterInput = document.getElementById('filterInput');
346
+ const methodFilter = document.getElementById('methodFilter');
347
+ const statusFilter = document.getElementById('statusFilter');
348
+ const logsBody = document.getElementById('logsBody');
349
+ const refreshStatus = document.getElementById('refreshStatus');
350
+ const refreshBtn = document.getElementById('refreshBtn');
351
+ const toggleAutoBtn = document.getElementById('toggleAutoBtn');
352
+
353
+ // Filter table rows based on user input
354
+ function applyFilters() {
355
+ const query = filterInput.value.toLowerCase().trim();
356
+ const method = methodFilter.value.toUpperCase();
357
+ const statusGroup = statusFilter.value;
358
+
359
+ const rows = logsBody.querySelectorAll('tr:not(.empty-row)');
360
+ let visibleCount = 0;
361
+
362
+ rows.forEach(row => {
363
+ const rowMethod = (row.dataset.method || '').toUpperCase();
364
+ const rowStatus = String(row.dataset.status || '');
365
+ const rowUrl = (row.dataset.url || '').toLowerCase();
366
+ const rowText = row.innerText.toLowerCase();
367
+
368
+ const matchesQuery = !query || rowText.includes(query) || rowUrl.includes(query) || rowStatus.includes(query);
369
+ const matchesMethod = !method || rowMethod === method;
370
+ const matchesStatus = !statusGroup || rowStatus.startsWith(statusGroup);
371
+
372
+ if (matchesQuery && matchesMethod && matchesStatus) {
373
+ row.style.display = '';
374
+ visibleCount++;
375
+ } else {
376
+ row.style.display = 'none';
377
+ }
378
+ });
379
+ }
380
+
381
+ filterInput.addEventListener('input', applyFilters);
382
+ methodFilter.addEventListener('change', applyFilters);
383
+ statusFilter.addEventListener('change', applyFilters);
384
+
385
+ function getStatusClass(status) {
386
+ if (status >= 200 && status < 300) return 'status-2xx';
387
+ if (status >= 300 && status < 400) return 'status-3xx';
388
+ if (status >= 400 && status < 500) return 'status-4xx';
389
+ if (status >= 500) return 'status-5xx';
390
+ return 'status-other';
391
+ }
392
+
393
+ function escapeHtml(str) {
394
+ if (!str) return '';
395
+ return String(str)
396
+ .replace(/&/g, '&amp;')
397
+ .replace(/</g, '&lt;')
398
+ .replace(/>/g, '&gt;')
399
+ .replace(/"/g, '&quot;')
400
+ .replace(/'/g, '&#39;');
401
+ }
402
+
403
+ // Fetch latest logs and update table in-place
404
+ async function fetchLogs() {
405
+ try {
406
+ const res = await fetch(dataEndpoint, { headers: { 'Accept': 'application/json' } });
407
+ if (!res.ok) return;
408
+ const data = await res.json();
409
+ const logs = data.logs || [];
410
+
411
+ if (logs.length === 0) {
412
+ logsBody.innerHTML = '<tr class="empty-row"><td colspan="6">No logs recorded yet. Make some requests to your app and they will show up here!</td></tr>';
413
+ return;
414
+ }
415
+
416
+ const rowsHtml = logs.map((log, index) => {
417
+ const statusClass = getStatusClass(log.status);
418
+ const methodClass = 'method-' + (log.method || 'GET').toLowerCase();
419
+ const bodyHtml = log.body ? '<span class="log-body" title="' + escapeHtml(log.body) + '">' + escapeHtml(log.body) + '</span>' : '<span class="text-muted">-</span>';
420
+
421
+ return '<tr data-method="' + escapeHtml(log.method) + '" data-status="' + escapeHtml(String(log.status)) + '" data-url="' + escapeHtml(log.url) + '">' +
422
+ '<td class="text-muted">#' + (logs.length - index) + '</td>' +
423
+ '<td class="font-mono">' + escapeHtml(log.timestamp) + '</td>' +
424
+ '<td><span class="badge ' + methodClass + '">' + escapeHtml(log.method) + '</span></td>' +
425
+ '<td class="font-mono text-url">' + escapeHtml(log.url) + '</td>' +
426
+ '<td><span class="badge ' + statusClass + '">' + escapeHtml(String(log.status)) + '</span></td>' +
427
+ '<td class="font-mono text-duration">' + escapeHtml(log.duration) + '</td>' +
428
+ '<td>' + bodyHtml + '</td>' +
429
+ '</tr>';
430
+ }).join('');
431
+
432
+ logsBody.innerHTML = rowsHtml;
433
+ applyFilters();
434
+ } catch (err) {
435
+ // Ignore network glitches
436
+ }
437
+ }
438
+
439
+ // Auto-refresh countdown loop
440
+ setInterval(() => {
441
+ if (!autoRefreshActive) return;
442
+ countdown--;
443
+ if (countdown <= 0) {
444
+ countdown = 5;
445
+ fetchLogs();
446
+ }
447
+ refreshStatus.textContent = 'Next update in: ' + countdown + 's';
448
+ }, 1000);
449
+
450
+ refreshBtn.addEventListener('click', () => {
451
+ countdown = 5;
452
+ refreshStatus.textContent = 'Refreshing...';
453
+ fetchLogs().then(() => {
454
+ refreshStatus.textContent = 'Next update in: 5s';
455
+ });
456
+ });
457
+
458
+ toggleAutoBtn.addEventListener('click', () => {
459
+ autoRefreshActive = !autoRefreshActive;
460
+ if (autoRefreshActive) {
461
+ toggleAutoBtn.textContent = '⏸ Pause Auto-Refresh';
462
+ toggleAutoBtn.classList.remove('btn-secondary');
463
+ refreshStatus.textContent = 'Next update in: ' + countdown + 's';
464
+ } else {
465
+ toggleAutoBtn.textContent = '▶ Resume Auto-Refresh';
466
+ toggleAutoBtn.classList.add('btn-secondary');
467
+ refreshStatus.textContent = 'Auto-refresh paused';
468
+ }
469
+ });
470
+ </script>
471
+ </body>
472
+ </html>`;
473
+ }
474
+
475
+ /**
476
+ * Creates the Express middleware/route handler for the log viewer dashboard.
477
+ *
478
+ * @param {object} [options]
479
+ * @param {string} [options.file='./logs/app.log'] - Path to log file
480
+ * @returns {Function} Express middleware (req, res, next)
481
+ */
482
+ function viewer(options = {}) {
483
+ const filePath = options.file || './logs/app.log';
484
+
485
+ return function viewerMiddleware(req, res, next) {
486
+ try {
487
+ const isJsonRequest =
488
+ req.query && req.query.format === 'json' ||
489
+ (req.url && (req.url === '/data' || req.url.endsWith('/data'))) ||
490
+ (req.headers.accept && req.headers.accept.includes('application/json'));
491
+
492
+ // Return JSON data
493
+ if (isJsonRequest) {
494
+ const logs = readLastLogs(filePath, 100);
495
+ res.setHeader('Content-Type', 'application/json');
496
+ return res.end(JSON.stringify({ logs }));
497
+ }
498
+
499
+ // Serve HTML dashboard
500
+ const logs = readLastLogs(filePath, 100);
501
+
502
+ // Determine the proper relative JSON URL based on how the middleware is mounted
503
+ let baseUrl = req.baseUrl || req.originalUrl.split('?')[0];
504
+ if (baseUrl.endsWith('/')) {
505
+ baseUrl = baseUrl.slice(0, -1);
506
+ }
507
+ const dataUrl = `${baseUrl}?format=json`;
508
+
509
+ const html = renderHtml(logs, dataUrl);
510
+ res.setHeader('Content-Type', 'text/html; charset=utf-8');
511
+ return res.end(html);
512
+ } catch (err) {
513
+ next(err);
514
+ }
515
+ };
516
+ }
517
+
518
+ module.exports = viewer;