104 lines
3.0 KiB
Python
104 lines
3.0 KiB
Python
#!/usr/bin/env python3
|
|
# -*- coding:utf-8 -*-
|
|
import logging
|
|
import logging.handlers
|
|
import sys
|
|
import os
|
|
import colorlog
|
|
|
|
class logs():
|
|
def __init__(self):
|
|
self.logger = logging.getLogger()
|
|
self.fatal = self.critical
|
|
|
|
def setConfig(self, conf):
|
|
name = conf['name'] # 是否开启日志
|
|
enable = conf['enable'] # 是否开启日志
|
|
console = conf['console'] # 是否输出到控制台
|
|
journal = conf['journal'] # 是否输出到文件
|
|
logPath = conf['logpath'] # 日志文件路径
|
|
level = conf['level'] # 日志级别
|
|
when = conf['when'] # 日志文件时间间隔
|
|
backupCount = conf['backupcount'] # 日志文件周期
|
|
|
|
if not logPath:
|
|
logPath = os.path.join(os.path.dirname(__file__), 'logFile')
|
|
|
|
os.makedirs(logPath, 0o755, True)
|
|
|
|
formatter = colorlog.ColoredFormatter(
|
|
fmt='{log_color}[{asctime}]|{levelname}{message}',
|
|
datefmt='%m-%d %H:%M:%S',
|
|
style='{'
|
|
)
|
|
|
|
self.logger.setLevel(level)
|
|
|
|
if enable:
|
|
# 输出到控制台
|
|
if console:
|
|
sh = logging.StreamHandler(sys.stdout)
|
|
sh.setLevel(level)
|
|
sh.setFormatter(formatter)
|
|
self.logger.addHandler(sh)
|
|
|
|
# 输出到文件
|
|
if journal:
|
|
th = logging.handlers.TimedRotatingFileHandler(
|
|
filename=os.path.join(logPath, name),
|
|
when=when,
|
|
backupCount=backupCount,
|
|
encoding='utf-8'
|
|
)
|
|
th.setFormatter(formatter)
|
|
self.logger.addHandler(th)
|
|
|
|
def join(func):
|
|
def s(self, *args, **kwargs):
|
|
back_frame = sys._getframe().f_back
|
|
back_filename = os.path.basename(back_frame.f_code.co_filename)
|
|
# back_funcname = back_frame.f_code.co_name
|
|
back_lineno = back_frame.f_lineno
|
|
# _args = f'[{back_filename} - {back_funcname} - {back_lineno}]'
|
|
_args = f'[{back_filename}:{back_lineno}]'
|
|
n = '-' * (10 - len(func.__name__))
|
|
_args = f'{n}{_args}'
|
|
n = ' ' * (40 - len(func.__name__ + _args))
|
|
_args = f'{_args}{n}: '
|
|
for i in args:
|
|
_args = _args + str(i)
|
|
result = func(self, _args, **kwargs)
|
|
return result
|
|
return s
|
|
|
|
@join
|
|
def debug(self, msg):
|
|
self.logger.debug(msg)
|
|
|
|
@join
|
|
def info(self, msg):
|
|
self.logger.info(msg)
|
|
|
|
@join
|
|
def warning(self, msg):
|
|
self.logger.warning(msg)
|
|
|
|
@join
|
|
def error(self, msg):
|
|
self.logger.error(msg)
|
|
|
|
@join
|
|
def fatal(self, msg):
|
|
self.logger.fatal(msg)
|
|
|
|
@join
|
|
def critical(self, msg):
|
|
self.logger.critical(msg)
|
|
|
|
log = logs()
|
|
# DEBUG = 10
|
|
# INFO = 20
|
|
# WARNING = 30
|
|
# ERROR = 40
|
|
# FATAL = 50
|