Sunday, 20 October 2019

Python Logging

For those of us that start a program with "print" statements to get our bearings, the Python logging library is a drop-in replacement. After creating the logger, you can replace "print" statements with logger.debug('same text as before') or use suitable levels from debug, info, warning, error, and critical. You quickly get logging that can be configured to different levels you can use from debugging during development and clear output for the program running. There's also a built-in handler on logging exceptions to cleanly log exception info during exception handling. The library and cookbook are both clear and illustrative so check these links out:

Python 3 Library - Logging

Python 3 Logging Cookbook

I mentioned shell logging last time here:

I'm a Logger and I'm Okay

The other tool I use all the time in Python is the "assert" call which raises an error with message given. For example to sanity check the resulting size of a blob is matching your file size:

# sanity check the resultant blob is the same size as what's in the database
assert (os.path.getsize(outpath) == len(imgblob)), "File size %d does not match blob size %d for image %d in %s saved to %s" % (os.path.getsize(outpath), len(imgblob), imgid, args.table, args.archivepath)
There's every opportunity to properly handle program output and errors.

Ciao


No comments:

Post a comment

Popular Posts