python3:logging模块 输出日志到文件

python自动化测试脚本运行后,想要将日志保存到某个特定文件,使用python的logging模块实现

参考代码:

import logging

def initLogging(logFilename,e):

  logging.basicConfig(
                    level = logging.INFO,
                    format ='%(asctime)s-%(levelname)s-%(message)s',
                    datefmt = '%y-%m-%d %H:%M',
                    filename = logFilename,
                    filemode = 'a')
  
  filehandler = logging.FileHandler(logFilename,encoding='utf-8')
  logging.getLogger().addHandler(filehandler )
  log = logging.exception(e)
  return log

1.日志级别使用场景:
在终端输出程序或脚本的使用方法:print
报告一个事件的发生(例如状态的修改):logging.info()或logging.debug()
发生了一个特定的警告性的事件:logging.warn()
发生了一个特定的错误性的事件:raise
发生了一个特定的错误性的事件,但是又不想因为此错误导致程序退出(例如程序是一个守护进程):logging.error(),logging.exception(),logging.critical()

2.logging.basicConfig()函数中可通过具体参数来更改logging模块默认行为,可用参数有:
level:设置日志级别
format:指定handler使用的日志显示格式
datefmt:指定日期时间格式,如果format参数中存在asctime,则需要指定时间格式
filename:用指定的文件名创建FiledHandler,这样日志会被存储在指定的文件中
filemode:文件打开方式,在指定了filename时使用这个参数,默认值为“a”还可指定为“w”

3.format参数中可能用到的格式化串:
%(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用户输出的消息

4.logging模块的了解,必须知道:Logger,Handler,Formatter,Filter
(1)logger 提供了应用程序可以直接使用的接口
每个程序在输出信息之前都要获得一个Logger
Logger.addHandler(hdlr)、Logger.removeHandler(hdlr):增加或删除指定的handler

(2)handler 将(logger创建的)日志记录发送到合适的目的输出
logging.FileHandler用于向一个文件输出日志信息,不过FileHandler会帮你打开这个文件。它的构造函数是:
FileHandler(filename[,mode])filename是文件名,必须指定一个文件名;mode是文件的打开方式

(3)filter 提供了细度设备来决定输出哪条日志记录

扫描二维码关注公众号,回复: 1571380 查看本文章

(4)formatter 决定日志记录的最终输出格式

5.输出日志结果:

18-06-12 17:34-ERROR-string indices must be integers
Traceback (most recent call last):
  File "C:/Users/xx/Documents/GitHub/python3/main/run_test.py", line 70, in go_on_run
    op_header.write_cookie()
  File "C:\Users\xx\Documents\GitHub\python3\util\operation_header.py", line 30, in write_cookie
    cookie = requests.utils.dict_from_cookiejar(self.get_cookie())
  File "C:\Users\xx\Documents\GitHub\python3\util\operation_header.py", line 25, in get_cookie
    url = self.get_response_url()+"&callback=jQuery21008240514814031887_1508666806688&_=1508666806689"
  File "C:\Users\xx\Documents\GitHub\python3\util\operation_header.py", line 18, in get_response_url
    url = self.response['data']['url'][0]
TypeError: string indices must be integers

参考文档:

https://www.cnblogs.com/Xjng/p/8a481db3399827ecbdec888989f7c0d5.html

https://www.cnblogs.com/wenwei-blog/p/7196658.html

猜你喜欢

转载自www.cnblogs.com/shapeL/p/9174303.html