Logging:日志记录是为了跟踪记录软件运行时,发生的事件,包括出错,提示信息等等。
log日志级别:日志级别大小关系为:CRITICAL > ERROR > WARNING > INFO > DEBUG > NOTSET;模块默认级别为WARNING,即当且仅当等于或高于WARNING的事件会被记录下来,其他的忽略不计。html
import logging logging.warn("this logging warn") logging.info("this is logging info")
屏幕打印为:面试
WARNING:root:this logging warn
import logging LOG_FILENAME="/root/project/log.txt" logging.basicConfig(filename=LOG_FILENAME,level=logging.INFO) logging.info("This message should go to the log file")
import logging # LOG_FILENAME = r"C:\Users\weiming\Desktop\log.txt" # logging.basicConfig(filename=LOG_FILENAME, level=logging.INFO) 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='logs.log', filemode='w') logging.debug('debug information') logging.info('info information') logging.warn( 'warning information')
logging.basicConfig函数各参数:函数
filename: 指定日志文件名
filemode: 和file函数意义相同,指定日志文件的打开模式,’w’或’a’
format: 指定输出的格式和内容,format能够输出不少有用信息,如上例所示:
%(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: 打印日志信息
datefmt: 指定时间格式,同time.strftime()
level: 设置日志级别,默认为logging.WARNING
stream: 指定将日志的输出流,能够指定输出到sys.stderr,sys.stdout或者文件,默认输出到sys.stderr,当stream和filename同时指定时,stream被忽略测试
若是对软件测试、接口测试、自动化测试、面试经验交流。感兴趣能够加软件测试交流:1085991341,还会有同行一块儿技术交流。this
import logging # LOG_FILENAME = r"C:\Users\weiming\Desktop\log.txt" # logging.basicConfig(filename=LOG_FILENAME, level=logging.INFO) 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='logs.log', filemode='w') # 定义一个StreamHandler,将INFO级别或更高的日志信息打印到标准错误,并将其添加到当前的日志处理对象 console = logging.StreamHandler() console.setLevel(logging.INFO) formatter = logging.Formatter('%(name)-12s:%(levelname)-8s %(message)s') console.setFormatter(formatter) logging.getLogger('').addHandler(console) logging.debug('debug information') logging.info('info information') logging.warn('warning information')
以上内容但愿对你有帮助,有被帮助到的朋友欢迎点赞,评论。线程