Home  >  Article  >  Backend Development  >  An article will guide you through the logging module in Python

An article will guide you through the logging module in Python

Go语言进阶学习
Go语言进阶学习forward
2023-07-25 14:04:431499browse

1. Basic usage

1. Logging usage scenarios

What is the log? This doesn’t require much explanation. Ninety percent of programs need to provide logging functionality. Python's built-in logging module provides us with a ready-made, efficient and easy-to-use logging solution. However, not all scenarios require the use of the logging module.

The following is the officially recommended usage method of Python: (Source Baidu)

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")

An article will guide you through the logging module in Python

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')

For example, we change the logger level to DEBUG,

and then observe the output results

An article will guide you through the logging module in Python

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:打印日志信息

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")

打开log.txt文件。

An article will guide you through the logging module in Python

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")

控制台信息。

An article will guide you through the logging module in Python

log.text信息。

An article will guide you through the logging module in Python

3. 设置消息的等级

可以设置不同的日志等级,用于控制日志的输出。

#日志等级:使用范围
FATAL:致命错误
CRITICAL:特别糟糕的事情,如内存耗尽、磁盘空间为空,一般很少使用
ERROR:发生错误时,如IO操作失败或者连接问题
WARNING:发生很重要的事件,但是并不是错误时,如用户登录密码错误
INFO:处理请求或者状态变化等日常事务
DEBUG:调试过程中使用DEBUG等级,如算法中每个循环的中间状态

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")

控制台和日志文件log.txt中输出。

An article will guide you through the logging module in Python

可以使用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.

An article will guide you through the logging module in Python

## 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.

Task Scenario Best Tool
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 above is the detailed content of An article will guide you through the logging module in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:Go语言进阶学习. If there is any infringement, please contact admin@php.cn delete