Geek Logbook

Tech sea log book

Logging in a file to avoid print statements

A video that was enlightening

We need to avoid the misuse of the print statements once we master the basic tools and ideas about programming in particular and software developer in general. So, here there are some notes about loggers.

Loggers have five levels, by critically:

  1. Critical
  2. Error
  3. Warning
  4. Info
  5. Debug

By default we typically set info and above. This information, and other I’m going to write down comes from the following video:

This is interesting because besides the fact that he encourages us to don’t use print statements. Something that it’s really difficult to eradicate from our, or at least my practices, he shows us a interesting way to log the information: With a logging config in a YAML file. You can read it directly on the Joe Freeman’s post entrance: Log! Don’t Print! Use the Python logging library

What the python documentation say about logging?

If you dig into the Python documentation you can see another interesting things besides the ones I talked here: Logger In python – First Approach

If you want to:

  • Display console output for ordinary usage -> print()
  • Report events that occur during normal operation – > logging.info()
  • Issue a warning -> warnings.warn()
  • Report an error -> Raise an exception
  • Report suppression of an error without raising an exception – > logging.error(), logging.exception() or logging.critical()

You can write the logs in a file:

import logging

logging.basicConfig(filename='example.log', encoding='utf-8', level=logging.DEBUG)
logging.warning("Ey, this is a logging warning")
logging.error("Ey, this is a logging error")
logging.debug('This message should go to the log file')
logging.info('So should this')
logging.warning('And this, too')
logging.error('And non-ASCII stuff, too, like Øresund and Malmö')

I’m following the Python’s documentation: Logging to a File

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *.

*
*
You may use these <abbr title="HyperText Markup Language">HTML</abbr> tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>