Pyton日志模块logging简介
日志是非常重要的,Python有专门的日志处理模块Logging,该模块属于Python内置模块,可以直接使用。
通过Logging模块把日志打印到屏幕上。
1 2 3 4 5 6 7 8 9 10 |
dengyuandeMacBook-Pro:~ oosmart$ python Python 3.6.1 (v3.6.1:69c0db5050, Mar 21 2017, 01:21:04) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import logging >>> logging.debug('Hello py40.com') >>> logging.info('Hello py30.com info') >>> logging.warning('Hello py40.com warning') WARNING:root:Hello py40.com warning >>> |
Python配置日志Logging.basicConfig方法简介
1 2 3 4 5 6 7 8 9 10 11 12 |
import logging logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s', datefmt='%a, %d %b %Y %H:%M:%S', filename='D:/tmp/test.log', filemode='w') logging.debug('debug message') logging.info('info message') logging.warning('warning message') logging.error('error message') logging.critical('critical message') |
打开我们的D:/tmp/test.log
1 2 3 4 5 |
Mon, 05 May 2014 16:29:53 test_logging.py[line:9] DEBUG debug message Mon, 05 May 2017 16:29:53 test_logging.py[line:10] INFO info message Mon, 05 May 2017 16:29:53 test_logging.py[line:11] WARNING warning message Mon, 05 May 2017 16:29:53 test_logging.py[line:12] ERROR error message Mon, 05 May 2017 16:29:53 test_logging.py[line:13] CRITICAL critical message |
logging.basicConfig()函数参数说明
filename:用指定的文件名创建FiledHandler(后边会具体讲解handler的概念),这样日志会被存储在指定的文件中。
filemode:文件打开方式,在指定了filename时使用这个参数,默认值为“a”还可指定为“w”。
format:指定handler使用的日志显示格式。
datefmt:指定日期时间格式。
level:设置rootlogger(后边会讲解具体概念)的日志级别
stream:用指定的stream创建StreamHandler。可以指定输出到sys.stderr,sys.stdout或者文件,默认为sys.stderr。若同时列出了filename和stream两个参数,则stream参数会被忽略。
format参数中常用用到的格式化串:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
%(name)s Logger的名字 %(levelno)s 数字形式的日志级别 %(levelname)s 文本形式的日志级别 %(pathname)s 调用日志输出函数的模块的完整路径名,可能没有 %(filename)s 调用日志输出函数的模块的文件名 %(module)s 调用日志输出函数的模块名 %(funcName)s 调用日志输出函数的函数名 %(lineno)d 调用日志输出函数的语句所在的代码行 %(created)f 当前时间,用UNIX标准的表示时间的浮 点数表示 %(relativeCreated)d 输出日志信息时的,自Logger创建以 来的毫秒数 %(asctime)s 字符串形式的当前时间。默认格式是 “2003-07-08 16:49:45,896”。逗号后面的是毫秒 %(thread)d 线程ID。可能没有 %(threadName)s 线程名。可能没有 %(process)d 进程ID。可能没有 %(message)s用户输出的消息 |
未经允许不得转载:Python在线学习 » python日志模块logging