import logging
import re
from logging.handlers import TimedRotatingFileHandler

#日志相关
LOG_LEVEL = "DEBUG"
LOG_FILE_NAME = f"/var/log/etc-controller/lane"
LOG_WHEN = "MIDNIGHT"
LOG_INTERVAL = 1
LOG_BACKUP_COUNT = 30
LOG_PRINT_FMT = "%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s"


PARK_ID='6101130020'
LANE = "2"

def Logger(fileName, level=LOG_LEVEL):
    '''
    interval 滚动周期，
    when="MIDNIGHT", interval=1 表示每天0点为更新点，每天生成一个文件
    backupCount  表示日志保存个数
    filename="xxx" suffix设置，会生成文件名为xxx.2020-02-25.log
    extMatch是编译好正则表达式，用于匹配日志文件名后缀
    需要注意的是suffix和extMatch一定要匹配的上，如果不匹配，过期日志不会被删除。
    '''
    logger = logging.getLogger(fileName)
    logger.setLevel(level)
    file_handler = TimedRotatingFileHandler(
        filename=f"{LOG_FILE_NAME}{PARK_ID}{LANE}",
        when=LOG_WHEN,
        interval=LOG_INTERVAL,
        backupCount=LOG_BACKUP_COUNT
    )
    file_handler.suffix = "%Y-%m-%d.log"
    file_handler.extMatch = re.compile(r"^\d{4}-\d{2}-\d{2}.log$")
    file_handler.setFormatter(logging.Formatter("%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s"))
    logger.addHandler(file_handler)
    return logger