当前位置:诺佳网 > 电子/半导体 > 可编程逻辑 >

Python自定义输出格式

时间:2023-10-07 | 栏目:可编程逻辑 | 点击:

自定义输出格式

我们可以在之前添加的输出格式中添加其他的格式内容

import coloredlogs
import logging

def func_name():
    # 增加了modulesfuncName两个变量,分辨标识我们日志所在文件以及在哪一个函数中输入的日志
    coloredlogs.install(level='DEBUG', fmt='%(asctime)s - %(module)s - %(funcName)s - %(levelname)s - %(message)s')

    logging.debug('debug message')
    logging.info('info message')
    logging.error('error message')
    logging.warning('warning message')


func_name()

输出结果如下

图片我们增加了两个变量后,可以方便我们后续寻找问题时就直接定位到了那个文件中的哪个函数出了问题,这是不是就方便我们后面解决问题的效率。

自定义日志级别输出样式

再上面我们是直接使用了coloredlogs中的默认日志级别颜色样式,同样的我们也可以自定义设置不同日志的显示的样色样式

import coloredlogs
import logging


def fun_name():
    level_styles = coloredlogs.DEFAULT_LEVEL_STYLES.copy()
    level_styles['debug'] = {'color': 'magenta'}
    level_styles['info'] = {'color': 'yellow'}
    level_styles['error'] = {'color': 'red'}
    level_styles['warning'] = {'color': 'blue'}
    coloredlogs.install(level="DEBUG", level_styles=level_styles,
                        fmt='%(asctime)s - %(module)s - %(funcName)s - %(levelname)s - %(message)s')

    logging.debug('debug message')
    logging.info('info message')
    logging.error('error message')
    logging.warning('warning message')


fun_name()

输入样式如下

图片

您可能感兴趣的文章:

相关文章