forked from locaal-ai/scoresight
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sc_logging.py
62 lines (51 loc) · 1.85 KB
/
sc_logging.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
import logging
import os
from platformdirs import user_log_dir
from datetime import datetime
from dotenv import load_dotenv
# Load the environment variables from the .env file
load_dotenv(os.path.abspath(os.path.join(os.path.dirname(__file__), ".env")))
# Create a logger
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
# get the user data directory
data_dir = user_log_dir("scoresight")
if not os.path.exists(data_dir):
os.makedirs(data_dir)
current_time = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
# basic config - send all logs to a file
logging.basicConfig(
filename=os.path.join(data_dir, f"scoresight_std_{current_time}.log"),
level=logging.INFO,
)
# prepend the user data directory
log_file_path = os.path.join(data_dir, f"scoresight_{current_time}.log")
# Create a file handler
file_handler = logging.FileHandler(log_file_path)
file_handler.setLevel(logging.DEBUG)
# Create a formatter
formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(module)s - %(message)s")
file_handler.setFormatter(formatter)
# Add the file handler to the logger
logger.addHandler(file_handler)
# if the .env file has a debug flag, set the logger to output to console
if os.getenv("SCORESIGHT_DEBUG"):
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.DEBUG)
console_handler.setFormatter(formatter)
logger.addHandler(console_handler)
logger.debug("Debug mode enabled")
# check to see if there are more log files, and only keep the most recent 10
log_files = [
f
for f in os.listdir(data_dir)
if f.startswith("scoresight_") and f.endswith(".log")
]
# sort log files by date
log_files.sort()
if len(log_files) > 10:
for f in log_files[:-10]:
try:
os.remove(os.path.join(data_dir, f))
except PermissionError as e:
logger.error(f"Failed to remove log file: {f}")