-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlogger.py
More file actions
163 lines (129 loc) · 4.56 KB
/
logger.py
File metadata and controls
163 lines (129 loc) · 4.56 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
"""
Logging Module
Structured logging system with file rotation and different log levels.
"""
import logging
import os
from logging.handlers import RotatingFileHandler
from typing import Optional
from datetime import datetime
import config
class TradingLogger:
"""
Custom logger for the trading platform.
Provides separate loggers for different components.
"""
_instances = {}
def __init__(self, name: str, log_file: Optional[str] = None):
"""
Initialize logger.
Args:
name: Logger name
log_file: Optional log file path
"""
self.name = name
self.log_file = log_file or config.LOG_FILE
self.logger = self._setup_logger()
def _setup_logger(self) -> logging.Logger:
"""
Setup logger with file and console handlers.
Returns:
Configured logger instance
"""
# Create logger
logger = logging.getLogger(self.name)
logger.setLevel(logging.DEBUG)
# Avoid adding handlers multiple times
if logger.handlers:
return logger
# Ensure log directory exists
config.ensure_directories()
# File handler with rotation
file_handler = RotatingFileHandler(
self.log_file,
maxBytes=config.LOG_MAX_BYTES,
backupCount=config.LOG_BACKUP_COUNT
)
file_handler.setLevel(logging.DEBUG)
# Console handler
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.INFO)
# Formatter
formatter = logging.Formatter(
config.LOG_FORMAT,
datefmt=config.LOG_DATE_FORMAT
)
file_handler.setFormatter(formatter)
console_handler.setFormatter(formatter)
# Add handlers
logger.addHandler(file_handler)
logger.addHandler(console_handler)
return logger
@classmethod
def get_logger(cls, name: str, log_file: Optional[str] = None) -> 'TradingLogger':
"""
Get or create logger instance.
Args:
name: Logger name
log_file: Optional log file path
Returns:
TradingLogger instance
"""
if name not in cls._instances:
cls._instances[name] = cls(name, log_file)
return cls._instances[name]
def debug(self, msg: str, **kwargs):
"""Log debug message."""
self.logger.debug(msg, **kwargs)
def info(self, msg: str, **kwargs):
"""Log info message."""
self.logger.info(msg, **kwargs)
def warning(self, msg: str, **kwargs):
"""Log warning message."""
self.logger.warning(msg, **kwargs)
def error(self, msg: str, **kwargs):
"""Log error message."""
self.logger.error(msg, **kwargs)
def critical(self, msg: str, **kwargs):
"""Log critical message."""
self.logger.critical(msg, **kwargs)
def trade(self, action: str, symbol: str, quantity: int, price: float, **kwargs):
"""
Log trade execution.
Args:
action: Trade action (BUY/SELL)
symbol: Stock symbol
quantity: Quantity
price: Execution price
"""
msg = f"TRADE - {action} {quantity} {symbol} @ ${price:.2f}"
if kwargs:
msg += f" | {kwargs}"
self.logger.info(msg)
def performance(self, metric: str, value: float, **kwargs):
"""
Log performance metric.
Args:
metric: Metric name
value: Metric value
"""
msg = f"PERFORMANCE - {metric}: {value}"
if kwargs:
msg += f" | {kwargs}"
self.logger.info(msg)
def security(self, event: str, details: str = ""):
"""
Log security event.
Args:
event: Security event type
details: Event details
"""
msg = f"SECURITY - {event}"
if details:
msg += f": {details}"
self.logger.warning(msg)
# Pre-configured loggers for different components
system_logger = TradingLogger.get_logger('system')
trading_logger = TradingLogger.get_logger('trading', os.path.join(config.LOG_DIR, 'trading.log'))
security_logger = TradingLogger.get_logger('security', os.path.join(config.LOG_DIR, 'security.log'))
performance_logger = TradingLogger.get_logger('performance', os.path.join(config.LOG_DIR, 'performance.log'))