Search code examples
pythonloggingpython-logging

Custom Logging Module not working in Python


I want to use same logging mechanism in all python scripts. Developed a class below class:

File Name: ms_logging.py

import logging

class ms_logging:
        @staticmethod
        def logging():
            logging.basicConfig(
                level=logging.DEBUG,
                format='%(asctime)s | %(levelname)s | [%(filename)s:%(lineno)d] | %(message)s',
                datefmt="%Y-%m-%d %H:%M:%S",
                filename="/home/etl_developer/ms_de/log_directory/master_log_file.log"
                )
            logger = logging.getLogger()
            return logger

Then I'm trying to load that module in another Python script and use that logging function to insert logs. The purpose of this is to write one configuration and use them in all Python scripts to have a centralized logs

Here is the code:

import sys
sys.path.append('/home/etl_developer/ms_de/module_library/')
from ms_logging import ms_logging

log = ms_logging.logging()
log.error('test')
log.info('hello there')

This above code doesn't give any error but logging is also not working. The log file is empty.

What is the mistake that I'm making? Any clues would be very much appreciated.


Solution

  • Why not simply do (ms_logging.py):

    import logging
    
    logging.basicConfig(
        level=logging.DEBUG,
        format='%(asctime)s | %(levelname)s | [%(filename)s:%(lineno)d] | %(message)s',
        datefmt="%Y-%m-%d %H:%M:%S",
        filename="/home/etl_developer/ms_de/log_directory/master_log_file.log"
    )
    log = logging.getLogger()
    

    and use it:

    from ms_logging import log
    
    log.error('test')
    log.info('hello there')
    

    it seems easier than setting up the entire logging machinery for each logging statement..?