Repository navigation
Expand file tree
/
Copy pathlogger.js
More file actions
277 lines (251 loc) · 7.12 KB
/
Copy pathlogger.js
File metadata and controls
277 lines (251 loc) · 7.12 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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
/**
* Structured Logging Service with Winston
*
* Provides JSON-formatted logs with:
* - Trace IDs for request correlation
* - Wallet addresses for user tracking
* - Contract IDs for blockchain operations
* - Severity levels and contextual metadata
*/
const winston = require('winston');
const { v4: uuidv4 } = require('uuid');
// Custom format for structured logging
const { combine, timestamp, json, errors, splat } = winston.format;
// Create logger instance
const logger = winston.createLogger({
level: process.env.LOG_LEVEL || 'info',
format: combine(
errors({ stack: true }),
timestamp({ format: 'ISO8601' }),
splat(), // Support printf-style formatting
json()
),
defaultMeta: {
service: 'substream-protocol',
environment: process.env.NODE_ENV || 'development',
},
transports: [
// Console transport for development
new winston.transports.Console({
format: process.env.NODE_ENV === 'production'
? json()
: combine(
timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }),
winston.format.printf(({ level, message, timestamp, ...meta }) => {
return `${timestamp} [${level.toUpperCase()}] ${message} ${
Object.keys(meta).length ? JSON.stringify(meta, null, 2) : ''
}`;
})
),
}),
// File transport for error logs
new winston.transports.File({
filename: 'logs/error.log',
level: 'error',
maxsize: 10485760, // 10MB
maxFiles: 5,
}),
// File transport for all logs
new winston.transports.File({
filename: 'logs/combined.log',
maxsize: 10485760, // 10MB
maxFiles: 5,
}),
],
});
/**
* Add trace context to log entries
* @param {string} traceId - Unique trace identifier
* @param {object} additionalContext - Additional context to add
*/
function createLoggerContext(traceId, additionalContext = {}) {
return {
traceId: traceId || uuidv4(),
...additionalContext,
};
}
/**
* Middleware to add trace ID to all requests
*/
function requestTracingMiddleware(req, res, next) {
// Get or create trace ID
const traceId = req.headers['x-trace-id'] || uuidv4();
// Add trace ID to response headers
res.setHeader('x-trace-id', traceId);
// Attach logger to request with context
req.logger = logger.child({
traceId,
method: req.method,
path: req.path,
ip: req.ip,
userAgent: req.headers['user-agent'],
});
// Track request timing
const startTime = Date.now();
res.on('finish', () => {
const duration = Date.now() - startTime;
const context = {
traceId,
statusCode: res.statusCode,
duration: `${duration}ms`,
};
if (res.statusCode >= 500) {
logger.error('Request failed', context);
} else if (res.statusCode >= 400) {
logger.warn('Client error', context);
} else {
logger.info('Request completed', context);
}
});
next();
}
/**
* Log wallet-related operations
* @param {string} walletAddress - Stellar wallet address
* @param {string} action - Action being performed
* @param {object} metadata - Additional metadata
*/
function logWalletOperation(walletAddress, action, metadata = {}) {
logger.info(`Wallet operation: ${action}`, {
walletAddress: walletAddress.toLowerCase(),
action,
...metadata,
});
}
/**
* Log smart contract interactions
* @param {string} contractId - Soroban contract ID
* @param {string} operation - Contract operation
* @param {object} txHash - Transaction hash
* @param {object} metadata - Additional metadata
*/
function logContractInteraction(contractId, operation, txHash, metadata = {}) {
logger.info(`Contract interaction: ${operation}`, {
contractId,
operation,
transactionHash: txHash,
network: process.env.STELLAR_NETWORK_PASSPHRASE?.includes('Test') ? 'testnet' : 'mainnet',
...metadata,
});
}
/**
* Log authentication events
* @param {string} walletAddress - Wallet address
* @param {string} eventType - Event type (login, logout, failed, etc.)
* @param {object} metadata - Additional metadata
*/
function logAuthEvent(walletAddress, eventType, metadata = {}) {
const logLevel = eventType.includes('failed') ? 'warn' : 'info';
logger[logLevel](`Authentication event: ${eventType}`, {
walletAddress: walletAddress?.toLowerCase(),
eventType,
category: 'authentication',
...metadata,
});
}
/**
* Log payment/payout operations
* @param {string} walletAddress - Recipient wallet
* @param {number} amount - Amount in stroops
* @param {string} asset - Asset type
* @param {object} metadata - Additional metadata
*/
function logPayment(walletAddress, amount, asset, metadata = {}) {
logger.info('Payment processed', {
walletAddress: walletAddress.toLowerCase(),
amount,
asset,
category: 'payment',
...metadata,
});
}
/**
* Log Sybil/fraud detection events
* @param {string} deviceId - Device ID
* @param {string} riskLevel - Risk level (low, medium, high, critical)
* @param {array} flags - Array of flag identifiers
* @param {object} metadata - Additional metadata
*/
function logFraudDetection(deviceId, riskLevel, flags, metadata = {}) {
const logLevel = riskLevel === 'critical' ? 'error' :
riskLevel === 'high' ? 'warn' : 'info';
logger[logLevel]('Fraud detection alert', {
deviceId,
riskLevel,
flags,
category: 'fraud-prevention',
...metadata,
});
}
/**
* Log video processing events
* @param {string} videoId - Video ID
* @param {string} status - Processing status
* @param {object} metadata - Additional metadata
*/
function logVideoProcessing(videoId, status, metadata = {}) {
logger.info(`Video processing: ${status}`, {
videoId,
status,
category: 'video-processing',
...metadata,
});
}
/**
* Log database operations
* @param {string} operation - Database operation
* @param {string} table - Table name
* @param {object} metadata - Additional metadata
*/
function logDatabaseOperation(operation, table, metadata = {}) {
logger.debug(`Database operation: ${operation}`, {
operation,
table,
category: 'database',
...metadata,
});
}
/**
* Log migration events
* @param {string} migrationName - Migration name
* @param {string} status - Migration status
* @param {object} metadata - Additional metadata
*/
function logMigration(migrationName, status, metadata = {}) {
const logLevel = status === 'failed' ? 'error' : 'info';
logger[logLevel](`Migration: ${status}`, {
migrationName,
status,
category: 'migration',
...metadata,
});
}
/**
* Format error with stack trace and context
* @param {Error} error - Error object
* @param {object} context - Additional context
*/
function formatError(error, context = {}) {
return {
message: error.message,
name: error.name,
stack: error.stack,
code: error.code,
...context,
};
}
// Export utilities
module.exports = {
logger,
createLoggerContext,
requestTracingMiddleware,
logWalletOperation,
logContractInteraction,
logAuthEvent,
logPayment,
logFraudDetection,
logVideoProcessing,
logDatabaseOperation,
logMigration,
formatError,
};