python自定义log打印模块

说明:能够从其他文件直接导入使用;能够在文件中显示debug信息,在控制台显示info信息,实现比较简单,仅供参考

# coding:utf-8
import logging
import datetime
import os

BASE_LOGGER = None
LOG_PATH = None


def gen_logger(log_file=None):
    global BASE_LOGGER, LOG_PATH
    if not LOG_PATH:
        log_path = os.path.dirname(os.path.realpath(__file__))
        log_name = datetime.datetime.now().strftime("%Y_%m_%d_%H_%M_%S") + '.log'
        LOG_PATH = os.path.join(log_path, log_name)
    if log_file:
        LOG_PATH = log_file
    if not BASE_LOGGER:
        BASE_LOGGER = logging.getLogger()
        BASE_LOGGER.setLevel(logging.DEBUG)
        fh = logging.FileHandler(LOG_PATH, encoding='utf-8')
        fh.setLevel(logging.DEBUG)
        ch = logging.StreamHandler()
        ch.setLevel(logging.INFO)
        formatter = logging.Formatter(
            '[%(asctime)s] %(filename)s->line:%(lineno)d [%(levelname)s]%(message)s')
        fh.setFormatter(formatter)
        ch.setFormatter(formatter)
        BASE_LOGGER.addHandler(fh)
        BASE_LOGGER.addHandler(ch)
        fh.close()
        ch.close()
    return BASE_LOGGER


def debug(msg, *args, **kwargs):
    gen_logger()
    BASE_LOGGER.debug(msg, *args, **kwargs)


def info(msg, *args, **kwargs):
    gen_logger()
    BASE_LOGGER.info(msg, *args, **kwargs)


def warning(msg, *args, **kwargs):
    gen_logger()
    BASE_LOGGER.warning(msg, *args, **kwargs)


def error(msg, *args, **kwargs):
    gen_logger()
    BASE_LOGGER.error(msg, *args, **kwargs)


def critical(msg, *args, **kwargs):
    gen_logger()
    BASE_LOGGER.critical(msg, *args, **kwargs)


if __name__ == '__main__':
    logger = gen_logger('test.log')
    logger.debug("debug")
    logger.info("info")
    logger.error("error")
    logger.warning("warn")
    logger.critical("critical")

其他文件使用直接导入此py文件,若需要自定义log目录,需在使用前调用gen_logger(path),

还有一种按照模块打印log的方式也贴出来大家参考下

# coding:utf-8
import os
import datetime
import logging
import logging.config as log_conf

log_dir = os.path.dirname(os.path.dirname(__file__))
if not os.path.exists(log_dir):
    os.mkdir(log_dir)

log_name = datetime.datetime.now().strftime("%Y_%m_%d_%H_%M_%S") + '.log'
log_path = os.path.join(log_dir, log_name)

log_config = {
    'version': 1.0,
    'formatters': {
        'detail': {
            'format': '%(asctime)s - %(name)s - %(levelname)s - %(message)s',
            'datefmt': "%Y-%m-%d %H:%M:%S"
        },
        'simple': {
            'format': '%(name)s - %(levelname)s - %(message)s',
        },
    },
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
            'level': 'INFO',
            'formatter': 'detail'
        },
        'file': {
            'class': 'logging.handlers.RotatingFileHandler',
            'maxBytes': 1024 * 1024 * 5,
            'backupCount': 10,
            'filename': log_path,
            'level': 'DEBUG',
            'formatter': 'detail',
            'encoding': 'utf-8',
        },
    },
    'loggers': {
        'logger': {
            'handlers': ['console', 'file'],
            'level': 'DEBUG',
        },
        'other': {
            'handlers': ['console', 'file'],
            'level': 'INFO',
        }
    }
}

log_conf.dictConfig(log_config)

logger = logging.getLogger('logger')
other = logging.getLogger('other')

if __name__ == '__main__':
    logger.info("logger")
    other.info("other")

你可能感兴趣的:(python自定义log打印模块)