Python logging日志记录, since 2022-0

2022-04-21  本文已影响0人  Mc杰夫

(2022.04.21 Thur)
Logging提供的日志记录方式有两种,分别是

日志级别

logging日志分为五个级别,从低到高如下

默认级别是WARNING。设置了日志级别之后,该级别和高于该级别的信息都可以保存/显示。

日志信息可输出到控制台console,也可输出到指定文件。

import logging
def logging_test():
    logging.debug('this is a debug logging.')
    logging.info('this is an info logging.')
    logging.warning('this is a warning logging.')
    logging.error('this is an error logging.')
    logging.critical('this is a critical logging.')
    return 'done'

调用

>>> logging_test()
WARNING:root:this is a warning logging.
ERROR:root:this is an error logging.
CRITICAL:root:this is a critical logging.
'done'

注意,对logging级别没有设置,所以默认是WARNING,仅显示WARNING, ERROR, CRITICAL三个信息。

日志设置

通过logging.basicConfig可设置,比如

>>> logging.basicConfig(filename='logging_debut.log', level=logging.DEBUG)

可设置的选项包括

指定的格式包括:

应用模块级别函数和设置信息生成日志

def test():
    log_format = '%(asctime)s: %(levelname)s - %(message)s'
    log_filename = 'logging_debut_fmt.log'
    logging.basicConfig(filename= log_filename, level=logging.DEBUG, \
                        format=log_format)
    logging.info('instanciate a class')
    a = [1,2,3] 
    logging.debug('instance: '+str(a))
    logging.warning('conduct addition')
    b = [34,5,6]
    logging.critical('b: '+str(b))
    tmp = a+b
    logging.info('results: '+str(tmp))
    return 'done'

查看log文件,logging_debut_fmt.log

$ cat logging_debut_fmt.log
2022-04-21 12:09:26,061: INFO - instanciate a class
2022-04-21 12:09:26,062: DEBUG - instance: [1, 2, 3]
2022-04-21 12:09:26,062: WARNING - conduct addition
2022-04-21 12:09:26,062: CRITICAL - b: [34, 5, 6]
2022-04-21 12:09:26,062: INFO - results: [1, 2, 3, 34, 5, 6]
上一篇 下一篇

猜你喜欢

热点阅读