You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何禁用Python MySQL Connector的日志输出?

禁用MySQL Connector/Python 8.0.31的日志输出

我正在使用8.0.31版本的MySQL Connector/Python,该库会向日志/终端输出内容,出于安全和清晰度考虑,我希望禁用它的日志功能。

日志示例

2022-12-30 21:03:59,287 # _do_auth(): user: test
2022-12-30 21:03:59,287 # _do_auth(): self._auth_plugin: mysql_native_password
2022-12-30 21:03:59,287 # _do_auth(): user: test
2022-12-30 21:03:59,288 # _do_auth(): password: test
2022-12-30 21:03:59,288 package: mysql.connector.plugins
2022-12-30 21:03:59,288 plugin_name: mysql_native_password
2022-12-30 21:03:59,290 AUTHENTICATION_PLUGIN_CLASS: MySQLNativePasswordAuthPlugin
2022-12-30 21:03:59,290 new_auth_plugin: mysql_native_password
2022-12-30 21:03:59,292 package: mysql.connector.plugins
2022-12-30 21:03:59,292 plugin_name: caching_sha2_password

数据库连接代码

import mysql.connector
...
self.sql_con = mysql.connector.connect(host=self._Host,
                                        database=self._DataBase,
                                        user=self._User,
                                        password=self._Password,
                                        auth_plugin='mysql_native_password')

项目日志配置代码

import logging
from logging.config import fileConfig
...

if LogToFile == True:
    self.path = "./logs/"
    if DebugMode == False:       
        self.filename = "app"
        self.save_old()
    else:
        self.filename = "SoftwareTestLog"
   
    logging.basicConfig(filename=self.path+self.filename+'.log', filemode='w', 
                        level=logging.DEBUG,format='%(asctime)-8s %(message)s')   
    console = logging.StreamHandler()
    console.setLevel(logging.DEBUG)
    formatter = logging.Formatter('%(asctime)-8s %(message)s')
    console.setFormatter(formatter)
    logging.getLogger('').addHandler(console)                     
else:     
    logging.basicConfig(level=logging.DEBUG,format='%(asctime)-8s %(message)s')   
            
self.mylogger = logging.getLogger(__name__)
...
myLogger.info("doing logs blabla")

我查阅了官方API文档,只在ShellAPI中找到log()函数,请问如何禁用MySQL Connector的日志输出?


解决方案

MySQL Connector/Python的日志是基于Python标准logging模块输出的,你可以通过调整它的日志级别来屏蔽这些输出:

方法1:屏蔽指定模块的日志

在你的项目日志配置代码执行完成后,添加以下代码:

# 仅允许mysql.connector输出严重错误日志,屏蔽调试/信息类日志
logging.getLogger('mysql.connector').setLevel(logging.CRITICAL)

如果需要彻底屏蔽所有日志(包括严重错误),可以设置一个高于所有内置级别的数值:

logging.getLogger('mysql.connector').setLevel(100)  # CRITICAL默认级别为50,100高于所有内置级别

方法2:批量屏蔽所有MySQL相关子模块

如果你的日志中还出现了mysql.connector.plugins这类子模块的输出,直接对整个mysql命名空间设置级别,一次性覆盖所有子模块:

logging.getLogger('mysql').setLevel(logging.CRITICAL)

这样设置后,MySQL Connector的调试日志就不会再干扰你的终端或日志文件,同时完全不影响你自己项目的日志功能。


内容的提问来源于stack exchange,提问作者theLastDay

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 05:10:20