Python: Output the log with logging module

CLI

It is general to export the log from the batch script which is executed periodically. The log is also useful to analyze the problem.

You may insert the special log for debug to explore the reason of bug.

The log is base facility to explore the reason of problem and recover from it.

You can output the log from Python script with logging module.

スポンサーリンク

Simple Logging

Most simple logging code is following.

import logging

logging.basicConfig(level=logging.INFO)
logging.info("Most Simple Log. The Value is %d.", 10)

Execute this script, the following log will be output.

$ python3 demo.py

INFO:root:Most Simple Log. The Value is 10.

How to output the log

You can output the log by following functions. You need to select the function for appropriated logging level.

  • info()
  • warning()
  • error()
  • critical()
  • exception()
  • debug()

The argument of these functions is a formatted string.

The Logging Levels

The importance of each logs are different. The logging level is an importance.

For example, in production environment, the log is not needed which is output by debug() function. However, in development environment, it is an important for the developer.

The output logging level can be specified with the code.

Change the output logging level

The minimum output logging level is changed with level argument of the basicConfig() method. In this sample code, the logging level of the output is INFO or greater.

The logging levels are following. This list is sorted in descending order.

  • CRITICAL
  • ERROR
  • WARNING
  • INFO
  • DEBUG
  • NOTSET

The DEBUG is lower than INFO, the DEBUG level log is not output if the INFO level is specified by basicConfig() method.

import logging

logging.basicConfig(level=logging.INFO)
logging.info("This is an INFO level log.")
logging.debug("This is an DEBUG level log.")

Execute this script, following log will be output.

INFO:root:This is an INFO level log.

If you change the minimum logging level to DEBUG, the log by `debug()` method also output.

import logging

logging.basicConfig(level=logging.DEBUG)
logging.info("This is an INFO level log.")
logging.debug("This is an DEBUG level log.")
INFO:root:This is an INFO level log.
DEBUG:root:This is an DEBUG level log.

The Destination

The default logging destination is the standard error (stderr). If you keep it as a record, it is better to output it to a file.

To change the destination of the logging, specify the file path to filename argument of the basicConfig() method.

import logging

logging.basicConfig(level=logging.INFO, filename="example.log")
logging.info("This is an INFO level log.")

If you execute this script, the example.log file will be created into the current directory. If the file is already exist, the log will be append to the end of the file.

Output the date and time

It is necessary the date and the time to make the log to be useful. When it was executed? How long it took? The output date and time is important information..

To output the date and time into the log, change the format of the log record to contain the date and time.

You can change the format with format argument of the basicConfig() method.

import logging

logging.basicConfig(level=logging.INFO, filename="example.log",
                    format="%(asctime)s %(levelname)s:%(name)s:%(message)s")
logging.info("This is an INFO level log.")

This code output the date and the time at the begging of the log record.

2020-03-10 15:41:22,772 INFO:root:This is an INFO level log.

The %(asctime)s will be replaced with the output date and time.

This code is same format as default but the date and time is output.

The %(levelname)s will be the logging level name, the %(name)s will be the logger name and the %(message)s will be replaced with the logging string.

This code doesn’t use the named logger, so the logger name is root.

The Time to call basicConfig method

The logging module of the Python is a thread-safe. You can use it in any thread.

However, you should call basicConfig() method in the main thread, and call it as soon as possible since the code is executed.

スポンサーリンク
最新情報をチェックしよう!
>現役のプログラマーが書くプログラミング情報

現役のプログラマーが書くプログラミング情報

日々の開発の中での学びや分かったこと、調べたことなどを書いていくブログです。

CTR IMG