Python 日志(logging)模块
来源:互联网 发布:php api 框架 编辑:程序博客网 时间:2024/05/16 04:56
对于小型项目而言,大家习惯于使用print语句打印信息到终端进行调试,然而,当项目代码量扩大到了一定级别后,打印调试的方法就显得很凌乱了,更重要的是,当debug完成后,甄别并删除(或注释)调试用的打印语句变得非常令人头痛。而使用日志模块则能很好地解决这些问题。
1. 什么是日志
日志(logging)是在程序运行过程中对发生的事件的追踪、记录。程序开发者们在代码中引入日志模块以指示某种特定事件的发生,而这些事件可以依据重要程度划分为不同的层级,比如一般信息(info),警告(warning),错误(error)等。
2. 如何使用日志模块
Python的日志模块提供了一系列的函数用来记录不同的日志信息,包括’debug()’,info()
,warning
,error()
,critical()
等,下面的表对不同的函数适用范围做了说明:
这些函数都是根据追踪事件的级别和严重程度来命名的。如下所示:
默认的层级是WARNING,即只追踪警告及其以上的事件发生,比如下面的简单的例子:
import logginglogging.warning('Watch out!') # 将会在终端打印信息logging.info('I told you so') # 不会打印任何信息
运行结果: WARNING:root:Watch out!
3.将日志记录到文件中
import logginglogging.basicConfig(filename='example.log',level=logging.DEBUG)logging.debug('This message should go to the log file')logging.info('So should this')logging.warning('And this, too')
执行上面的代码,然后打开example.log
文件,将会看到下面的内容:
DEBUG:root:This message should go to the log fileINFO:root:So should thisWARNING:root:And this, too
这段代码也对如何设置日志层级进行了说明。其实,也可以通过命令行的方式设置: --log=INFO
然后加入下面的代码读到设置好的层级信息:
numeric_level = getattr(logging, loglevel.upper(), None)if not isinstance(numeric_level, int): raise ValueError('Invalid log level: %s' % loglevel)logging.basicConfig(level=numeric_level, ...)
如果不断运行上面的程序,新的日志将追加到旧的日志之后,这会变得越来越庞大,可以通过下面的方法使新的日志覆盖旧的日志:
logging.basicConfig(filename='example.log', filemode='w', level=logging.DEBUG)
4.从多个模块收集日志信息
下面的代码演示了当你的程序由多个模块组成时管理日志的方法: # myapp.py
import loggingimport mylibdef main(): logging.basicConfig(filename='myapp.log', level=logging.INFO) logging.info('Started') mylib.do_something() logging.info('Finished')if __name__ == '__main__': main()
# mylib.py
import loggingdef do_something(): logging.info('Doing something')
运行myapp.py
的结果:
INFO:root:StartedINFO:root:Doing somethingINFO:root:Finished
5. 记录变量信息
可以使用格式化字符串的方法记录变量:
import logginglogging.warning('%s before you %s', 'Look', 'leap!')
除了上面的方法外,也可以使用str.format()和string.Template方法。
6.改变日志格式
import logginglogging.basicConfig(format='%(levelname)s:%(message)s', level=logging.DEBUG)logging.debug('This message should appear on the console')logging.info('So should this')logging.warning('And this, too')
输出:
DEBUG:This message should appear on the consoleINFO:So should thisWARNING:And this, too
7. 显示日期时间
在格式化输出信息中引入(asctime)s
来显示时间:
import logginglogging.basicConfig(format='%(asctime)s %(message)s')logging.warning('is when this event was logged.')
输出:
2010-12-12 11:41:42,612 is when this event was logged.
默认的日期格式是ISO8601,你也可以在basicConfig
中进行改变:
import logginglogging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')logging.warning('is when this event was logged.')
输出:
12/12/2010 11:46:36 AM is when this event was logged.
除此之外,还可以使用time.strftime()
来改变时间格式。
更高级的使用方法请看官方教程 Advanced Logging Tutorial
关注微信公众号IT练功房,分享最新IT资讯,学习编程技能,让我们共同进步!
- Python日志模块-logging
- Python日志模块logging
- Python 日志(logging)模块
- Python:logging日志模块
- python日志模块----logging
- python 日志模块 logging
- python(logging )日志模块
- python logging日志模块
- Python 日志logging模块
- python logging日志模块
- python日志模块---logging
- python 日志模块logging
- Python--日志模块Logging
- python logging日志模块
- Python logging 日志模块
- python日志模块(logging)
- python-logging.config【日志模块】
- python 的日志logging模块
- ios开发进阶之多线程02 NSOperation
- PCM Mix
- TCP/IP详解-TCP的超时和重传
- 剑指Offer-从头到尾打印链表
- 1302 The Snail【模拟】
- Python 日志(logging)模块
- Android 线程详解
- Walls(floyd POJ1161)
- 剑指Offer-重建二叉树
- DB2 存储过程的异常处理器类型有几种?
- JavaFX中javafx.concurrent.Task类的使用
- Terminal Access Controller Access-Control System
- 第50讲:Scala中Variance变化点及其在Spark中的应用源码解析学习笔记
- 剑指Offer-链表中倒数第k个结点