Python tips

Ref: https://fangpenlin.com/posts/2012/08/26/good-logging-practice-in-python/

    import logging
    logging.basicConfig(level=logging.INFO)
    logger = logging.getLogger(__name__)

    logger.info('Start reading database')
    # read database here
    records = {'john': 55, 'tom': 66}
    logger.debug('Records: %s', records)
    logger.info('Updating records ...')
    # update records here
    logger.info('Finish updating records')


    #There are different importance levels you can use, debug, info, warning, error and critical. 
    #By giving different level to logger or handler, you can write only error messages to specific log file, 
    #or record debug details when debugging. Let’s change the logger level to DEBUG and see the output again


    logging.basicConfig(level=logging.DEBUG)

    #As you can see, we adjust the logger level to DEBUG, then debug records appear in output. 
    #You can also decide how these messages are processed. For example, you can use a FileHandler to 
    #write records to a file.

    import logging

    logger = logging.getLogger(__name__)
    logger.setLevel(logging.INFO)

    # create a file handler
    handler = logging.FileHandler('hello.log')
    handler.setLevel(logging.INFO)

    # create a logging format
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    handler.setFormatter(formatter)

    # add the handlers to the logger
    logger.addHandler(handler)

    logger.info('Hello baby')


    #Use __name__ as the logger name

    #You don’t have to set the logger name as __name__, but by doing that, it brings us some benefits. 
    #The variable __name__ is current module name in Python. For example, you call logger.getLogger(__name__) 
    #in a module “foo.bar.my_module”, then it is logger.getLogger(“foo.bar.my_module”). When you need to 
    #configure the logger, you can configure to “foo”, then all modules in “foo” packages shares same 
    #configuration. You can also understand what is the module of message when reading the log.

Last updated

Was this helpful?