python项目封装日志通用工具

关于日志颜色控制,详见:python打印高亮-日志颜色输出控制

一、日志工具类utils_log.py

"""
定义log对象,以及改写log的部分函数,改变日志的输出颜色
"""

import os, logging, logging.config, settings


class MyLogger(logging.Logger):
    """重写Logger的某些函数,给这些等级的日志输出不同颜色"""

    def info(self, msg, *args, **kwargs):
        """重写info函数"""

        if self.isEnabledFor(20):
            self._log(20, "\033[36;1m%s\033[0m" % msg, args, **kwargs)

    def error(self, msg, *args, **kwargs):
        """重写error函数"""

        if self.isEnabledFor(40):
            self._log(40, "\033[31;1m%s\033[0m" % msg, args, **kwargs)


logging.setLoggerClass(MyLogger)
logging.config.fileConfig(os.path.join(settings.PROJECT_ROOT, "logger.conf"))
log = logging.getLogger("infile")
log.info("============== log initialized ==============")

二.logger.conf

#logger.conf

###############################################
[loggers]
keys=root,infile

[logger_root]
level=ERROR
handlers=error

[logger_infile]
level=DEBUG
handlers=console,socket
qualname=infile
propagate=0

###############################################
[handlers]
keys=console,socket,error

[handler_console]
class=StreamHandler
formatter=verbose
args=(sys.stdout,)

[handler_socket]
class=handlers.SocketHandler
formatter=verbose
args=('localhost', handlers.DEFAULT_TCP_LOGGING_PORT)

[handler_error]
class=StreamHandler
formatter=simple
args=(sys.stderr,)

###############################################
[formatters]
keys=verbose,simple

[formatter_verbose]
format=[%(asctime)s][%(process)d][%(thread)d][%(levelname)-5s][%(filename)s:%(lineno)d][%(funcName)s]: %(message)s
datefmt=%m%d %H:%M:%S

[formatter_simple]
format=[%(asctime)s][%(name)s]: %(message)s
datefmt=%m%d %H:%M:%S

发布了146 篇原创文章 · 获赞 66 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/qq_38923792/article/details/103914151