Difficult-Rocket/libs/lib_not_dr/logger/logger.py

101 lines
3.1 KiB
Python
Raw Normal View History

2023-10-13 23:04:32 +08:00
# -------------------------------
# Difficult Rocket
# Copyright © 2020-2023 by shenjackyuanjie 3695888@qq.com
# All rights reserved
# -------------------------------
2023-10-13 23:07:08 +08:00
2023-10-14 15:36:43 +08:00
import time
import inspect
from types import FrameType
from typing import List, Optional
2023-11-03 16:24:59 +08:00
from lib_not_dr.logger.structers import LogMessage
from lib_not_dr.logger.outstream import BaseOutputStream
2023-10-13 23:07:08 +08:00
from lib_not_dr.types.options import Options
2023-10-14 15:36:43 +08:00
class Logger(Options):
name = 'Logger-v2'
outputs: List[BaseOutputStream] = []
enable: bool = True
level: int = 20
def log_for(self, level: int) -> bool:
"""
Check if logging is enabled for a specific level.
Args:
level (int): The logging level to check.
Returns:
bool: True if logging is enabled for the given level, False otherwise.
"""
return self.enable and level >= self.level
def add_output(self, output: BaseOutputStream) -> None:
"""
Add an output to the list of outputs.
Args:
output (BaseOutputStream): The output to be added.
Returns:
None
"""
self.outputs.append(output)
self.level = min(self.level, output.level)
def remove_output(self, output: BaseOutputStream) -> None:
"""
Removes the specified output from the list of outputs.
Args:
output (BaseOutputStream): The output to be removed.
Returns:
None
"""
self.outputs.remove(output)
self.level = max(self.level, *[output.level for output in self.outputs])
def make_log(self,
messages: List[str],
end: str = '\n',
split: str = ' ',
flush: bool = True,
level: int = 20,
2023-10-14 20:02:42 +08:00
log_time: Optional[float] = None,
2023-10-14 15:36:43 +08:00
logger_name: str = 'root',
logger_tag: Optional[str] = None,
stack_trace: Optional[FrameType] = None) -> None:
2023-10-14 20:02:42 +08:00
# 检查是否需要记录
2023-10-14 15:36:43 +08:00
if not self.log_for(level):
return
2023-10-14 20:02:42 +08:00
# 处理时间
if log_time is None:
log_time = time.time_ns()
# 处理堆栈信息
2023-10-14 15:36:43 +08:00
if stack_trace is None:
2023-10-14 20:02:42 +08:00
# 尝试获取堆栈信息
2023-10-14 15:36:43 +08:00
if (stack := inspect.currentframe()) is not None:
2023-10-14 20:02:42 +08:00
# 如果可能 尝试获取上两层的堆栈信息
2023-10-14 15:36:43 +08:00
if (up_stack := stack.f_back) is not None:
2023-10-14 20:02:42 +08:00
if (upper_stack := up_stack.f_back) is not None:
stack_trace = upper_stack
else:
stack_trace = up_stack
2023-10-14 15:36:43 +08:00
else:
stack_trace = stack
message = LogMessage(messages=messages,
end=end,
split=split,
flush=flush,
level=level,
2023-10-14 20:02:42 +08:00
log_time=log_time,
2023-10-14 15:36:43 +08:00
logger_name=logger_name,
logger_tag=logger_tag,
stack_trace=stack_trace)