Python Logging Setup


Date: 2021-09-25
Language: Python
Code Link:

Background

Needed a way to log messages for my script

Problem

The logging needed to do the things below:
  • Log messages to a file and also steaming
  • Two different functions had to log to two different log files.

  • Solution

    import logging
    TS = datetime.now().strftime('%Y%m%d_%H%M%S')
    formatter = logging.Formatter(
      '%(asctime)s, %(levelname)s: %(message)s')
    
    def setup_logger(name, log_file, level=logging.INFO):
        file_handler = logging.FileHandler(log_file)
        file_handler.setFormatter(formatter)
    
        stream_handler = logging.StreamHandler()
        stream_handler.setFormatter(formatter)
    
        logger = logging.getLogger(name)
        logger.setLevel(level)
        logger.addHandler(file_handler)
        logger.addHandler(stream_handler)
        return logger
    
    log_level = logging.DEBUG
    logger = setup_logger('exmaple_log_name_1', f'exmaple_log_file-{TS}.log', log_level)
    logger.info(f'Example Info Log')

    Result
    WIP