@nm-logger/logger 1.1.6 → 1.1.8

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,14 +1,241 @@
1
1
  # @nm-logger/logger
2
2
 
3
- Express JSON logger with:
4
-
3
+ Daily JSON logger for Node.js / Express APIs with:
5
4
  - Per-request logging (success, error, external API)
6
5
  - Separate daily files:
7
6
  - `daily_logs_success.json`
8
7
  - `daily_logs_error.json`
9
8
  - `daily_logs_external.json`
10
- - Periodic S3 upload (and local file deletion)
11
- - Correlation IDs (`X-Correlation-ID`)
12
- - Sensitive field masking
9
+ - S3 upload + queue + daily rotation
10
+ - Correlation IDs (with `X-Correlation-ID` header)
11
+ - External API logging (Axios)
12
+ - Sensitive field masking (password, token, otp, etc.)
13
+
14
+ ---
15
+
16
+ ## Installation
17
+
18
+ After you publish the package to npm:
19
+
20
+ ```bash
21
+ npm install @nm-logger/logger
22
+ ```
23
+
24
+ ---
25
+
26
+ ## Log Format
27
+
28
+ Each log line in `daily_logs.json` is a JSON object:
29
+
30
+ ```json
31
+ {
32
+ "url": "/api/v1/attendance/get",
33
+ "body": "{\"month\":\"2025-12\"}",
34
+ "params": "{\"params\":{},\"query\":{}}",
35
+ "type": "get",
36
+ "error": "",
37
+ "date": "2025-12-05 12:24:00",
38
+ "employee_id": "TAKK122",
39
+ "correlation_id": "cid-abcd1234-17f5d3c9a"
40
+ }
41
+ ```
42
+
43
+ Fields:
44
+
45
+ - `url` – `req.originalUrl`
46
+ - `body` – stringified (and masked) `req.body`
47
+ - `params` – stringified (and masked) object `{ params: req.params, query: req.query }`
48
+ - `type` – last segment of the URL (e.g. `/api/v1/attendance/get` → `"get"`)
49
+ - `error` – error message if any
50
+ - `date` – `YYYY-MM-DD HH:mm:ss`
51
+ - `employee_id` – from argument or `req.user.employee_id / emp_code / id`
52
+ - `correlation_id` – unique per request chain (also added as `X-Correlation-ID` header)
53
+
54
+ ---
55
+
56
+ ## Basic Usage
57
+
58
+ ### 1. Create the logger
59
+
60
+ ```js
61
+ const Logger = require("@nm-logger/logger");
62
+
63
+ const logger = new Logger(
64
+ {
65
+ accessKeyId: process.env.AWS_KEY,
66
+ secretAccessKey: process.env.AWS_SECRET,
67
+ region: "ap-south-1",
68
+ bucket: "your-log-bucket-name"
69
+ },
70
+ {
71
+ baseDir: "logs", // optional, default "logs"
72
+ watchIntervalMs: 60000, // optional, default 60s
73
+ maskFields: ["aadhaar", "panNumber"] // extra fields to mask
74
+ }
75
+ );
76
+ ```
77
+
78
+ ### 2. Log every request + set correlation ID header
79
+
80
+ ```js
81
+ app.use(logger.requestLoggerMiddleware());
82
+ ```
83
+
84
+ ### 3. Log errors via Express error middleware
85
+
86
+ ```js
87
+ // your routes above...
88
+
89
+ app.use(logger.expressMiddleware()); // or logger.expressErrorMiddleware()
90
+ ```
91
+
92
+ ### 4. Manual logging in routes
93
+
94
+ ```js
95
+ app.post("/api/v1/attendance/get", async (req, res) => {
96
+ try {
97
+ // ... your logic, external APIs etc ...
98
+
99
+ await logger.logRequest(req, req.user?.employee_id);
100
+ res.json({ success: true });
101
+ } catch (err) {
102
+ await logger.logError(err, req, req.user?.employee_id);
103
+ res.status(500).json({ error: err.message });
104
+ }
105
+ });
106
+ ```
107
+
108
+ ---
109
+
110
+ ## External API logging with Axios
111
+
112
+ ```js
113
+ const axios = require("axios");
114
+
115
+ // Attach once at startup
116
+ logger.attachAxiosLogger(axios);
117
+
118
+ app.get("/api/v1/some-data", async (req, res) => {
119
+ try {
120
+ const response = await axios.get("https://api.example.com/data", {
121
+ headers: {
122
+ "X-Correlation-ID": req.correlationId, // propagated
123
+ "X-Employee-ID": req.user?.employee_id || "" // optional
124
+ },
125
+ params: {
126
+ id: 123
127
+ }
128
+ });
129
+
130
+ res.json(response.data);
131
+ } catch (err) {
132
+ await logger.logError(err, req, req.user?.employee_id);
133
+ res.status(500).json({ error: err.message });
134
+ }
135
+ });
136
+ ```
137
+
138
+ This will produce external log lines like:
139
+
140
+ ```json
141
+ {
142
+ "url": "https://api.example.com/data",
143
+ "body": "{}",
144
+ "params": "{\"id\":123}",
145
+ "type": "external_api",
146
+ "error": "",
147
+ "date": "2025-12-05 12:24:00",
148
+ "employee_id": "TAKK122",
149
+ "correlation_id": "cid-abcd1234-17f5d3c9a"
150
+ }
151
+ ```
152
+
153
+ ---
154
+
155
+ ## Sensitive Data Masking
156
+
157
+ Built-in masked keys (case-insensitive, partial match):
158
+
159
+ - password, pass
160
+ - token, secret
161
+ - otp
162
+ - auth, authorization
163
+ - apiKey, api_key
164
+ - session
165
+ - ssn
166
+
167
+ Plus anything you pass in `maskFields` option.
168
+
169
+ Any object like:
170
+
171
+ ```json
172
+ {
173
+ "password": "MyPass123",
174
+ "otp": "111222",
175
+ "aadhaar": "9999-8888-7777",
176
+ "email": "user@example.com"
177
+ }
178
+ ```
179
+
180
+ will be logged as:
181
+
182
+ ```json
183
+ {
184
+ "password": "*****",
185
+ "otp": "*****",
186
+ "aadhaar": "*****",
187
+ "email": "user@example.com"
188
+ }
189
+ ```
190
+
191
+ ---
192
+
193
+ ## S3 Upload Behavior
194
+
195
+ - Logs are stored locally under:
196
+ - `logs/YYYY/MM/DD/daily_logs.json`
197
+ - A watcher runs every `watchIntervalMs` (default 60 seconds)
198
+ - When the date changes (e.g., from `2025-12-05` to `2025-12-06`),
199
+ - The logger uploads the **previous day's** log file to S3:
200
+
201
+ Example S3 key:
202
+
203
+ ```txt
204
+ 2025/12/05/daily_logs.json
205
+ ```
206
+
207
+ So final S3 path:
208
+
209
+ ```txt
210
+ s3://<bucket>/<year>/<month>/<day>/daily_logs.json
211
+ ```
212
+
213
+ ---
214
+
215
+ ## TypeScript Usage
216
+
217
+ ```ts
218
+ import Logger, { S3Config, LoggerOptions } from "@ve/logger";
219
+
220
+ const s3config: S3Config = {
221
+ accessKeyId: process.env.AWS_KEY!,
222
+ secretAccessKey: process.env.AWS_SECRET!,
223
+ region: "ap-south-1",
224
+ bucket: "your-log-bucket"
225
+ };
226
+
227
+ const options: LoggerOptions = {
228
+ baseDir: "logs",
229
+ watchIntervalMs: 60000,
230
+ maskFields: ["aadhaar", "pan"]
231
+ };
232
+
233
+ const logger = new Logger(s3config, options);
234
+ ```
235
+
236
+ ---
237
+
238
+ ## License
239
+
240
+ MIT
13
241
 
