Sunday, October 8, 2017

Logging in Python using dynamic log file

Sometimes we need to send logs to a log file supplied dynamically. The standard mechanism of the python is to set the file as part of configuration. I will put down a way to do this.

Let's write a python file which captures the initialization of logger.

Let the file name be init-log.py



import os
import sys
import logging

# Declare the log variable
log = None

# initialize the log. If the level is not passed than info becomes the
# default log level
def initialize_log(log_file_name, level = logging.INFO):

    # Use the same variable as declared globally
    global log

    # Get the actual logger and set various properties
    # including file handler and formatter
    log = logging.getLogger()
    log.setLevel(level)
    log_file_handler = logging.FileHandler(log_file_name)
    log_formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    log_file_handler.setFormatter(log_formatter)
    log.addHandler(log_file_handler)

# function to return the log instance
def get_logger():

    return log

Now wherever you want to do the logging, just call the get_logger method

For example in test.py

import logging
from init-log import get_logger

get_logger().info("Logging happens")

To initialize the logger call the initialize_log method in the begininig. This can be done in the main entry point of the program.

No comments:

Post a Comment