Python: use logging module - how it works
Related Videos: Logging in Python || Learn Python Programming (Computer Science) (May 2024).
With the logging module in Python, you can program Python applications more easily and errors can be output better. We show you how this works in this practical tip.
Python: use logging module
The logging module has five different log levels as standard, which can be used depending on the type and severity of the program error. The log levels (with increasing severity) are "DEBUG", "INFO", "WARNING", "ERROR" and "CRITICAL".
- To use the logging module, first import it using the “ import logging ” command.
- You can now, for example, create a log with » logging.error (" Test ") «. The corresponding log level (error) and the actual log are now displayed in the console. You can create logs of other levels in the same way: For example, change » logging.error () « to » logging.debug () «.
- By default, however, debug and info logs are not displayed in the console.
Python: configure 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) «.
- Furthermore, the log can also be output as a file: Use the "filename" parameter to specify the name of the file. With "filemode" the writing mode is determined: "a" for "Append" or "w" for "Write" is recommended. Finally, "format" can be used to format the output of the text in file and shell. An example of 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 numerous other functions. For example, you can use the current time through " % (asctime) s " in the format parameter. Just take a look at the documentation.
Exceptions and logging
Logging in connection with exceptions is particularly helpful.
- To prevent the program from crashing on 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 that are 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) «.
More tips about Python in the CHIP guides
Tip: You can find further programming tutorials on our Python programming language topic page. There we show you, for example, how to deal with exceptions and errors in Python.