Psycopg2 Error Messages

All,

I am writing error messages to a log file, and it gets quite large, because these are errors on unique constraints in the database. This is normal, and in fact, he wants it to be so, my question is: how can I avoid duplicating key errors in the log file every time they happen?

        except Exception as err:
                logger.error('FunctionName: %s',  err)

Thanks Adam

+5
source share
1 answer

Psycopg passes the PostgreSQL error code along with an exception to the attribute pgcode: you can verify that the error is actually associated with a unique violation and does not allow them to be written. For instance:

try:
    cursor.execute("...")
except psycopg2.IntegrityError as err:
    if err.pgcode != '23505':
        logger.error('FunctionName: %s',  err)
except Exception as err:
    logger.error('FunctionName: %s',  err)
+7
source

All Articles