Normally, the output is displayed on the console |
print() |
Reports events that occur during normal program operation |
logging.info() (or more detailed logging.debug() ) |
Issue a warning about a specific event |
##warnings.warn() orlogging.warning () |
Report an error |
Popup exception |
Report errors without raising an exception
|
##logging.error() , logging.exception() orlogging.critical()
|
The logging module defines the log levels shown in the following table, arranged from low to high event severity (note that they are all capital letters! Because they are constants.):
import logging
logging.basicConfig(level = logging.INFO,format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
logger.info("Start print log")
logger.debug("Do something")
logger.warning("Something maybe fail.")
logger.info("Finish")
Copy after login
Many message levels can be selected in logging, such as debug, info, warning, error and critical. By assigning different levels to the logger or handler, developers can only output error information to a specific log file, or only record debugging information during debugging.
logging.basicConfig(level = logging.DEBUG,format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
Copy after login
For example, we change the logger level to DEBUG,
and then observe the output results
Console output, you can find that debug information is output.
Parameters of logging.basicConfig function:
filename: Specify log File name;
filemode: has the same meaning as the file function, specifying the opening mode of the log file, 'w' or 'a';
format: Specify the output format and content. format can output a lot of useful information.
datefmt:指定时间格式,同time.strftime();
level:设置日志级别,默认为logging.WARNNING;
stream:指定将日志的输出流,可以指定输出到sys.stderr,sys.stdout或者文件,默认输出到sys.stderr,当stream和filename同时指定时,stream被忽略;
#参数:作用
%(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:打印日志信息
Copy after login
2. 将日志写入到文件
设置logging,创建一个FileHandler,并对输出消息的格式进行设置,将其添加到logger,然后将日志写入到指定的文件。
import logging
logger = logging.getLogger(__name__)
logger.setLevel(level = logging.INFO)
handler = logging.FileHandler("log.txt")
handler.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.info("Start print log")
logger.debug("Do something")
logger.warning("Something maybe fail.")
logger.info("Finish")
Copy after login
打开log.txt文件。
2. 将日志同时输出到屏幕和日志文件
logger中添加StreamHandler,可以将日志输出到屏幕上
import logging
logger = logging.getLogger(__name__)
logger.setLevel(level = logging.INFO) #添加StreamHandler
handler = logging.FileHandler("log.txt")
handler.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
console = logging.StreamHandler()
console.setLevel(logging.INFO) #添加StreamHandler
logger.addHandler(handler)
logger.addHandler(console)
logger.info("Start print log")
logger.debug("Do something")
logger.warning("Something maybe fail.")
logger.info("Finish")
Copy after login
控制台信息。
log.text信息。
3. 设置消息的等级
可以设置不同的日志等级,用于控制日志的输出。
#日志等级:使用范围
FATAL:致命错误
CRITICAL:特别糟糕的事情,如内存耗尽、磁盘空间为空,一般很少使用
ERROR:发生错误时,如IO操作失败或者连接问题
WARNING:发生很重要的事件,但是并不是错误时,如用户登录密码错误
INFO:处理请求或者状态变化等日常事务
DEBUG:调试过程中使用DEBUG等级,如算法中每个循环的中间状态
Copy after login
4. 捕获traceback
Python中的traceback模块被用于跟踪异常返回信息,可以在logging中记录下traceback.
import logging
logger = logging.getLogger(__name__)
logger.setLevel(level = logging.INFO)
handler = logging.FileHandler("log.txt")
handler.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
console = logging.StreamHandler()
console.setLevel(logging.INFO)
logger.addHandler(handler)
logger.addHandler(console)
logger.info("Start print log")
logger.debug("Do something")
logger.warning("Something maybe fail.")
try:
open("sklearn.txt","rb")
except (SystemExit,KeyboardInterrupt):
raise
except Exception:
logger.error("Faild to open sklearn.txt from logger.error",exc_info = True)
logger.info("Finish")
Copy after login
控制台和日志文件log.txt中输出。
可以使用logger.exception(msg,args),它等价于logger.error(msg,exc_info = True,args)。
将logger.error("Faild to open sklearn.txt from logger.error",exc_info = True)
Replaced with logger.exception("Failed to open sklearn.txt from logger.exception")
Control output in the console and log file log.txt.
## 2. Summary
This article ends with Taking the basics of Pythonl as an example, it mainly introduces the basic usage of the logging module, as well as the problems encountered in real-life applications, and provides detailed answers.