logging Python

Introduction

In this article you can study examples of using the logging

Example

Info and Debug are disabled by default. It is easy to see this by running a script with the following content

import logging logging.critical("Critial Log") logging.error("Error Log") logging.warning("Warning Log") logging.info("Info Log") logging.debug("Debug Log")

python log_example.py

CRITICAL:root:Critial Log ERROR:root:Error Log WARNING:root:Warning Log

Enable Debug

If you now need to raise the detail level of the log, you can do it with logging.basicConfig

import logging logging.basicConfig(level=logging.DEBUG) logging.critical("Critial Log") logging.error("Error Log") logging.warning("Warning Log") logging.info("Info Log") logging.debug("Debug Log")

python log_example.py

CRITICAL:root:Critial Log ERROR:root:Error Log WARNING:root:Warning Log INFO:root:Info Log DEBUG:root:Debug Log

Log to a file

import logging logging.basicConfig(filename='example.log', level=logging.DEBUG) logging.critical("Critial Log") logging.error("Error Log") logging.warning("Warning Log") logging.info("Info Log") logging.debug("Debug Log")

python log_example.py

Nothing is output to the terminal anymore, but a file has appeared example.log

cat example.log

CRITICAL:root:Critial Log ERROR:root:Error Log WARNING:root:Warning Log INFO:root:Info Log DEBUG:root:Debug Log

Formatting

You can set the log format you need with logrecord-attributes

# log_example.py import logging def main() -> None: logging.basicConfig( filename="example.log", level=logging.DEBUG, format="%(asctime)s %(levelname)s: %(message)s", datefmt="%Y-%m-%d %H:%M:%S", ) logging.critical("Critial Log") logging.error("Error Log") logging.warning("Warning Log") logging.info("Info Log") logging.debug("Debug Log") if __name__ == "__main__": main()

python log_example.py
cat example.log

2026-11-17 22:15:47 CRITICAL: Critial Log 2026-11-17 22:15:47 ERROR: Error Log 2026-11-17 22:15:47 WARNING: Warning Log 2026-11-17 22:15:47 INFO: Info Log 2026-11-17 22:15:47 DEBUG: Debug Log

Pass the log level as a string

The log level is often specified somewhere in the config. So it will be read and passed to the function as a string rather than as an object like logging.critical … logging.debug

In this case you need to use logginb.getLevelName()

# log_example.py import logging def main(log_level) -> None: level = str(log_level).upper() logging.basicConfig( level=logging.getLevelName(level), format="%(asctime)s %(levelname)s: %(message)s", datefmt="%Y-%m-%d %H:%M:%S", ) logging.critical("Critial Log") logging.error("Error Log") logging.warning("Warning Log") logging.info("Info Log") logging.debug("Debug Log") if __name__ == "__main__": main("Error")

python log_example.py

2026-11-17 22:15:47 CRITICAL: Critial Log 2026-11-17 22:15:47 ERROR: Error Log

Article author: Andrei Olegovich