14
- See source comments for usage.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nm-logger/logger",
3
- "version": "1.1.6",
3
+ "version": "1.1.8",
4
4
  "description": "Express JSON logger with S3 upload, correlation IDs, and separate success/error/external daily logs.",
5
5
  "main": "index.js",
6
6
  "types": "index.d.ts",
@@ -22,7 +22,8 @@
22
22
  "license": "MIT",
23
23
  "dependencies": {
24
24
  "@aws-sdk/client-s3": "^3.600.0",
25
- "fs-extra": "^11.1.1"
25
+ "fs-extra": "^11.1.1",
26
+ "@nm-logger/logger": "^1.1.8"
26
27
  },
27
28
  "peerDependencies": {
28
29
  "express": ">=4.0.0"
@@ -40,16 +40,42 @@ class DailyWatcher {
40
40
  return;
41
41
  }
42
42
 
43
- this.queue.add(async () => {
44
- try {
45
- console.log(`📤 Uploading [${category}] logs to S3:`, key);
46
- await this.s3Uploader.upload(file, key);
47
- console.log("✅ Uploaded. Deleting local file:", file);
48
- await fs.remove(file);
49
- } catch (err) {
50
- console.error(`❌ Error uploading [${category}] logs to S3:`, err);
51
- }
52
- });
43
+ this.queue.add(async () => {
44
+ try {
45
+ const now = new Date();
46
+ const key = `${Y}/${M}/${D}/${fileName}`;
47
+
48
+ console.log(`📤 Uploading [${category}] logs to S3: ${key}`);
49
+
50
+ // Step 1 Read local file
51
+ const localContent = JSON.parse(await fs.readFile(file, "utf8"));
52
+
53
+ // Step 2 — Try loading existing file from S3
54
+ let existing = { logs: [] };
55
+ try {
56
+ const s3Content = await this.s3Uploader.getObject(key);
57
+ if (s3Content) {
58
+ existing = JSON.parse(s3Content);
59
+ }
60
+ } catch (err) {
61
+ // File may not exist on first upload — ignore
62
+ }
63
+
64
+ // Step 3 — Append logs
65
+ const merged = {
66
+ logs: [...existing.logs, ...localContent.logs]
67
+ };
68
+
69
+ // Step 4 — Upload merged logs
70
+ await this.s3Uploader.putObject(key, JSON.stringify(merged, null, 2));
71
+
72
+ console.log("✅ Logs appended to S3 successfully");
73
+
74
+ } catch (err) {
75
+ console.error(`❌ Error uploading logs to S3:`, err);
76
+ }
77
+ });
78
+
53
79
  });
