[Python] Why is my log file empty in my python script?

Discussão em 'Python' iniciado por Stack, Setembro 11, 2024.

  1. Stack

    Stack Membro Participativo

    I am trying to output the errors, if there are any in the code, and also the results of the stored procedure in my log file. The log file is created but it is empty. I have other logging in my code that logs errors but nothing is showing up. Here is my code:

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


    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(__name__)
    logger.setLevel(logging.DEBUG)

    # Rotating log setup
    log_filename = f"E:\\file\\path\\here\\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):
    logger = logging.getLogger()
    logger.setLevel(logging.INFO)
    connection = None
    try:
    config=LogOutput.get_config(self)
    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 = """
    select *`
    from table
    """
    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:
    logging.exception(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()


    So setup_logger is the function that is writing the log file.

    Continue reading...

Compartilhe esta Página