logs-ks
v0.3.10
Published
A lightweight and developer-friendly middleware that provides structured and contextual logging for Express APIs.
Downloads
189
Readme
🛠️ Express API Middleware Logger
A lightweight and developer-friendly middleware that provides structured and contextual logging for Express APIs.
This middleware helps developers easily trace API calls, debug issues, and monitor request/response cycles by capturing detailed logs. It supports time-based log batching and works seamlessly in both development and production environments with minimal setup.
📦 Installation
Install the core logging package:
npm install logs-ks⚙️ Quick Setup
index.ts – Initialize Logger
import express from 'express';
import { Logger } from 'logs-ks';
const app = express();
// Initialize logger with custom configuration
// Note: Logger.init() must be called before using the middleware
Logger.init({
writeLogTime: 5, // Write logs to file every 5 minutes
logWithEnd: true, // Default false logging response at the end of API calls
logWithSummary: true, // Default false logging api summary like > 2025-06-13 10:11:12 | GET 200 /api/v2/user 20 ms
});router.ts – Apply Middleware per Route
import express, { Request, Response } from 'express';
import { loggerMiddleware, LoggerContext, logEmitter } from 'logs-ks';
const router = express.Router();
// request api localhost:3000/api/foo?page=1&limit=10
router.get('/api/:id', loggerMiddleware(), async (req: Request, res: Response) => {
try {
const { id } = req.params;
const data = await getController(id);
res.json(data);
} catch (error: unknown) {
res.status(500).send(error);
}
});
// Use loggerMiddleware(false) to disable logging the response payload
// Useful for lightweight GET endpoints
router.get('/api/user/all', loggerMiddleware(false), (req, res) => res.json({ code: 200, payload: '...too much data' }));
async function getController(id) {
const logger = LoggerContext.get();
logger.addService({ type: 'DB' }, { name: 'findUser', argument: { id } });
const findUser = await findUserDB({ id });
logger.endService(findUser);
return { code: 200, payload: { foo: 'bar' } };
}
// Listen for when a log file is finalized (previous file that finished writing)
// `filePath` refers to the last log file that was completed and closed
logEmitter.on('file-end', (filePath) => {
console.log(`New log file created: ${filePath}`);
// You can trigger backup, upload to S3, or notify devs here
});
export default router;🧪 Example Log Output (JSON)
{
"api": "api/foo?page=1&limit=10",
"method": "GET",
"authorization": null,
"status": 200,
"message": "OK",
"inputTimestamp": "2025-06-13T10:11:12.000Z",
"outputTimestamp": "2025-06-13T10:11:12.020Z",
"processingTime": "20 ms",
"request": {
"headers": {},
"params": { id: "foo"},
"query": { page: "1", limit: "10" },
"body": {},
"detail": {}
},
"services": [{
"id": 1,
"type": "DB",
"request": { "name": "findUser", "argument": { "id": "foo" } },
"response": { "id": "foo", "name": "foobar" },
"processingTime": "5 ms",
"startTime": "2025-06-11T10:11:12.010Z",
"endTime": "2025-06-11T10:11:12.015Z"
}],
"response": {
"code": 200,
"payload": { "foo": "bar" }
},
"summary": "2025-06-13 10:11:12 | GET 200 /api/user 20 ms"
}
type {
api: string;
method: string;
authorization: string | JwtPayload | null;
status: number;
message: string;
inputTimestamp: string;
outputTimestamp: string;
processingTime: string;
request: {
headers: Record<string, string>; // soon
params: Record<string, string>;
query: Record<string, string>;
body: Record<string, any>;
detail: Record<string, any>; // soon
};
services: Array<{
id: number;
type: 'DB' | 'API' | 'REDIS' | 'S3' | 'FILE' | 'FUNC';
request: {
name: string;
argument: Record<string, any>;
};
response: Record<string, any> | Array<Record<string, any>>;
processingTime: string;
startTime: string;
endTime: string;
}>;
response: Record<string, any>;
summary: string;
}🧩 Features
- ✅ Plug-and-play Express middleware
- 📄 Structured logs for easy debugging
- ⏱️ Time-based file writes for performance
- 🔍 Contextual request/response trace logging
- 💻 Console + file output support
📁 Output
Log files will be saved automatically in the working directory (or custom location if configured via logs-ks).
- 📂 Default path:
./logs/app-logs-${yy}-${mm}-${dd}-${hh}${mi}.jsonl - (e.g.
logs/app-log-25-06-13-1300.jsonl)
