Python中的日志模块为logging,需导入之后才可以使用。先上代码再解释:
-
#coding=utf-8
-
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= 'test.log',
-
filemode= 'w')
-
test = [ 1, 2, 3, 4, 5, 6, 7, 8, 9]
-
for i in xrange( 5):
-
logging.debug(test)
Sat, 04 Mar 2017 14:13:20 write_logging.py[line:11] DEBUG [1, 2, 3, 4, 5, 6, 7, 8, 9]
Sat, 04 Mar 2017 14:13:20 write_logging.py[line:11] DEBUG [1, 2, 3, 4, 5, 6, 7, 8, 9]
Sat, 04 Mar 2017 14:13:20 write_logging.py[line:11] DEBUG [1, 2, 3, 4, 5, 6, 7, 8, 9]
Sat, 04 Mar 2017 14:13:20 write_logging.py[line:11] DEBUG [1, 2, 3, 4, 5, 6, 7, 8, 9]
Sat, 04 Mar 2017 14:13:20 write_logging.py[line:11] DEBUG [1, 2, 3, 4, 5, 6, 7, 8, 9]
再次执行代码,则新生成的文件会替换掉原有文件。
下面详细解释一下logging模块(部分内容参考网络):
日志级别大小关系:CRITICAL>ERROR>WARNING>INFO>DEBUG>NOTSET
logging.basicConfig函数各参数:
level:设置日志级别,默认值logging.WARNING
filename:指定的日志文件名
filemode:指定日志文件的打开模式,‘w’或‘a‘
format:指定输出格式和内容,其中:
%(asctime)s:打印日志的时间
%(filename)s:打印当前执行的程序名
%(lineno)d:打印日志的当前行号
%(levelname)s:打印日志级别名称
%(message)s:打印日志信息
完整的:
%(levelno)s: 打印日志级别的数值
%(levelname)s: 打印日志级别名称
%(pathname)s: 打印当前执行程序的路径,其实就是sys.argv[0]
%(filename)s: 打印当前执行程序名
%(funcName)s: 打印日志的当前函数
%(lineno)d: 打印日志的当前行号
%(asctime)s: 打印日志的时间
%(thread)d: 打印线程ID
%(threadName)s: 打印线程名称
%(process)d: 打印进程ID
%(message)s: 打印日志信息
将异常信息打印到日志中:
-
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= 'test.log',
-
filemode= 'a') # 在文件原有内容后追加新内容
-
-
try:
-
import asdfghjkl # 尝试导入一个非法库
-
-
except:
-
logging.exception( "Exception logged")