sqllineage/utils/log.py

69 lines
2.0 KiB
Python
Raw Normal View History

2025-02-05 14:18:02 +08:00
import logging
import os
from datetime import datetime
# 定义全局变量 log_path
cur_path = os.path.dirname(os.path.realpath(__file__))
log_path = os.path.join(os.path.dirname(cur_path), 'logs')
class Log():
def __init__(self, logger_name='my_logger'):
self.logger = logging.getLogger(logger_name)
if self.logger.hasHandlers():
self.logger.handlers.clear()
self.logger.setLevel(logging.INFO)
if not os.path.exists(log_path):
os.makedirs(log_path)
self.update_log_file()
def update_log_file(self):
current_date = datetime.now().strftime("%Y_%m_%d")
self.log_name = os.path.join(log_path, f'{current_date}.log')
for handler in self.logger.handlers[:]:
self.logger.removeHandler(handler)
fh = logging.FileHandler(self.log_name, 'a', encoding='utf-8')
fh.setLevel(logging.INFO)
ch = logging.StreamHandler()
ch.setLevel(logging.INFO)
2025-02-05 16:16:44 +08:00
formatter = logging.Formatter(
'[%(asctime)s] %(filename)s line:%(lineno)d [%(levelname)s]%(message)s',
datefmt="%Y-%m-%d %H:%M:%S"
)
2025-02-05 14:18:02 +08:00
fh.setFormatter(formatter)
ch.setFormatter(formatter)
self.logger.addHandler(fh)
self.logger.addHandler(ch)
def getlog(self):
2025-02-05 16:16:44 +08:00
current_date = datetime.now().strftime("%Y_%m_%d")
2025-02-05 14:18:02 +08:00
log_date = os.path.basename(self.log_name).split('.')[0]
2025-02-05 16:16:44 +08:00
if current_date != log_date:
2025-02-05 14:18:02 +08:00
self.update_log_file()
return self.logger
def info(self, msg, *args, **kwargs):
logger = self.getlog()
logger.info(msg, *args, **kwargs)
2025-02-05 16:16:44 +08:00
def error(self, msg, *args, **kwargs):
logger = self.getlog()
logger.error(msg, *args, **kwargs)
def warning(self, msg, *args, **kwargs):
logger = self.getlog()
logger.warning(msg, *args, **kwargs)
2025-02-05 14:18:02 +08:00
if __name__ == "__main__":
2025-02-05 16:16:44 +08:00
log = Log()
2025-02-05 14:18:02 +08:00
log.info("---测试开始----")
log.error("操作步骤1,2,3")
2025-02-05 16:16:44 +08:00
log.warning("----测试结束----")