Logging Errors to a PostgreSQL table from Python 3 using Psycopg2

Let's create a database table to store errors:

CREATE TABLE errors (
    id serial NOT NULL,
    message character varying(1000),
    exception_message character varying(1000),
    exception_stacktrace character varying(4000),
    date_entered timestamp with time zone DEFAULT now() NOT NULL
);

Creating the id column with the serial type tells PostgreSQL to create a sequence named errors_id_seq (this is similar to AUTO_INCREMENT in MySQL. We can now insert without specifying an ID; the sequence will be incremented, and the value used).

Here's some Python code to insert into the table when an exception occurs:

import psycopg2
import traceback


def log_error(message, exception):
    try:
        conn_string = 'dbname=mydb user=myuser host=localhost' + \n                      ' port=5432 password=secret sslmode=require'
        db = psycopg2.connect(conn_string)

        exception_message = str(exception)
        sql = """INSERT INTO errors (message, exception_message, exception_stacktrace) VALUES (%s, %s, %s)"""
        cursor = db.cursor()
        cursor.execute(sql, (message[:1000], exception_message[:1000], traceback.format_exc()[:4000]))
        db.commit()
    except Exception as ex:
        db.rollback()
        raise Exception('An error occurred while logging an error: ' + str(ex))

try:
    s = 1 / 0
except Exception as ex:
    log_error('An error occurred while dividing two numbers.', ex)

Using the traceback module helps format the stack trace (readability).

Comments

Leave a comment

What color are green eyes? (spam prevention)
Submit
Code under MIT License unless otherwise indicated.
© 2020, Downranked, LLC.