python输出日志到文件_python3:logging模块 输出日志到文件

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

参考代码:

importloggingdefinitLogging(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 提供了细度设备来决定输出哪条日志记录

(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, ingo_on_run

op_header.write_cookie()

File"C:\Users\xx\Documents\GitHub\python3\util\operation_header.py", line 30, inwrite_cookie

cookie=requests.utils.dict_from_cookiejar(self.get_cookie())

File"C:\Users\xx\Documents\GitHub\python3\util\operation_header.py", line 25, inget_cookie

url= self.get_response_url()+"&callback=jQuery21008240514814031887_1508666806688&_=1508666806689"File"C:\Users\xx\Documents\GitHub\python3\util\operation_header.py", line 18, inget_response_url

url= self.response['data']['url'][0]

TypeError: string indices must be integers

参考文档:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值