Let’s Talk About (Python) Logging

How Python Handles Logging

Life Hacking Your Logging Tools

Common Coding Your Logger

Make Your Own Handlers

class MyNewHandler(logging.Handler):  # inherit from Handler class
def __init__(self, special_args):
logging.Handler.__init__(self) # run parent __init__ class
## Do custom setup stuff
## Save special_args, setup files, etc
def emit(self, record): # override Handler's `emit` method
## Do log-time actions here
## Send to webhook, send to file, write an email, whatever

Make Your Own Levels

logging.addLevelName(int_custom_level, 'ALERT')
def alert(self, message, *args, **kwargs):
"""http://stackoverflow.com/a/13638084"""
if self.isEnabledFor(int_custom_level):
self._log(int_custom_level, message, args, **kwargs)
logging.Logger.alert = alert

Embracing Best Practices

Library Loggers are Null Loggers

import loggingDEFAULT_LOGGER = logging.getLogger('NULL')
DEFAULT_LOGGER.addHandler(logging.NullHandler())

Only Create Loggers In Main

Capture Those Exceptions

except Exception as err_msg:
## Bad Logging ##
logging.error('Things went wrong: {0}'.format(err_msg))
## "Things went wrong: "
## Better Logging ##
logging.error('Things went wrong: {0}'.format(repr(err_msg)))
## "Things went wrong: Execption_class message"
## Best Logging ##
logging.error('Things went wrong', exc_info=True)
## "Things went wrong <stack_trace>"

Death To Print(), Long Live Logger

--

--

--

#eveonline space-economist #tweetfleet. Electrical Engineer, python #devfleet, graphmaker Twitch: eveprosper

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

“STEPN” - Your Steps are Worth more than what you think💯

Fixed: Dont have libtensorflow_framework.so

TexLive remote repository version mismatch (2017<2021)

NumPy for Data Science Interviews

NumPy for Data Science Interviews

When NO Name is the Best Name

How my unit tests went from 42 seconds to 1.8 seconds

Automate Test Scenario Life Cycle

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Lockefox

Lockefox

#eveonline space-economist #tweetfleet. Electrical Engineer, python #devfleet, graphmaker Twitch: eveprosper

More from Medium

Singleton pattern in python libraries

Exceptions in Python

Python Advance Level — Object Oriented Programming(Part I)

How to connect to a MySQL database with C# and WinForms.