当前位置:首页 > python > 正文内容

python 自定义好用logger模块

root4年前 (2022-01-13)python1406
# -*- coding:utf-8 -*-
import sys
import logging.handlers

DEFAULT_LOG_FMT = '%(asctime)s %(filename)s [line:%(lineno)d] %(levelname)s: %(message)s'
DEFUALT_LOG_DATEFMT = '%Y-%m-%d %H:%M:%S'
Handlers = {
    # logging.NOTSET : "./log/NOTSET.log",
    logging.DEBUG: "./log/DEBUG.log",
    logging.INFO: "./log/INFO.log",
    logging.WARNING: "./log/WARNING.log",
    logging.ERROR: "./log/ERROR.log",
    # logging.CRITICAL : "./log/CRITICAL.log"
}
class Logger(object):

    def __init__(self):
        # set formatter ,the log will print like this formatter
        self.formatter = logging.Formatter(fmt=DEFAULT_LOG_FMT, datefmt=DEFUALT_LOG_DATEFMT)
        self.log_set = {}
        # get logger and set handler
        for level in Handlers.keys():
            logger = logging.getLogger(str(Handlers[level]))
            if not logger.handlers:
                logger.addHandler(self._get_rotating_file_handler(Handlers[level]))
                logger.addHandler(self._get_console_handler())
                logger.setLevel(level)
                self.log_set[level] = logger
            else:
                self.log_set[level] = logger

    def _get_console_handler(self):
        '''get console handler,will print log on console'''
        console_handler = logging.StreamHandler(sys.stdout)
        console_handler.setFormatter(self.formatter)
        return console_handler

    def _get_rotating_file_handler(self, filename):
        '''get a file handler,will write log in file'''
        rotating_handler = logging.handlers.RotatingFileHandler(filename=filename, maxBytes=104857600, backupCount=5,
                                                                encoding="utf-8")
        rotating_handler.setFormatter(self.formatter)
        return rotating_handler

    @property
    def debug(self):
        '''return a function that write debug message'''
        return self.log_set[logging.DEBUG].debug

    @property
    def info(self):
        '''return a function that write info message'''
        return self.log_set[logging.INFO].info

    @property
    def warning(self):
        '''return a function that write warning message'''
        return self.log_set[logging.WARNING].warning

    @property
    def error(self):
        '''return a function that write error message'''
        return self.log_set[logging.ERROR].error


logger = Logger()

if __name__ == '__main__':

    logger.debug("debug")


非常好用的自定义logger模块

可以设置控制台输出和写入文件

对于写入数据库还需努力

扫描二维码推送至手机访问。

版权声明:本文由一叶知秋发布,如需转载请注明出处。

本文链接:https://zhiqiu.top/?id=207

分享给朋友:

相关文章

linux 的信号和快捷键&python的信号

linux信号 1) SIGHUP           2) SIGINT     &nb...

python 在centos 执行pip安装包时最好提前执行的语句

yum install python-develpip install --upgrade setuptoolspip install --upgrade pi...

python简单的加密解密

rsa 是非对称加密公钥加密,私钥解密pip install rsaimport rsa from binascii import b2a_hex, a2b_hex class&nb...

cmd启动python交互模式 出现UnicodeDecodeError: 'gbk' codec can't decode byte 0x9a in position 533

这是因为在python交互模式的中输出了中文,且是个输出被记录在.python_history中删除历史记录文件C:\Users\Administrator\.python_history...

flask 服务添加ssl 证书

flask 服务添加ssl 证书

1、利用openssl生成自用的ssl证书利用openssl 生成证书openssl genrsa -des3 -out server.key 2048不要密码:再执行 一下:openssl rsa -in server.key -out...

python 之optparse模块OptionParser

该模块让python脚本命令能够符合标准的Unix命令例程式每个命令行参数就是由参数名字符串和参数属性组成的。如 -f 或者 file 分别是长短参数名当你将所有的命令行参数都定义好了的时候,我们需要调用parse_args()方法赖际熙a...