Skip to content

Instantly share code, notes, and snippets.

@JimFawkes
Created January 28, 2019 06:02
Show Gist options
  • Save JimFawkes/e5f767288e6d8e2df8fa53b5862db9d6 to your computer and use it in GitHub Desktop.
Save JimFawkes/e5f767288e6d8e2df8fa53b5862db9d6 to your computer and use it in GitHub Desktop.
Brief summary of the packages: better-exceptions and loguru.

Better Exceptions and Loguru

A Metis investigation by Moritz Eilfort January 28th, 2019

If you are looking for a good introduction on how to handle exceptions in python, take a look at realpython.com.

Better Exceptions - Pretty and useful exceptions in Python, automatically.

Better Exceptions is a package to improve the python Traceback. It adds syntax highlighting and the actual values that were passed to the problematic portion of the code. To use this package, install it and set the environment variable BETTER_EXCEPTIONS=1.

# Set the variable for the environment of the following function call only.
BETTER_EXCEPTIONS=1 python your-code.py

# OR

# Set the variable for the entire session.
export BETTER_EXCEPTIONS=1
python your-code.py

# OR add it to your .bashrc or .profile etc.

For more information see better-exceptions or ask me!

Loguru - Python logging made (stupidly) simple

Loguru is an alternative to pythons built in logging module. It significantly reduces the amount of configuration necessary to write the first log.

You can install loguru via: pip install loguru. A short tour of some of the highlights, can be found on GitHub and the full documentation here.

To get started, simply add the following to your code:

from loguru import logger

# Write your first log message:
logger.info("My first log entry!")

There are many configuration options for loguru and they are all very simple. Here are a few things I like to do (not necessarily all the time).

from loguru import logger

# Get the current filename
# If your python file is called project-luther.py, your log file will be stored
# in the directory logs/ with the name project-luther.log
_log_file_name = __file__.split("/")[-1].split(".")[0]
logger.add('logs/{_log_file_name}.logs')

# Filter different log levels into different files:
logger.add('logs/success.log', level='SUCCESS')
logger.add('logs/error.log', level='ERROR')

# To reduce the size you might also want to consider all or one of the following:
logger.add('logs/filename.log', rotation="12:00", retention='10 days', compression="zip")

"""This will:
    - create a new file everyday at 12:00 am
    - delete the files after 10 days
    - compress the files to a .zip file
"""

Note: There are multiple log levels:

  • INFO
  • DEBUG
  • WARNING
  • ERROR
  • EXCEPTION
  • TRACE
  • SUCCESS

And you can add your own (e.g. RESULTS).

If you have any further questions, please do not hesitate to ask me.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment