zoukankan      html  css  js  c++  java
  • [module]_比Python标准库logging更简洁高效的日志库_loguru

    官方文档: https://loguru.readthedocs.io/en/stable/index.html

    安装:

    pip3 install loguru
    

    基本使用:

    # demo.py
    from loguru import logger
    
    logger.debug("this is a debug message")
    

    命令行输出内容:

    2020-06-04 11:53:00.954 | DEBUG    | __main__:<module>:4 - this is a  debug message
    

    依次对应的是, 时间/级别/模块名/行号/日志信息, 在vscode/pycharm中是彩色输出.

    输出到文件:

    # demo.py
    from loguru import logger
    
    logger.add('runtime.log')
    logger.debug("this is a debug message")
    

    详细使用

    loguru支持输出到多个文件, 分级别分别输出, 超出限制大小创建新文件, 超出时限自动删除等等功能.
    基本上就是add方法的使用, 相当于给logger添加了一个Handle(类似logging里的Handle).

    # https://loguru.readthedocs.io/en/latest/_modules/loguru/_logger.html
    def add(
            self,
            sink,
            *,
            level=_defaults.LOGURU_LEVEL,
            format=_defaults.LOGURU_FORMAT,
            filter=_defaults.LOGURU_FILTER,
            colorize=_defaults.LOGURU_COLORIZE,
            serialize=_defaults.LOGURU_SERIALIZE,
            backtrace=_defaults.LOGURU_BACKTRACE,
            diagnose=_defaults.LOGURU_DIAGNOSE,
            enqueue=_defaults.LOGURU_ENQUEUE,
            catch=_defaults.LOGURU_CATCH,
            **kwargs
        ):
    
    sink参数
    format使用

    filter, 筛选器, 具体怎么使用, 还未知...
    level, "INFO"/"DEBUG"/"ERROR", 输出指定的级别日志.
    time和message使用默认值, 注意time采用UTC+8表达

    # demo.py
    from loguru import logger
    
    logger.add('runtime.log', format="{time} {level} {message}", level="ERROR")
    logger.info("this is a  info message")
    logger.success("this is a  success message")
    logger.error("this is a  error message")
    
    """ runtime.log
    2020-06-04T16:23:18.981843+0800 ERROR this is a  error message
    """
    
    rotation (循环配置)
    """
    The ``rotation`` check is made before logging each message. If there is already an existing
            file with the same name that the file to be created, then the existing file is renamed by
            appending the date to its basename to prevent file overwriting. This parameter accepts:
    
            - an |int| which corresponds to the maximum file size in bytes before that the current
              logged file is closed and a new one started over.
            - a |timedelta| which indicates the frequency of each new rotation.
            - a |time| which specifies the hour when the daily rotation should occur.
            - a |str| for human-friendly parametrization of one of the previously enumerated types.
              Examples: ``"100 MB"``, ``"0.5 GB"``, ``"1 month 2 weeks"``, ``"4 days"``, ``"10h"``,
              ``"monthly"``, ``"18:00"``, ``"sunday"``, ``"w0"``, ``"monday at 12:00"``, ...
            - a |callable|_ which will be invoked before logging. It should accept two arguments: the
              logged message and the file object, and it should return ``True`` if the rotation should
              happen now, ``False`` otherwise.
    """
    
    # 每隔500MB创建1个新的log文件, 并加上time占位符, 生成一个带时间的log文件.
    logger.add('runtime_{time}.log', rotation="500 MB")
    
    # 每天0点创建一个log文件
    logger.add('runtime_{time}.log', rotation="00:00")
    
    # 每隔1周创建1个log文件
    logger.add('runtime_{time}.log', rotation="1 week")
    
    retention (保留配置)
    """
    The ``retention`` occurs at rotation or at sink stop if rotation is ``None``. Files are
            selected if they match the pattern ``"basename(.*).ext(.*)"`` (possible time fields are
            beforehand replaced with ``.*``) based on the sink file. This parameter accepts:
    
            - an |int| which indicates the number of log files to keep, while older files are removed.
            - a |timedelta| which specifies the maximum age of files to keep.
            - a |str| for human-friendly parametrization of the maximum age of files to keep.
              Examples: ``"1 week, 3 days"``, ``"2 months"``, ...
            - a |callable|_ which will be invoked before the retention process. It should accept the
              list of log files as argument and process to whatever it wants (moving files, removing
              them, etc.).
    """
    
    # 指定日志最长保留10天, 这个log只会保留最新10天的log信息
    logger.add('runtime.log', retention='10 days')
    
    compression (压缩配置)
    """
    The ``compression`` happens at rotation or at sink stop if rotation is ``None``. This
            parameter accepts:
    
            - a |str| which corresponds to the compressed or archived file extension. This can be one
              of: ``"gz"``, ``"bz2"``, ``"xz"``, ``"lzma"``, ``"tar"``, ``"tar.gz"``, ``"tar.bz2"``,
              ``"tar.xz"``, ``"zip"``.
            - a |callable|_ which will be invoked before file termination. It should accept the path of
              the log file as argument and process to whatever it wants (custom compression, network
              sending, removing it, etc.).
    """
    
    # 指定压缩格式, 采用zip压缩, 节省空间
    logger.add('runtime.log', compression='zip')
    
    字符串格式化
    """
    # 支持字符串格式化操作, 类似 C# 的String.Format()
    logger.info('If you are using Python {}, prefer {feature} of course!', 3.6, feature='f-strings')
    """
    
    Traceback 记录
    @logger.catch
    def func(x, y, z):
        return 1 / (x + y + z)
    
    
    func(0, 0, 0)
    
    
    Tips:

    微信原文: https://mp.weixin.qq.com/s/CgmfVqogqKBzezmIR7ZfsQ

  • 相关阅读:
    jsf web.xml配置
    JSF中Filter的实现
    转码
    facelates标签
    jsf学习笔记注解
    date工具类
    js秒读功能
    w3c document 与 dom4j document转化工具类
    jsf学习笔记ui
    jsf学习笔记拦截器
  • 原文地址:https://www.cnblogs.com/sunqikai/p/13045158.html
Copyright © 2011-2022 走看看