How to use the logging module in Python

The logging module in Python has five different log levels as standard, which can be used depending on the type and severity of the program error.

The python logging level (with increasing severity) are “DEBUG”, “INFO”, “WARNING”, “ERROR” and “CRITICAL”.

  • To use the logging module, first import it with the » import logging « command .
  • You can now create a log with » logging.error (” Test “) «, for example . The corresponding log level (error) and the actual log are now displayed in the console (python logging to console).
    You can create logs of other levels in the same way: Change, for example, ” logging.error () ” to ” logging.debug () “.
  • By default, however, debug and info logs are not displayed in the console.

Python logging example

Read: How to run Python on Ubuntu 20.04

Configure the python logging module

With the command » logging.basicConfig () « you can make further settings on the logging module.

  • For example, if you want the debug and info messages to be displayed in the console, you can change this with » logging.basicConfig (level = logging.DEBUG) «.
  • The log can also be output as a file: With the “filename” parameter you specify the name of the file. The write mode is set with “filemode”: We recommend “a” for “Append” or “w” for “Write”. Finally, “format” can be used to format the output of the text in the file and shell.
    An example for this would be » logging.basicConfig (filename = ‘test.log’, filemode = ‘a’, format = ‘% (name) s -% (level name) s -% (message) s’) «.
  • When it comes to formatting the output, Python offers many other functions. For example, you can use the current time through ” % (asctime) s ” in the format parameter. Just take a look at the documentation .

Read: 6 Reasons why you Should Learn Python 

Python logging exceptions

Logging is particularly helpful in connection with exceptions.

  • To prevent the program from crashing in the event of an exception, you can add the command ” try: ” and write below it the commands that could cause exceptions.
  • If an exception is generated, the commands listed under ” except: ” are executed . So that you can later understand what happened at this point, you can log the exception with » logging.error (” Exception “, exc_info = True) “.

If you like the content, we would appreciate your support by buying us a coffee. Thank you so much for your visit and support.


Marianne elanotta

Marianne is a graduate in communication technologies and enjoys sharing the latest technological advances across various fields. Her programming skills include Java OO and Javascript, and she prefers working on open-source operating systems. In her free time, she enjoys playing chess and computer games with her two children.

Leave a Reply