-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlogging.py
More file actions
376 lines (302 loc) · 12.1 KB
/
Copy pathlogging.py
File metadata and controls
376 lines (302 loc) · 12.1 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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
"""
Structured Logging - Professional logging with multiple output modes.
This module provides comprehensive logging functionality:
- JSON mode for SIEM integration
- Human-readable mode for terminal output
- Quiet mode (errors only)
- Verbose mode (debug information)
- File logging support
"""
import sys
import json
import logging
from pathlib import Path
from typing import Optional, Dict, Any
from datetime import datetime
from enum import Enum
class LogLevel(Enum):
"""Log levels."""
DEBUG = 'debug'
INFO = 'info'
WARNING = 'warning'
ERROR = 'error'
class StructuredLogger:
"""Structured logger with multiple output modes."""
def __init__(
self,
level: str = 'info',
json_mode: bool = False,
quiet: bool = False,
verbose: bool = False,
log_file: Optional[Path] = None
):
"""
Initialize structured logger.
Args:
level: Log level (debug, info, warning, error)
json_mode: Output in JSON format for SIEM
quiet: Suppress all output except errors
verbose: Enable verbose output (sets level to debug)
log_file: Optional file to write logs to
"""
self.json_mode = json_mode
self.quiet = quiet
self.verbose = verbose
self.log_file = log_file
if verbose:
self.level = LogLevel.DEBUG
elif quiet:
self.level = LogLevel.ERROR
else:
self.level = LogLevel[level.upper()]
self.logger = self._setup_logger()
def _setup_logger(self) -> logging.Logger:
"""Setup Python logging."""
logger = logging.getLogger('jenkins-decrypt')
logger.setLevel(logging.DEBUG)
logger.handlers.clear()
if self.log_file:
file_handler = logging.FileHandler(self.log_file)
file_handler.setLevel(logging.DEBUG)
if self.json_mode:
file_handler.setFormatter(JSONFormatter())
else:
file_handler.setFormatter(HumanFormatter())
logger.addHandler(file_handler)
console_handler = logging.StreamHandler(sys.stderr)
console_handler.setLevel(self._get_logging_level())
if self.json_mode:
console_handler.setFormatter(JSONFormatter())
else:
console_handler.setFormatter(HumanFormatter())
logger.addHandler(console_handler)
return logger
def _get_logging_level(self) -> int:
"""Convert log level to logging constant."""
mapping = {
LogLevel.DEBUG: logging.DEBUG,
LogLevel.INFO: logging.INFO,
LogLevel.WARNING: logging.WARNING,
LogLevel.ERROR: logging.ERROR
}
return mapping.get(self.level, logging.INFO)
def debug(self, message: str, **kwargs: Any) -> None:
"""Log debug message."""
self._log(LogLevel.DEBUG, message, **kwargs)
def info(self, message: str, **kwargs: Any) -> None:
"""Log info message."""
self._log(LogLevel.INFO, message, **kwargs)
def warning(self, message: str, **kwargs: Any) -> None:
"""Log warning message."""
self._log(LogLevel.WARNING, message, **kwargs)
def error(self, message: str, **kwargs: Any) -> None:
"""Log error message."""
self._log(LogLevel.ERROR, message, **kwargs)
def _log(self, level: LogLevel, message: str, **kwargs: Any) -> None:
"""Internal logging method."""
if self.quiet and level != LogLevel.ERROR:
return
if self.json_mode:
self._log_json(level, message, **kwargs)
else:
self._log_human(level, message, **kwargs)
def _log_json(self, level: LogLevel, message: str, **kwargs: Any) -> None:
"""Log in JSON format."""
log_entry = {
'timestamp': datetime.utcnow().isoformat() + 'Z',
'level': level.value,
'message': message,
'application': 'jenkins-credential-decryptor',
'version': '3.0.0'
}
if kwargs:
log_entry['context'] = kwargs
mapping = {
LogLevel.DEBUG: logging.DEBUG,
LogLevel.INFO: logging.INFO,
LogLevel.WARNING: logging.WARNING,
LogLevel.ERROR: logging.ERROR
}
self.logger.log(mapping[level], json.dumps(log_entry))
def _log_human(self, level: LogLevel, message: str, **kwargs: Any) -> None:
"""Log in human-readable format."""
prefix_map = {
LogLevel.DEBUG: '[DEBUG]',
LogLevel.INFO: '[*]',
LogLevel.WARNING: '[!]',
LogLevel.ERROR: '[-]'
}
prefix = prefix_map.get(level, '[*]')
log_message = f"{prefix} {message}"
if kwargs and self.verbose:
context_str = ' '.join(f"{k}={v}" for k, v in kwargs.items())
log_message += f" ({context_str})"
mapping = {
LogLevel.DEBUG: logging.DEBUG,
LogLevel.INFO: logging.INFO,
LogLevel.WARNING: logging.WARNING,
LogLevel.ERROR: logging.ERROR
}
self.logger.log(mapping[level], log_message)
def success(self, message: str, **kwargs: Any) -> None:
"""Log success message (info with [+] prefix)."""
if self.json_mode:
self._log_json(LogLevel.INFO, message, status='success', **kwargs)
else:
prefix = '[+]'
log_message = f"{prefix} {message}"
if kwargs and self.verbose:
context_str = ' '.join(f"{k}={v}" for k, v in kwargs.items())
log_message += f" ({context_str})"
self.logger.info(log_message)
def progress(self, message: str, current: int, total: int, **kwargs: Any) -> None:
"""Log progress message."""
percentage = (current / total * 100) if total > 0 else 0
if self.json_mode:
self._log_json(
LogLevel.INFO,
message,
progress=percentage,
current=current,
total=total,
**kwargs
)
else:
log_message = f"[*] {message} [{current}/{total}] ({percentage:.1f}%)"
self.logger.info(log_message)
def metric(self, name: str, value: Any, unit: Optional[str] = None, **kwargs: Any) -> None:
"""Log metric for monitoring."""
if self.json_mode:
log_entry = {
'timestamp': datetime.utcnow().isoformat() + 'Z',
'type': 'metric',
'metric_name': name,
'metric_value': value,
'application': 'jenkins-credential-decryptor'
}
if unit:
log_entry['unit'] = unit
if kwargs:
log_entry.update(kwargs)
self.logger.info(json.dumps(log_entry))
elif self.verbose:
unit_str = f" {unit}" if unit else ""
self.logger.debug(f"[METRIC] {name}: {value}{unit_str}")
class JSONFormatter(logging.Formatter):
"""JSON log formatter for structured logging."""
def format(self, record: logging.LogRecord) -> str:
"""Format log record as JSON."""
try:
return record.getMessage()
except Exception:
log_entry = {
'timestamp': datetime.utcnow().isoformat() + 'Z',
'level': record.levelname.lower(),
'message': record.getMessage(),
'application': 'jenkins-credential-decryptor'
}
return json.dumps(log_entry)
class HumanFormatter(logging.Formatter):
"""Human-readable log formatter."""
def format(self, record: logging.LogRecord) -> str:
"""Format log record as human-readable text."""
return record.getMessage()
class AuditLogger:
"""Audit logger for forensic operations."""
def __init__(self, audit_file: Path):
"""
Initialize audit logger.
Args:
audit_file: Path to audit log file
"""
self.audit_file = audit_file
self.audit_file.parent.mkdir(parents=True, exist_ok=True)
def log_access(self, file_path: Path, operation: str, **kwargs: Any) -> None:
"""Log file access for audit trail."""
entry = {
'timestamp': datetime.utcnow().isoformat() + 'Z',
'type': 'file_access',
'file': str(file_path),
'operation': operation
}
entry.update(kwargs)
self._write_entry(entry)
def log_decryption(self, secret_count: int, source: str, **kwargs: Any) -> None:
"""Log decryption operation."""
entry = {
'timestamp': datetime.utcnow().isoformat() + 'Z',
'type': 'decryption',
'secret_count': secret_count,
'source': source
}
entry.update(kwargs)
self._write_entry(entry)
def log_export(self, format: str, destination: Path, record_count: int, **kwargs: Any) -> None:
"""Log export operation."""
entry = {
'timestamp': datetime.utcnow().isoformat() + 'Z',
'type': 'export',
'format': format,
'destination': str(destination),
'record_count': record_count
}
entry.update(kwargs)
self._write_entry(entry)
def _write_entry(self, entry: Dict[str, Any]) -> None:
"""Write audit entry to file."""
with open(self.audit_file, 'a') as f:
f.write(json.dumps(entry) + '\n')
class ProgressLogger:
"""Progress logger with ETA estimation."""
def __init__(self, logger: StructuredLogger, total: int, description: str = "Processing"):
"""
Initialize progress logger.
Args:
logger: StructuredLogger instance
total: Total number of items
description: Progress description
"""
self.logger = logger
self.total = total
self.description = description
self.current = 0
self.start_time = datetime.utcnow()
def update(self, increment: int = 1) -> None:
"""Update progress."""
self.current += increment
if self.current % max(1, self.total // 20) == 0 or self.current == self.total:
elapsed = (datetime.utcnow() - self.start_time).total_seconds()
if self.current > 0:
eta = (elapsed / self.current) * (self.total - self.current)
self.logger.progress(
self.description,
self.current,
self.total,
eta_seconds=int(eta)
)
else:
self.logger.progress(self.description, self.current, self.total)
def finish(self) -> None:
"""Mark progress as finished."""
elapsed = (datetime.utcnow() - self.start_time).total_seconds()
self.logger.success(
f"{self.description} completed",
total=self.total,
elapsed_seconds=elapsed
)
if __name__ == '__main__':
logger = StructuredLogger(level='debug', json_mode=False, verbose=True)
logger.debug("Debug message", context="test")
logger.info("Info message")
logger.warning("Warning message")
logger.error("Error message")
logger.success("Operation completed successfully")
logger.progress("Processing files", 50, 100)
logger.metric("secrets_found", 42, "count")
print("\nJSON mode:")
json_logger = StructuredLogger(level='info', json_mode=True)
json_logger.info("Test message", user="admin", action="decrypt")
print("\nQuiet mode:")
quiet_logger = StructuredLogger(quiet=True)
quiet_logger.info("This should not appear")
quiet_logger.error("Only errors appear in quiet mode")