Python 不记录我的存储过程错误和成功消息

问题描述 投票:0回答:1

这是我的代码:

import os 
import json
import platform
import pymysql as pm
from datetime import date
import logging
from logging.handlers import TimedRotatingFileHandler
import logger

class LogOutput:
    env=None
    config=None

    def __init__(self, env_filename):
        self.env=env_filename
        self.config=self.get_config()
        

    def get_config(self):
        with open(self.env) as file_in:
            return json.load(file_in)
        
    def is_Windows():
        if "win" in (platform.system().lower()):
            return True
        else:
            return False       

    def setup_logger():
        logger = logging.getLogger()
        logger.setLevel(logging.DEBUG)
        
        # Rotating log setup
        log_filename = f"E:\\here\\log\\file\\log-{date.today()}.log"
        file_handler = TimedRotatingFileHandler(log_filename, when="midnight", backupCount=7)
        file_handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
        
        console_handler = logging.StreamHandler()
        console_handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
        
        logger.addHandler(file_handler)
        logger.addHandler(console_handler)
        return logger 
    setup_logger()

    def DB_connection(self):
        connection = None
        logger = logging.getLogger()
        logger.setLevel(logging.INFO)
        try:
            config = self.get_config()
            host=config["log-output"]["database-secrets"]["host"]
            port=config["log-output"]["database-secrets"]["port"]
            database=config["log-output"]["database-secrets"]["db"]
            username=config["log-output"]["database-secrets"]["username"]
            password=config["log-output"]["database-secrets"]["password"]

            # Load the configuration from DB_conn_info_local.json
            config_file_path = os.path.join(os.path.dirname(__file__), 'DB_conn_info_local.json')
            with open(config_file_path) as config_file:
                config = json.load(config_file)

            connection = pm.connect(user=username,password=password,host=host,port=port,database=database)
    
            logger.info("Successfully connected to database")

        except Exception as e:
            logger.error("Unable to connect to database: %s", str(e))
        
        return connection
    
    def logging_sp(self):
        logging_sp_query = """
        stored procedure code here
        """
        cnxn = self.DB_connection()
        if cnxn is None:
            logging.error("Database connection is None. Cannot proceed.")
            return  # Exit here if there's no valid connection
            
        with cnxn.cursor() as cur:
            try:
                cur.execute(logging_sp_query)
            except Exception as e:
                logger.error("Unable to execute query: %s", e)        
            else:
                cnxn.commit()
        cnxn.close()  # Close the connection 


def main():
    cwd=os.getcwd()
    if "win" in (platform.system().lower()):
        vfc=(cwd+"\\DB_conn_info_local"+".json")
    else:
        vfc=(cwd+"/DB_conn_info_local"+".json")
    ve=LogOutput(vfc)
    ve.logging_sp()
   
if __name__ == "__main__":
    main()

未写入日志文件的部分在这里:

with cnxn.cursor() as cur:
    try:
        cur.execute(logging_sp_query)
    except Exception as e:
        logger.error("Unable to execute query: %s", e)        
    else:
        cnxn.commit()
cnxn.close()  # Close the connection 

但我不知道为什么。我尝试使用

logger.error
logger.info
logging.error
,并且我使用特定异常
OperationalError
作为
pm.err.OperationalError
而不是
Exception
,并且它没有读取它。这很奇怪,因为这部分代码
logger.info("Successfully connected to database")
也被写入日志和
logging.info("Unable to connect to database: %s", str(e))
部分,但不是
with
语句中的部分。

python logging error-handling
1个回答
0
投票

记录器未在您的

logging_sp
函数上定义。

© www.soinside.com 2019 - 2024. All rights reserved.