python日志库loguru使用教程/封装loguru工具类/自定义日志格式化控制台输出和日志写入

觉得有帮助的小伙伴可以点个赞!分享给更多人!

目录

    • 先看二次封装loguru后的结果如何.
      • 控制台输出,增加进程,线程记录
      • 日志写入到文件的格式,日志写入格式可以与控制台单独分开设置
      • 而默认的输出模式是这样的
    • 如何封装loguru为工具类/修改控制台日志输出和日期写入的格式/关闭日志写入
      • 为什么有关闭日志写入的需求呢?
    • 分享自己从作者的源码中查到的一些参数说明.用于调整日志的输出格式(颜色等)

loguru的git网址,点我去

先看二次封装loguru后的结果如何.

控制台输出,增加进程,线程记录

python日志库loguru使用教程/封装loguru工具类/自定义日志格式化控制台输出和日志写入_第1张图片

日志写入到文件的格式,日志写入格式可以与控制台单独分开设置

python日志库loguru使用教程/封装loguru工具类/自定义日志格式化控制台输出和日志写入_第2张图片

而默认的输出模式是这样的

python日志库loguru使用教程/封装loguru工具类/自定义日志格式化控制台输出和日志写入_第3张图片
我更改了其输出的格式使我们可以利用编辑器(pycharm)快速定位到问题所在
说明:loguru的格式化输出,控制台和日志写入是不同的,分开设置的.
在这里插入图片描述
python日志库loguru使用教程/封装loguru工具类/自定义日志格式化控制台输出和日志写入_第4张图片

以pycharm为例,**我们鼠标选中黄色区域,Ctrl+Shift+N 即可在ALL中找到该方法(精确到行号)**快速定位到日志显示的代码所在.这里笔者只是做了简单的演示,更多的需求可以自己更改实现.

如何封装loguru为工具类/修改控制台日志输出和日期写入的格式/关闭日志写入

为什么有关闭日志写入的需求呢?

因为某些场景下降低多线程/多进程下磁盘性能开销;

前置条件:

pip install loguru
import sys

from loguru import logger

my_log_file_path = "test_log"


class MyLogger:
    def __init__(self, log_file_path=my_log_file_path):
        self.logger = logger
        # 清空所有设置
        self.logger.remove()
        # 添加控制台输出的格式,sys.stdout为输出到屏幕;关于这些配置还需要自定义请移步官网查看相关参数说明
        self.logger.add(sys.stdout,
                        format="{time:YYYYMMDD HH:mm:ss} | "  # 颜色>时间
                               "{process.name} | "  # 进程名
                               "{thread.name} | "  # 进程名
                               "{module}.{function}"  # 模块名.方法名
                               ":{line} | "  # 行号
                               "{level}: "  # 等级
                               "{message}",  # 日志内容
                        )
        # 输出到文件的格式,注释下面的add',则关闭日志写入
        self.logger.add(log_file_path, level='DEBUG',
                        format='{time:YYYYMMDD HH:mm:ss} - '  # 时间
                               "{process.name} | "  # 进程名
                               "{thread.name} | "  # 进程名
                               '{module}.{function}:{line} - {level} -{message}',  # 模块名.方法名:行号
                        rotation="10 MB")

    def get_logger(self):
        return self.logger


my_logger = MyLogger().get_logger()


def ss():
    my_logger.info(2222222)
    my_logger.debug(2222222)
    my_logger.warning(2222222)
    my_logger.error(2222222)
    my_logger.exception(2222222)


if __name__ == '__main__':
    ss()

分享自己从作者的源码中查到的一些参数说明.用于调整日志的输出格式(颜色等)

        +------------+---------------------------------+----------------------------+
        | Key        | Description                     | Attributes                 |
        +============+=================================+============================+
        | elapsed    | The time elapsed since the      | See |timedelta|            |
        |            | start of the program            |                            |
        +------------+---------------------------------+----------------------------+
        | exception  | The formatted exception if any, | ``type``, ``value``,       |
        |            | ``None`` otherwise              | ``traceback``              |
        +------------+---------------------------------+----------------------------+
        | extra      | The dict of attributes          | None                       |
        |            | bound by the user (see |bind|)  |                            |
        +------------+---------------------------------+----------------------------+
        | file       | The file where the logging call | ``name`` (default),        |
        |            | was made                        | ``path``                   |
        +------------+---------------------------------+----------------------------+
        | function   | The function from which the     | None                       |
        |            | logging call was made           |                            |
        +------------+---------------------------------+----------------------------+
        | level      | The severity used to log the    | ``name`` (default),        |
        |            | message                         | ``no``, ``icon``           |
        +------------+---------------------------------+----------------------------+
        | line       | The line number in the source   | None                       |
        |            | code                            |                            |
        +------------+---------------------------------+----------------------------+
        | message    | The logged message (not yet     | None                       |
        |            | formatted)                      |                            |
        +------------+---------------------------------+----------------------------+
        | module     | The module where the logging    | None                       |
        |            | call was made                   |                            |
        +------------+---------------------------------+----------------------------+
        | name       | The ``__name__`` where the      | None                       |
        |            | logging call was made           |                            |
        +------------+---------------------------------+----------------------------+
        | process    | The process in which the        | ``name``, ``id`` (default) |
        |            | logging call was made           |                            |
        +------------+---------------------------------+----------------------------+
        | thread     | The thread in which the         | ``name``, ``id`` (default) |
        |            | logging call was made           |                            |
        +------------+---------------------------------+----------------------------+
        | time       | The aware local time when the   | See |datetime|             |
        |            | logging call was made           |                            |
        +------------+---------------------------------+----------------------------+


		+------------------------------------+--------------------------------------+
        | Color (abbr)                       | Styles (abbr)                        |
        +====================================+======================================+
        | Black (k)                          | Bold (b)                             |
        +------------------------------------+--------------------------------------+
        | Blue (e)                           | Dim (d)                              |
        +------------------------------------+--------------------------------------+
        | Cyan (c)                           | Normal (n)                           |
        +------------------------------------+--------------------------------------+
        | Green (g)                          | Italic (i)                           |
        +------------------------------------+--------------------------------------+
        | Magenta (m)                        | Underline (u)                        |
        +------------------------------------+--------------------------------------+
        | Red (r)                            | Strike (s)                           |
        +------------------------------------+--------------------------------------+
        | White (w)                          | Reverse (v)                          |
        +------------------------------------+--------------------------------------+
        | Yellow (y)                         | Blink (l)                            |
        +------------------------------------+--------------------------------------+
        |                                    | Hide (h)                             |
        +------------------------------------+--------------------------------------+

你可能感兴趣的:(python,python,日志,loguru)