Python自定义输出格式

描述

自定义输出格式

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

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()

输入样式如下

日志

打开APP阅读更多精彩内容
声明:本文内容及配图由入驻作者撰写或者入驻合作网站授权转载。文章观点仅代表作者本人,不代表电子发烧友网立场。文章及其配图仅供工程师学习之用,如有内容侵权或者其他违规问题,请联系本站处理。 举报投诉

全部0条评论

快来发表一下你的评论吧 !

×
20
完善资料,
赚取积分