Logging:日志记录是为了跟踪记录软件运行时,发生的事件,包括出错,提示信息等等。
log日志级别:日志级别大小关系为:CRITICAL > ERROR > WARNING > INFO > DEBUG > NOTSET;模块默认级别为WARNING,即当且仅当等于或高于WARNING的事件会被记录下来,其余的忽略不计。
1、打印到屏幕:
import logging
logging.warn("this logging warn")
logging.info("this is logging info")
屏幕打印为:
WARNING:root:this logging warn
2、打印到指定文件
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")
3、通过logging.basicConfig函数对日志的输出格式及方式做相关配置
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函数各参数:
4、将日志同时输出到文件和屏幕
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')