54
80
  }, this.intervalMs);
55
81
  }
package/src/S3Uploader.js CHANGED
@@ -1,8 +1,10 @@
1
1
  const fs = require("fs");
2
2
  const {
3
3
  S3Client,
4
- PutObjectCommand
4
+ PutObjectCommand,
5
+ GetObjectCommand
5
6
  } = require("@aws-sdk/client-s3");
7
+ const { streamToString } = require("./utils");
6
8
 
7
9
  class S3Uploader {
8
10
  constructor(config) {
@@ -17,16 +19,28 @@ class S3Uploader {
17
19
  this.bucket = config.bucket;
18
20
  }
19
21
 
20
- async upload(filePath, s3Key) {
21
- const fileData = fs.readFileSync(filePath);
22
-
23
- const command = new PutObjectCommand({
24
- Bucket: this.bucket,
25
- Key: s3Key,
26
- Body: fileData
27
- });
22
+ async getObject(key) {
23
+ try {
24
+ const result = await this.client.send(
25
+ new GetObjectCommand({
26
+ Bucket: this.bucket,
27
+ Key: key
28
+ })
29
+ );
30
+ return await streamToString(result.Body);
31
+ } catch (err) {
32
+ return null; // file not found
33
+ }
34
+ }
28
35
 
29
- await this.client.send(command);
36
+ async putObject(key, body) {
37
+ await this.client.send(
38
+ new PutObjectCommand({
39
+ Bucket: this.bucket,
40
+ Key: key,
41
+ Body: body
42
+ })
43
+ );
30
44
  }
31
45
  }
32
46
 
package/src/utils.js CHANGED
@@ -89,3 +89,12 @@ exports.generateCorrelationId = () => {
89
89
  const ts = Date.now().toString(16);
90
90
  return `cid-${rand}-${ts}`;
91
91
  };
92
+
93
+ exports.streamToString = async (stream) => {
94
+ return await new Promise((resolve, reject) => {
95
+ const chunks = [];
96
+ stream.on("data", (chunk) => chunks.push(chunk));
97
+ stream.on("error", reject);
98
+ stream.on("end", () => resolve(Buffer.concat(chunks).toString("utf8")));
99
+ });
100
+ };