admin管理员组

文章数量:1123091

I am using 'logging' module to log my info,error and warning messages. However to print the help message, I am removing the logger handler by removeHandler otherwise main.INFO gets printed with the help messages. So I am using 'print' function instead for that.

Is there a way to use logger for help messages as well without the main.INFO getting printed in it ?

Below is my code :

import logging  


def show_help():
    'This is help messages'
    help_msg = '''\n
    The valid options:\n
    [-src_path : <option to provide src_path ]
    [-dest_path : <option to provide dest_path ]
    
    '''
    print(help_msg)
    

def define_logger():
    log_path = "/usr/scripts/logs/my_script.log"
    # Create a custom logger
    logger = logging.getLogger(__name__)
    logger.setLevel(logging.DEBUG)

    # Create a console handler
    f_handler = logging.FileHandler(log_path)
    con_handler = logging.StreamHandler()
    con_handler.setLevel(logging.DEBUG)

    # Create a formatter and add it to the handler
    con_format = logging.Formatter('%(name)s - %(levelname)s - %(message)s')
    con_handler.setFormatter(con_format)
    f_format = logging.Formatter('%(name)s - %(levelname)s - %(message)s')
    f_handler.setFormatter(f_format)

    # Add the handler to the logger
    logger.addHandler(con_handler)
    logger.addHandler(f_handler)

    return logger, con_handler
    
    
    
if __name__ == '__main__':
    logger, con_handler = define_logger()
    if args[1] == '-help_msg':
        logger.removeHandler(con_handler)
        show_help()
        logger.addHandler(con_handler)

本文标签: How to use Python logger in help messages without the mainINFO getting printedStack Overflow