ciyidogan commited on
Commit
0e7f4f9
·
verified ·
1 Parent(s): 6856d8d

Delete logger.py

Browse files
Files changed (1) hide show
  1. logger.py +0 -223
logger.py DELETED
@@ -1,223 +0,0 @@
1
- """
2
- Centralized Logging System for Flare Platform
3
- """
4
- import sys
5
- import logging
6
- import json
7
- import os
8
- import threading
9
- import traceback
10
- from datetime import datetime
11
- from enum import Enum
12
- from typing import Optional, Dict, Any, Union
13
- from pathlib import Path
14
-
15
- class LogLevel(Enum):
16
- DEBUG = "DEBUG"
17
- INFO = "INFO"
18
- WARNING = "WARNING"
19
- ERROR = "ERROR"
20
- CRITICAL = "CRITICAL"
21
-
22
- class FlareLogger:
23
- _instance = None
24
- _lock = threading.Lock()
25
-
26
- def __new__(cls):
27
- if cls._instance is None:
28
- with cls._lock:
29
- if cls._instance is None:
30
- cls._instance = super().__new__(cls)
31
- cls._instance._initialized = False
32
- return cls._instance
33
-
34
- def __init__(self):
35
- if self._initialized:
36
- return
37
-
38
- self._initialized = True
39
-
40
- # Log level from environment
41
- self.log_level = LogLevel[os.getenv('LOG_LEVEL', 'INFO')]
42
-
43
- # Configure Python logging
44
- self.logger = logging.getLogger('flare')
45
- self.logger.setLevel(self.log_level.value)
46
-
47
- # Remove default handlers
48
- self.logger.handlers = []
49
-
50
- # Console handler with custom format
51
- console_handler = logging.StreamHandler(sys.stdout)
52
- console_handler.setFormatter(self._get_formatter())
53
- self.logger.addHandler(console_handler)
54
-
55
- # File handler for production
56
- if os.getenv('LOG_TO_FILE', 'false').lower() == 'true':
57
- log_dir = Path('logs')
58
- log_dir.mkdir(exist_ok=True)
59
- file_handler = logging.FileHandler(
60
- log_dir / f"flare_{datetime.now().strftime('%Y%m%d')}.log"
61
- )
62
- file_handler.setFormatter(self._get_formatter())
63
- self.logger.addHandler(file_handler)
64
-
65
- # Future: Add ElasticSearch handler here
66
- # if os.getenv('ELASTICSEARCH_URL'):
67
- # from elasticsearch_handler import ElasticsearchHandler
68
- # es_handler = ElasticsearchHandler(
69
- # hosts=[os.getenv('ELASTICSEARCH_URL')],
70
- # index='flare-logs'
71
- # )
72
- # self.logger.addHandler(es_handler)
73
-
74
- def _get_formatter(self):
75
- return logging.Formatter(
76
- '[%(asctime)s.%(msecs)03d] [%(levelname)s] [%(name)s] %(message)s',
77
- datefmt='%H:%M:%S'
78
- )
79
-
80
- def log(self, level: LogLevel, message: str, **kwargs):
81
- """Central logging method with structured data"""
82
- # Add context data
83
- extra_data = {
84
- 'timestamp': datetime.utcnow().isoformat(),
85
- 'service': 'flare',
86
- 'thread_id': threading.get_ident(),
87
- **kwargs
88
- }
89
-
90
- # Log with structured data
91
- log_message = message
92
- if kwargs:
93
- # Format kwargs for readability
94
- kwargs_str = json.dumps(kwargs, ensure_ascii=False, default=str)
95
- log_message = f"{message} | {kwargs_str}"
96
-
97
- getattr(self.logger, level.value.lower())(log_message, extra={'data': extra_data})
98
-
99
- # Always flush for real-time debugging
100
- sys.stdout.flush()
101
-
102
- def debug(self, message: str, **kwargs):
103
- """Log debug message"""
104
- self.log(LogLevel.DEBUG, message, **kwargs)
105
-
106
- def info(self, message: str, **kwargs):
107
- """Log info message"""
108
- self.log(LogLevel.INFO, message, **kwargs)
109
-
110
- def warning(self, message: str, **kwargs):
111
- """Log warning message"""
112
- self.log(LogLevel.WARNING, message, **kwargs)
113
-
114
- def error(self, message: str, **kwargs):
115
- """Log error message"""
116
- self.log(LogLevel.ERROR, message, **kwargs)
117
-
118
- def critical(self, message: str, **kwargs):
119
- """Log critical message"""
120
- self.log(LogLevel.CRITICAL, message, **kwargs)
121
-
122
- def set_level(self, level: str):
123
- """Dynamically change log level"""
124
- try:
125
- self.log_level = LogLevel[level.upper()]
126
- self.logger.setLevel(self.log_level.value)
127
- self.info(f"Log level changed to {level}")
128
- except KeyError:
129
- self.warning(f"Invalid log level: {level}")
130
-
131
- # Global logger instance
132
- logger = FlareLogger()
133
-
134
- # Convenience functions
135
- def log_debug(message: str, **kwargs):
136
- """Log debug message"""
137
- logger.debug(message, **kwargs)
138
-
139
- def log_info(message: str, **kwargs):
140
- """Log info message"""
141
- logger.info(message, **kwargs)
142
-
143
- def log_warning(message: str, **kwargs):
144
- """Log warning message"""
145
- logger.warning(message, **kwargs)
146
-
147
- def log_error(message: str, exception: Optional[Exception] = None, **kwargs):
148
- """
149
- Log error message with optional exception
150
-
151
- Usage:
152
- log_error("Error occurred")
153
- log_error("Error occurred", e) # Otomatik olarak str(e) ve traceback ekler
154
- log_error("Error occurred", error="custom error")
155
- log_error("Error occurred", e, extra_field="value")
156
- """
157
- import traceback
158
-
159
- # Eğer exception parametresi verilmişse, otomatik olarak error ve traceback ekle
160
- if exception is not None:
161
- # Eğer kwargs'da error yoksa, exception'dan al
162
- if 'error' not in kwargs:
163
- kwargs['error'] = str(exception)
164
-
165
- # Exception tipini ekle
166
- if 'error_type' not in kwargs:
167
- kwargs['error_type'] = type(exception).__name__
168
-
169
- # Eğer kwargs'da traceback yoksa ve bu bir Exception ise, traceback ekle
170
- if 'traceback' not in kwargs and isinstance(exception, Exception):
171
- kwargs['traceback'] = traceback.format_exc()
172
-
173
- # Özel exception tipleri için ekstra bilgi
174
- if hasattr(exception, '__dict__'):
175
- # Custom exception'ların attribute'larını ekle
176
- for attr, value in exception.__dict__.items():
177
- if not attr.startswith('_') and attr not in kwargs:
178
- kwargs[f'exc_{attr}'] = value
179
-
180
- # HTTP status code varsa ekle
181
- if hasattr(exception, 'status_code') and 'status_code' not in kwargs:
182
- kwargs['status_code'] = exception.status_code
183
-
184
- # Orijinal logger'a gönder
185
- logger.error(message, **kwargs)
186
-
187
- def log_critical(message: str, **kwargs):
188
- """Log critical message"""
189
- logger.critical(message, **kwargs)
190
-
191
- # Backward compatibility
192
- def log(message: str, level: str = "INFO", **kwargs):
193
- """Legacy log function for compatibility"""
194
- getattr(logger, level.lower())(message, **kwargs)
195
-
196
- # Performance logging helpers
197
- class LogTimer:
198
- """Context manager for timing operations"""
199
- def __init__(self, operation_name: str, **extra_kwargs):
200
- self.operation_name = operation_name
201
- self.extra_kwargs = extra_kwargs
202
- self.start_time = None
203
-
204
- def __enter__(self):
205
- self.start_time = datetime.now()
206
- log_debug(f"Starting {self.operation_name}", **self.extra_kwargs)
207
- return self
208
-
209
- def __exit__(self, exc_type, exc_val, exc_tb):
210
- duration_ms = (datetime.now() - self.start_time).total_seconds() * 1000
211
- if exc_type:
212
- log_error(
213
- f"{self.operation_name} failed after {duration_ms:.2f}ms",
214
- error=str(exc_val),
215
- duration_ms=duration_ms,
216
- **self.extra_kwargs
217
- )
218
- else:
219
- log_info(
220
- f"{self.operation_name} completed in {duration_ms:.2f}ms",
221
- duration_ms=duration_ms,
222
- **self.extra_kwargs
223
- )