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

python 自定义好用logger模块

root3年前 (2022-01-13)python942
# -*- 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

分享给朋友:

相关文章

python logging 模块对多进程的支持

深度解决方案logging 模块 是支持多线程的但是多进程的会出现问题,因为对文件读写会出现资源的争抢如何解决对多进程的出现的问题concurrent-log-handler包 解决问题该模块同样也为python的标准日志记录软件提供了额外...

centos7 python2安装psutil

[root@internet geo_server]# pip install psutilDEPRECATION: Python 2.7 reached th...

父进程退出后如何退出子进程

我们知道当子进程推出的时候,父进程会收到 SIGCHLD 信号,从而可以采取相应的操作。但是当父进程退出的时候,系统会把子进程的父进程更改为pid=0的 init 进程,而且子进程不会收到任何信号。而我们经常想在父进程退出的时候,让子进程也...

python os 模块文件常用操作

123456import os #回去当前文件路径os.path.realpath(__file__)#获取文件是否存在os.path.exists(filepath)#获取文件大小os.path.getsize(fil...

python 环境变量 conda 包管理 virtualenv 工具

conda 环境conda -h 查看帮助conda env list 查看所有虚拟环境deactivate 退出虚拟环境activate  环境名  进入虚拟环境virtualenv  环境workon&nb...

Python的多线程并发限制

maxConnections connection_lock (maxConnections)在开启线程前执行connection_lock.acquire()线程执行结束执行connection_lock.releas...