Difficult-Rocket/libs/msdnicrosoft_logger/shenjack.py

83 lines
2.3 KiB
Python
Raw Normal View History

2022-06-27 14:42:26 +08:00
import atexit
2022-06-27 16:22:40 +08:00
import threading
2022-06-27 14:42:26 +08:00
from time import strftime
from typing import Optional
2022-06-29 13:45:25 +08:00
from Difficult_Rocket.exception import
2022-06-27 16:51:14 +08:00
2022-06-27 14:42:26 +08:00
color_reset_suffix = "\033[0m"
class LogFileCache:
"""日志文件缓存"""
def __init__(self, file_name: str = 'logs//log.log', flush_time: Optional[int, float] = 1, cache_entries_num: int = 10):
# 配置相关
2022-06-27 16:51:14 +08:00
self._logfile_name = file_name # log 文件名称
2022-06-27 14:42:26 +08:00
self.flush_time = flush_time # 缓存刷新时长
self.cache_entries_num = cache_entries_num
# 写入缓存数
self.cache_count = 0
2022-06-27 16:22:40 +08:00
# 日志缓存表
2022-06-29 13:45:25 +08:00
self.logs_cache = []
2022-06-27 16:22:40 +08:00
# 同步锁
2022-06-27 16:51:14 +08:00
self.thread_lock = threading.Lock()
@property
def logfile_name(self) -> str:
return self._logfile_name
2022-06-27 14:42:26 +08:00
2022-06-27 16:51:14 +08:00
@logfile_name.setter
def logfile_name(self, value: str) -> None:
2022-06-29 13:45:25 +08:00
with self.thread_lock.acquire(timeout=1/60):
...
2022-06-27 16:51:14 +08:00
self.thread_lock.acquire(timeout=1/60)
if not self.thread_lock.locked():
...
2022-06-27 14:42:26 +08:00
def _log_file_time_write(self) -> None:
"""使用 threading.Timer 调用的定时写入日志文件的函数"""
if self.cache_count == 0:
return None
...
2022-06-29 13:45:25 +08:00
def write_logs(self, string: str, wait_for_cache: bool = True) -> None:
2022-06-27 16:22:40 +08:00
if wait_for_cache:
2022-06-27 16:51:14 +08:00
with open(file=self.logfile_name, encoding='utf-8', mode='a') as log_file:
2022-06-29 13:45:25 +08:00
log_file.writelines(self.logs_cache)
2022-06-27 16:22:40 +08:00
log_file.write(string)
...
2022-06-27 14:42:26 +08:00
else:
...
class Logger:
"""shenjack logger"""
def __init__(self, config: dict = None) -> None:
if config is None:
self.config = {}
else:
self.config = config
2022-06-29 13:45:25 +08:00
class LoggerManager:
2022-06-27 14:42:26 +08:00
"""shenjack牌logger"""
def __init__(self):
self.configs = {}
def add_config(self, name: str, config: dict) -> dict:
self.configs[name] = config
return self.configs
2022-06-29 13:45:25 +08:00
def get_logger(self, name: str = 'root', config: dict = None) -> Logger:
"""相当于 logging.getLogger(name='root')"""
if not config is None:
self.add_config(name, config)
2022-06-27 14:42:26 +08:00
return Logger(config=self.configs)
2022-06-29 13:45:25 +08:00
logger_manager = LoggerManager()
get_logger = logger_manager.get_logger
# shenjack.get_logger()