

Scenario 2: I have an application, single/multi-threaded that is using several libraries and I want to get some logging done When not to use it: When you need fine-grained control on how logging is performed or any multi-process application. Minimal usage of external libraries and you do not require too much control on how logging is performed. When to use it: Simple applications where you just need to get some logging done without too much fuzz. Which will change the output messages in your log files to: 17:05:29,686 - Just entered the function 17:05:29,790 - Just after the sleep 17:05:29,790 - Attempted division by zero. In case you would like to also display the time, simply add the format as follows: logging.basicConfig(filename='my_log_file.log', format='%(asctime)s - %(message)s', level=logging.INFO) This will result in the following output on our my_log_file.log file: INFO:root:Just entered the function INFO:root:Just after the sleep ERROR:root:Attempted division by zero Traceback (most recent call last): File "/xxxx/simple_application.py", line 14, in my_app_logic res = 1 / 0 ZeroDivisionError: division by zero Then use it as follows: import logging from time import sleep def setup_logger(): logging.basicConfig(filename='my_log_file.log', level=logging.INFO) def my_app_logic(): ("Just entered the function") sleep(0.1) ("Just after the sleep") try: res = 1 / 0 except ZeroDivisionError: logging.exception("Attempted division by zero") if _name_ = '_main_': setup_logger() my_app_logic() Configure it as follows: import logging logging.basicConfig(filename='my_log_file.log',level=logging.INFO) The fastest way to get logging done for simple applications is to use logging.basicConfig, it will create a StreamHandler (and a FileHandler if we specify the filename) and add it to the ROOT logger. Scenario 1: I have a simple application, I need to setup some basic logging to file Without further ado, let’s just dive straight into it and get some quick recipes to get your python application logging in no time. Formatters: They make your logs appear in the way you want them, in a specific format you can define.Handlers: They take your log messages and they route them to specific locations, such as files or console.Loggers: Main actors that provide several methods to allow runtime logging from your applications.Before we get started, just some basic terminology for python logging: In this article, we’ll try to figure out quick recipes to get productive with logging. Logging is important for your understanding of applications behavior, and to help IT operations to have a dedicated control panel to quickly monitor and analyze application issues.
