Python: 日志记录模块

日志记录模块,根据配置字灵活调用

import logging
import os
from datetime import datetime

def gen_logger(log_level: str = 'INFO', log_path: str = os.getcwd()):
    # Generate logging object
    logger = logging.getLogger(__name__)

    #create log file name
    log_name = datetime.now().strftime('%Y_%m_%d__%H_%M_%S') + 'mylog.log'
    log_name.replace('-', '_')
    # create a file handler
    handler = logging.FileHandler(os.path.join(log_path, log_name), mode='w')
    # create a logging format
    formatter = logging.Formatter('%(levelname)s: [%(asctime)s] %(message)s', '%Y-%m-%d %H:%M:%S')
    handler.setFormatter(formatter)
    logging.basicConfig(format='%(levelname)s: [%(asctime)s] %(message)s', datefmt='%Y-%m-%d %H:%M:%S')

    # set level of logging
    num_level = getattr(logging, log_level.upper(), None)
    if not isinstance(num_level, int):
        logger.setLevel(logging.INFO)
        logger.error('"%s" is not a valid logging level. Level is set to INFO', log_level)
        handler.setLevel(logging.INFO)
    else:
        logger.setLevel(num_level)
        handler.setLevel(num_level)

    # add file handler to logger
    logger.addHandler(handler)

    return logger

 

 

你可能感兴趣的:(python通关之路)