log_utils.py
import os
import sys
from time import strftime, localtime
from loguru import logger
class LogUtils:
log_file_root_path = ""
@classmethod
def init_logger(cls, name, console_level='DEBUG', write_level='INFO'):
console_log_level_list = ['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL']
if console_level.upper() not in console_log_level_list:
raise Exception(f'控制台log设置的等级不存在,控制台log等级为:{console_log_level_list}')
write_log_level_list = ['DEBUG', 'INFO', 'WARNING']
if write_level.upper() not in write_log_level_list:
raise Exception(f'写入log设置的等级不存在,写入log等级为:{write_log_level_list}')
base_path, file_name = os.path.split(os.path.abspath(sys.argv[0]))
current_year_month_day = strftime('%Y%m%d', localtime())
current_hour_minute_second = strftime('%H%M%S', localtime())
log_base_path = os.path.join(base_path, f'logs/{current_year_month_day}')
if not os.path.exists(log_base_path):
os.makedirs(log_base_path)
cls.log_file_root_path = os.path.join(log_base_path,
f'{name}_{current_year_month_day}_{current_hour_minute_second}')
error_log_file_path = f'{cls.log_file_root_path}_error'
critical_log_file_path = f'{cls.log_file_root_path}_critical'
logger.remove()
logger.level('DEBUG', color='<blue>')
logger.level('INFO', color='<green>')
logger.level('WARNING', color='<yellow>')
logger.level('ERROR', color='<red>')
logger.level('CRITICAL', color='<magenta>')
logger.add(
sink=sys.stderr,
format='<level>{time:YYYY-MM-DD HH:mm:ss.SSS} [{level}] {message}(in: {file} line: {line})</level>',
level=console_level,
colorize=True,
)
logger.add(
sink=f'{cls.log_file_root_path}.log',
format='{time:YYYY-MM-DD HH:mm:ss.SSS} [{level}] {message}(in: {file} line: {line})',
rotation='50 MB',
filter=lambda x: x['level'].name in write_log_level_list,
encoding='utf-8',
compression='zip',
level=write_level,
enqueue=True,
)
logger.add(
sink=f'{error_log_file_path}.log',
format='{time:YYYY-MM-DD HH:mm:ss.SSS} [{level}] {message}(in: {file} line: {line})',
rotation='10 MB',
filter=lambda x: x['level'].name == 'ERROR',
encoding='utf-8',
level='ERROR',
enqueue=True,
)
logger.add(
sink=f'{critical_log_file_path}.log',
format='{time:YYYY-MM-DD HH:mm:ss.SSS} [{level}] {message}(in: {file} line: {line})',
rotation='10 MB',
filter=lambda x: x['level'].name == 'CRITICAL',
encoding='utf-8',
level='CRITICAL',
enqueue=True,
)
@classmethod
def get_logger(cls, name="default"):
new_log_file_path = f'{cls.log_file_root_path}_{name}'
new_logger = logger.bind(type=name)
new_logger.add(
sink=f'{new_log_file_path}.log',
format='{time:YYYY-MM-DD HH:mm:ss.SSS} [{level}] {message}(in: {file} line: {line})',
rotation='10 MB',
filter=lambda record: record.get("extra", dict()).get("type", "") == name,
encoding='utf-8',
enqueue=True,
compression='zip',
)
return new_logger
test_log.py
from loguru import logger
from log_utils import LogUtils
LogUtils.init_logger("zby")
chat1_logger = LogUtils.get_logger("chat1")
chat2_logger = LogUtils.get_logger("chat2")
chat1_logger.info("Hello World11111111")
chat2_logger.info("Hello World22222222")
@logger.catch
def test_log():
logger.debug(1111111)
logger.info(222222)
logger.warning(333333)
logger.error(444444)
logger.critical(555555)
1 / 0
if __name__ == '__main__':
test_log()