-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlogger.py
103 lines (73 loc) · 2.92 KB
/
logger.py
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
import logging
import sys
from logging.handlers import RotatingFileHandler, TimedRotatingFileHandler
import json
from datetime import datetime
import os
class CustomJsonFormatter(logging.Formatter):
def format(self, record):
log_record = {
"timestamp": datetime.utcnow().isoformat(),
"level": record.levelname,
"message": record.getMessage(),
}
if record.levelno >= logging.WARNING:
log_record.update(
{
"module": record.module,
"function": record.funcName,
"line": record.lineno,
}
)
if record.exc_info:
log_record["exception"] = self.formatException(record.exc_info)
return json.dumps(log_record)
def setup_logger(name, log_file="bot.log", level=logging.INFO):
logger = logging.getLogger(name)
# Clear any existing handlers to prevent duplicate logging
if logger.hasHandlers():
logger.handlers.clear()
logger.setLevel(level)
# Console handler
console_handler = logging.StreamHandler(sys.stdout)
console_handler.setFormatter(CustomJsonFormatter())
logger.addHandler(console_handler)
# File handler with rotation
file_handler = TimedRotatingFileHandler(log_file, when="midnight", interval=1, backupCount=7, encoding="utf-8")
file_handler.setFormatter(CustomJsonFormatter())
logger.addHandler(file_handler)
# Prevent propagation to avoid duplicate logs
logger.propagate = False
return logger
# Create a global logger instance
logger = setup_logger("twitch_bot")
def log_command(command_name, user, channel):
"""Utility function to log command usage."""
logger.info(f"Command '{command_name}' used", extra={"user": user, "channel": channel, "command": command_name})
def log_error(error_message, exc_info=False, **kwargs):
"""Utility function to log errors."""
logger.error(error_message, exc_info=exc_info, extra=kwargs)
def log_info(message, **kwargs):
"""Utility function to log info messages."""
logger.info(message, extra=kwargs)
def log_warning(message, **kwargs):
"""Utility function to log warning messages."""
logger.warning(message, extra=kwargs)
def log_debug(message, **kwargs):
"""Utility function to log debug messages."""
logger.debug(message, extra=kwargs)
def log_critical(message, **kwargs):
"""Utility function to log critical messages."""
logger.critical(message, extra=kwargs)
def get_logger(name):
"""Get a named logger."""
return logging.getLogger(name)
# Environment-based logging level
log_level = os.getenv("LOG_LEVEL", "INFO").upper()
logging.basicConfig(level=getattr(logging, log_level))
# Function to change log level dynamically
def set_log_level(level):
logger.setLevel(level)
for handler in logger.handlers:
handler.setLevel(level)
log_info(f"Log level changed to {level}")