/
šŸ“š
Python: Using the logging lib
Search
Duplicate
Try Notion
šŸ“š
Python: Using the logging lib
In this post we are going to use theĀ logging libĀ to write messages, inĀ productionĀ we are going to write to aĀ Rotating FileĀ and inĀ developmentĀ we are going to write to theĀ console.
Create a logger.py file
The first step is to create a logger file, in my case iā€™m going to create it in theĀ srcĀ folder:
mkdir src cd src touch __init__.py touch logger.py
Shell
And letā€™s create aĀ main.py file in the parent folder to test theĀ logger.
cd .. touch main.py
Shell
Code the logger
Letā€™s read theĀ environmentĀ variables to determinate if we are inĀ developmentĀ and if the user wants to use a specificĀ folderĀ to store theĀ logs.
If we are working onĀ developmentĀ we are going to use a logging handler that writes to theĀ consoleĀ and we want to log everything aboveĀ DEBUGĀ level.
In production we just want to log the messages aboveĀ INFOĀ and directly to aĀ file.
In theĀ src/logger.pyĀ file add this:
import logging import os from logging.handlers import RotatingFileHandler ENV = os.getenv('ENV', 'DEV') LOG_FOLDER = os.getenv('LOG_FOLDER', '/tmp') logger = logging.getLogger() if ENV == 'DEV': # Console logger handler = logging.StreamHandler() formatter = logging.Formatter('[%(asctime)s][%(levelname)s]: %(message)s', '%H:%M:%S') level = logging.DEBUG else: # Rotating file handler handler = RotatingFileHandler(f'{LOG_FOLDER}/my_app.log', maxBytes=2000, backupCount=10) formatter = logging.Formatter('%(asctime)s,%(msecs)03d;%(levelname)s;%(message)s', '%Y-%m-%d %H:%M:%S') level = logging.INFO logger.setLevel(level) handler.setFormatter(formatter) logger.addHandler(handler)
Python
src/logger.py
In theĀ main.py file add this:
import time from src.logger import logger if __name__ == '__main__': logger.info('Info message') time.sleep(0.1) logger.debug('Debug message')
Python
main.py
NOTE: you can use the logger anywhere just importingĀ loggerĀ fromĀ src.logger
Test the logger:
Run theĀ main.pyĀ file without any option and the output should be like this:
$ python main.py [13:11:51][INFO]: Info message [13:11:51][DEBUG]: Debug message
Shell
Run the main.pyĀ file setting the environment asĀ production, the log will be in aĀ fileĀ and without theĀ debugĀ info.
$ ENV=PROD python main.py $ cat /tmp/my_app.log 2021-05-16 13:13:20,353;INFO;Info message
Shell