@anhocva214/logzen 1.0.0

Sign up to get free protection for your applications and to get access to all the features.
package/README.md ADDED
@@ -0,0 +1,8 @@
1
+ # LogZen
2
+
3
+ **LogZen** là một middleware logging nhẹ cho các ứng dụng Node.js/Express, được viết bằng TypeScript. Module này ghi lại chi tiết các request và response theo định dạng JSON, giúp bạn dễ dàng tích hợp và theo dõi hoạt động của hệ thống.
4
+
5
+ ## Cài đặt
6
+
7
+ ```bash
8
+ npm install @anho/logzen
@@ -0,0 +1,15 @@
1
+ import { Request, Response, NextFunction } from "express";
2
+ export interface LogZenOptions {
3
+ /**
4
+ * Đường dẫn đến file log nơi các log sẽ được ghi.
5
+ * Mặc định là 'logzen.log' tại thư mục hiện hành.
6
+ */
7
+ filePath?: string;
8
+ }
9
+ /**
10
+ * LogZen middleware
11
+ * @param options Cấu hình cho middleware
12
+ * @returns Express middleware function
13
+ */
14
+ export declare function logzen(options?: LogZenOptions): (req: Request, res: Response, next: NextFunction) => void;
15
+ export default logzen;
package/dist/index.js ADDED
@@ -0,0 +1,82 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ Object.defineProperty(exports, "__esModule", { value: true });
26
+ exports.logzen = void 0;
27
+ const fs = __importStar(require("fs"));
28
+ const path = __importStar(require("path"));
29
+ /**
30
+ * LogZen middleware
31
+ * @param options Cấu hình cho middleware
32
+ * @returns Express middleware function
33
+ */
34
+ function logzen(options = {}) {
35
+ const filePath = options.filePath || path.join(process.cwd(), "logzen.log");
36
+ // Tạo stream ghi log ở chế độ append
37
+ const logStream = fs.createWriteStream(filePath, { flags: "a" });
38
+ return (req, res, next) => {
39
+ const startTime = Date.now();
40
+ const { method, originalUrl, headers } = req;
41
+ // Khai báo mảng chứa các phần của response
42
+ const chunks = [];
43
+ // Lưu lại tham chiếu của các hàm gốc
44
+ const originalWrite = res.write.bind(res);
45
+ const originalEnd = res.end.bind(res);
46
+ // Ghi đè res.write để lưu lại các chunk dữ liệu của response
47
+ res.write = ((chunk, ...args) => {
48
+ // chunk có thể là string hoặc Buffer
49
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
50
+ return originalWrite(chunk, ...args);
51
+ });
52
+ // Ghi đè res.end để hoàn thiện quá trình logging khi response kết thúc
53
+ res.end = ((chunk, ...args) => {
54
+ if (chunk) {
55
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
56
+ }
57
+ const responseBody = Buffer.concat(chunks).toString("utf8");
58
+ const duration = Date.now() - startTime;
59
+ const logEntry = {
60
+ time: new Date().toISOString(),
61
+ duration,
62
+ request: {
63
+ method,
64
+ url: originalUrl,
65
+ headers,
66
+ // Lưu ý: req.body sẽ có giá trị nếu middleware body-parser đã được gọi trước
67
+ body: req.body || null,
68
+ },
69
+ response: {
70
+ statusCode: res.statusCode,
71
+ body: responseBody,
72
+ },
73
+ };
74
+ // Ghi log dưới dạng JSON
75
+ logStream.write(JSON.stringify(logEntry) + "\n");
76
+ return originalEnd(chunk, ...args);
77
+ });
78
+ next();
79
+ };
80
+ }
81
+ exports.logzen = logzen;
82
+ exports.default = logzen;
package/package.json ADDED
@@ -0,0 +1,30 @@
1
+ {
2
+ "name": "@anhocva214/logzen",
3
+ "version": "1.0.0",
4
+ "description": "A lightweight logging middleware for Node.js/Express written in TypeScript that logs request and response details in JSON format.",
5
+ "main": "dist/index.js",
6
+ "types": "dist/index.d.ts",
7
+ "scripts": {
8
+ "build": "tsc",
9
+ "test": "echo \"No tests yet\""
10
+ },
11
+ "keywords": [
12
+ "logging",
13
+ "middleware",
14
+ "express",
15
+ "nodejs",
16
+ "typescript",
17
+ "log"
18
+ ],
19
+ "author": "anho",
20
+ "license": "MIT",
21
+ "dependencies": {},
22
+ "devDependencies": {
23
+ "@types/express": "^4.17.15",
24
+ "@types/node": "^18.11.0",
25
+ "typescript": "^4.9.5"
26
+ },
27
+ "publishConfig": {
28
+ "access": "public"
29
+ }
30
+ }
package/src/index.ts ADDED
@@ -0,0 +1,76 @@
1
+ import { Request, Response, NextFunction } from "express";
2
+ import * as fs from "fs";
3
+ import * as path from "path";
4
+
5
+ export interface LogZenOptions {
6
+ /**
7
+ * Đường dẫn đến file log nơi các log sẽ được ghi.
8
+ * Mặc định là 'logzen.log' tại thư mục hiện hành.
9
+ */
10
+ filePath?: string;
11
+ }
12
+
13
+ /**
14
+ * LogZen middleware
15
+ * @param options Cấu hình cho middleware
16
+ * @returns Express middleware function
17
+ */
18
+ export function logzen(options: LogZenOptions = {}) {
19
+ const filePath = options.filePath || path.join(process.cwd(), "logzen.log");
20
+
21
+ // Tạo stream ghi log ở chế độ append
22
+ const logStream = fs.createWriteStream(filePath, { flags: "a" });
23
+
24
+ return (req: Request, res: Response, next: NextFunction): void => {
25
+ const startTime = Date.now();
26
+ const { method, originalUrl, headers } = req;
27
+
28
+ // Khai báo mảng chứa các phần của response
29
+ const chunks: Buffer[] = [];
30
+
31
+ // Lưu lại tham chiếu của các hàm gốc
32
+ const originalWrite = res.write.bind(res);
33
+ const originalEnd = res.end.bind(res);
34
+
35
+ // Ghi đè res.write để lưu lại các chunk dữ liệu của response
36
+ res.write = ((chunk: any, ...args: any[]): boolean => {
37
+ // chunk có thể là string hoặc Buffer
38
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
39
+ return originalWrite(chunk, ...args);
40
+ }) as typeof res.write;
41
+
42
+ // Ghi đè res.end để hoàn thiện quá trình logging khi response kết thúc
43
+ res.end = ((chunk?: any, ...args: any[]): Response => {
44
+ if (chunk) {
45
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
46
+ }
47
+ const responseBody = Buffer.concat(chunks).toString("utf8");
48
+ const duration = Date.now() - startTime;
49
+
50
+ const logEntry = {
51
+ time: new Date().toISOString(),
52
+ duration, // Thời gian xử lý request (ms)
53
+ request: {
54
+ method,
55
+ url: originalUrl,
56
+ headers,
57
+ // Lưu ý: req.body sẽ có giá trị nếu middleware body-parser đã được gọi trước
58
+ body: req.body || null,
59
+ },
60
+ response: {
61
+ statusCode: res.statusCode,
62
+ body: responseBody,
63
+ },
64
+ };
65
+
66
+ // Ghi log dưới dạng JSON
67
+ logStream.write(JSON.stringify(logEntry) + "\n");
68
+
69
+ return originalEnd(chunk, ...args);
70
+ }) as typeof res.end;
71
+
72
+ next();
73
+ };
74
+ }
75
+
76
+ export default logzen;
package/tsconfig.json ADDED
@@ -0,0 +1,13 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "es6",
4
+ "module": "commonjs",
5
+ "declaration": true,
6
+ "outDir": "./dist",
7
+ "strict": true,
8
+ "esModuleInterop": true,
9
+ "skipLibCheck": true
10
+ },
11
+ "include": ["src"],
12
+ "exclude": ["node_modules", "**/*.spec.ts"]
13
+ }