-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
208 lines (178 loc) · 6.8 KB
/
index.js
File metadata and controls
208 lines (178 loc) · 6.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
const mongoose = require("mongoose");
const axios = require("axios");
let key;
let secret;
class Bugatlas {
constructor(apiKey, apiSecret) {
key = apiKey;
secret = apiSecret;
if (!apiKey || !apiSecret) {
if (!apiKey) {
console.log("Please Provide apiKey");
}
if (!apiSecret) {
console.log("Please Provide apiSecret");
}
}
// Register uncaughtException handler
process.on('uncaughtException', (err) => {
if (err) {
console.log("uncaughtException")
this.storeError(err);
}
});
// Register unhandledRejection handler
process.on('unhandledRejection', (reason, promise) => {
console.log("unhandledRejection")
if (reason) {
this.storeError(reason);
}
});
}
async storeError(err) {
const { code, keyPattern } = err;
if (code === 11000 && keyPattern) {
return this.handleDuplicateKeyError(err);
}
if (err instanceof mongoose.Error.ValidationError) {
return this.handleValidationError(err);
}
await this.sendErrorToApi(err.name, err.message, err.stack);
}
async caughtErrors(err) {
const { code } = err;
if (code === 11000) {
return this.handleDuplicateKeyError(err);
}
if (err instanceof mongoose.Error.ValidationError) {
return this.handleValidationError(err);
}
// console.log(err, "caughtErrors")
await this.sendErrorToApi(err.name, err.message, err.stack);
}
async handleDuplicateKeyError(err) {
const value=`${Object.keys(err.keyValue).join(' and ')} already exists in DB`
if(value){
await this.sendErrorToApi("MongoDuplicateKeyError", value, err.stack);
}
}
async handleValidationError(err) {
for (const field in err.errors) {
if (err.errors[field].kind === 'ObjectId') {
// console.log(err, "handleValidationError");
await this.sendErrorToApi(err.name, `Invalid ${field} ID provided!`, err.stack);
} else {
console.log(err.message);
}
}
}
async sendErrorToApi(errorName, errorMessage, errorStack) {
try {
const {data} = await axios.post("https://api.bugatlas.com/v1/api/errors",{
error_type: errorName,
error_message: errorMessage,
meta: {
meta: errorStack
}
},
{
headers: {
"api_key": key,
"secret_key": secret
}
}
);
// console.log("sendErrorToApiCompleted", data);
} catch (error) {
console.error("Error sending error to API:", error.message);
}
}
async createLog(req, res, next) {
try {
const startTime = new Date();
let responseData = ''; // Variable to store response data
// Override res.send to capture response data
const originalSend = res.send;
res.send = function (body) {
responseData = JSON.parse(body); // Capture response data
originalSend.call(res, body); // Send the response once
};
res.on('finish', async () => {
try {
const endTime = new Date();
const processTime = endTime - startTime;
// Create log data
const logData = {
request_user_agent: req.headers['user-agent'],
request_host: req.headers['origin'] || req.headers.host,
request_method: req.method,
payload: req.body,
protocol: req.protocol,
request_url: req.originalUrl,
type: res.statusCode !== 200 ? 2 : 1,
status_code: res.statusCode,
status_message: res.statusMessage,
content_length: `${res.get('Content-Length') || 0} bytes`,
requested_at: new Date().toLocaleString('en-IN', { timeZone: 'Asia/Kolkata' }),
remote_address: req.connection.remoteAddress,
request_ip: req.ip,
response_message: responseData?.message || '',
process_time: `${processTime} ${unitCalculation(processTime)}`,
};
if (res.statusCode !== 200 && res.statusCode !== 201) {
const data = await axios.post("https://api.bugatlas.com/v1/api/errors", {
request_url: req.originalUrl,
request_method: req.method,
error_message: responseData?.message || '',
payload: req.body,
meta: {
data: responseData
}
}, {
headers: {
"api_key": key,
"secret_key": secret
}
});
// console.log("apiErrorData",data)
} else {
const data = await axios.post("https://api.bugatlas.com/v1/api/logs", logData, {
headers: {
"api_key": key,
"secret_key": secret
}
});
// console.log(data, "apiLogData");
}
} catch (err) {
console.log('Error creating logs:', err.message);
}
});
next();
} catch (err) {
console.log('Error in api logger middleware:', err.message);
next();
}
}
}
module.exports = Bugatlas;
const unitCalculation = function(processTime) {
let unit = 'ms';
// Convert to seconds if processTime is >= 1000 milliseconds
if (processTime >= 1000) {
if (processTime >= 60 * 60 * 1000) {
// Convert to hours
processTime /= 60 * 60 * 1000;
unit = 'hrs';
} else if (processTime >= 60 * 1000) {
// Convert to minutes
processTime /= 60 * 1000;
unit = 'min';
} else {
// Convert to seconds
processTime /= 1000;
unit = 's';
}
}
return unit;
}