将日志保存到文件中

Python中的日志模块为logging,需导入之后才可以使用。先上代码再解释:

  1. #coding=utf-8
  2. import logging
  3. logging.basicConfig(level=logging.DEBUG,
  4. format= '%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
  5. datefmt= '%a, %d %b %Y %H:%M:%S',
  6. filename= 'test.log',
  7. filemode= 'w')
  8. test = [ 1, 2, 3, 4, 5, 6, 7, 8, 9]
  9. for i in xrange( 5):
  10. logging.debug(test)
代码执行之后,会在代码当前目录中生成一个test.log文件,文件里的内容为:

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: 打印日志信息


将异常信息打印到日志中:

  1. import logging
  2. logging.basicConfig(level=logging.DEBUG,
  3. format= '%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
  4. datefmt= '%a, %d %b %Y %H:%M:%S',
  5. filename= 'test.log',
  6. filemode= 'a') # 在文件原有内容后追加新内容
  7. try:
  8. import asdfghjkl # 尝试导入一个非法库
  9. except:
  10. logging.exception( "Exception logged")

猜你喜欢

转载自blog.csdn.net/weixin_37887248/article/details/81010868