示例:logger日志输出功能
以前不知道logger这个功能这么好用,每次查问题,都是print大法,用起来不方便
使用logger的时候,首先需要使用basicConfig配置下
import logging
level = logging.INFO
logging.basicConfig(format="%(asctime)s %(levelname)s %(message)s", datefmt="%Y-%m-%d %H:%M:%S",
level=levle)
# 这样既可以输出日志了
format格式输出,可以直接输出
| Format | Description |
|---|---|
| filename | Specifies that a FileHandler be created, using the specified filename, rather than a StreamHandler. |
| filemode | If filename is specified, open the file in this mode. Defaults to 'a'. |
| format | Use the specified format string for the handler. |
| datefmt | Use the specified date/time format, as accepted by time.strftime(). |
| style | If format is specified, use this style for the format string. One of '%', '{' or '$'for printf-style, str.format() or string.Template respectively. Defaults to '%'. |
| level | Set the root logger level to the specified level. |
| stream | Use the specified stream to initialize the StreamHandler. Note that this argument is incompatible with filename - if both are present, a ValueError is raised. |
| handlers | If specified, this should be an iterable of already created handlers to add to the root logger. Any handlers which don’t already have a formatter set will be assigned the default formatter created in this function. Note that this argument is incompatible with filename or stream - if both are present, a ValueError is raised. |
日志级别有5种
| 日志等级(level) | 描述 |
|---|---|
| DEBUG | 最详细的日志信息,典型应用场景是 问题诊断 |
| INFO | 信息详细程度仅次于DEBUG,通常只记录关键节点信息,用于确认一切都是按照我们预期的那样进行工作 |
| WARNING | 当某些不期望的事情发生时记录的信息(如,磁盘可用空间较低),但是此时应用程序还是正常运行的 |
| ERROR | 由于一个更严重的问题导致某些功能不能正常运行时记录的信息 |
| CRITICAL | 当发生严重错误,导致应用程序不能继续运行时记录的信息 |
如何输出日志到文件里面
from logging.handlers import RotatingFileHandler
file_log_handler = RotatingFileHandler("logs/log", maxBytes=1024 * 1024 * 100, backupCount=10)
logging.getLogger().addHandler(file_log_handler)
# 这样就可以输出日志了
介绍下
class logging.handlers.RotatingFileHandler(filename, mode='a', maxBytes=0, backupCount=0, encoding=None, delay=False)
您可以使用maxBytes 和backupCount 值来允许文件以预定大小进行rollover。当要超过大小时,将关闭文件并静默打开一个新文件以进行输出。只要当前日志文件的长度接近maxBytes ,就会发生Rollover ;但如果maxBytes 或backupCount中的任何一个为零,则永远不会发生Rollover ,因此您通常希望将backupCount 设置为至少1,并且maxBytes为非零。当backupCount 非零时,系统将通过将扩展名‘.1’, ‘.2’ 等附加到文件名来保存旧的日志文件。
如何输出对应日志
import logging
logging.debug("debug_msg")
logging.info("info_msg")
logging.warning("warning_msg")
logging.error("error_msg")
logging.critical("critical_msg")
这样输出出来的日志,可以输出时间,执行文件文件名
本文深入探讨了Python中logger模块的使用方法,包括基本配置、日志级别的设定、日志输出到文件的功能以及如何利用RotatingFileHandler实现日志文件的滚动。通过实例展示了不同日志级别的应用,为开发者提供了高效的问题诊断和系统监控手段。
2438

被折叠的 条评论
为什么被折叠?



