python logger日志功能使用

示例: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格式输出,可以直接输出

FormatDescription
filenameSpecifies that a FileHandler be created, using the specified filename, rather than a StreamHandler.
filemodeIf filename is specified, open the file in this mode. Defaults to 'a'.
formatUse the specified format string for the handler.
datefmtUse the specified date/time format, as accepted by time.strftime().
styleIf format is specified, use this style for the format string. One of '%', '{' or '$'for printf-style, str.format() or string.Template respectively. Defaults to '%'.
levelSet the root logger level to the specified level.
streamUse the specified stream to initialize the StreamHandler. Note that this argument is incompatible with filename - if both are present, a ValueError is raised.
handlersIf 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")

这样输出出来的日志,可以输出时间,执行文件文件名

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值