demo/demo_coloredformatter.py
changeset 2 d3ffa15f5886
equal deleted inserted replaced
1:ee31f1bf17c1 2:d3ffa15f5886
       
     1 #!/usr/bin/env python3
       
     2 
       
     3 from pycolib.coloredformatter import ColoredFormatter
       
     4 
       
     5 import logging
       
     6 
       
     7 
       
     8 def prepare_logger(name, level=logging.DEBUG):
       
     9     logger = logging.getLogger(name)
       
    10     logger.setLevel(level)
       
    11     return logger
       
    12 
       
    13 
       
    14 def prepare_console_handler(level=logging.DEBUG):
       
    15     handler = logging.StreamHandler()
       
    16     formatter = ColoredFormatter('%(asctime)s %(levelname)-5s %(message)s', '%H:%M:%S')
       
    17     formatter.set_color('message', 'RECV', 2)
       
    18     formatter.set_color('message', 'SEND', 6)
       
    19     handler.setFormatter(formatter)
       
    20     handler.setLevel(level)
       
    21     return handler
       
    22 
       
    23 
       
    24 def setup():
       
    25     logging.addLevelName(21, 'RECV')
       
    26     logging.addLevelName(22, 'SEND')
       
    27 
       
    28     logger_main = prepare_logger('main')
       
    29 
       
    30     handler_console = prepare_console_handler()
       
    31     logger_main.addHandler(handler_console)
       
    32 
       
    33 
       
    34 def finish():
       
    35     logging.shutdown()
       
    36 
       
    37 
       
    38 def main():
       
    39     setup()
       
    40     log = logging.getLogger('main')
       
    41 
       
    42     log.info('test')
       
    43 
       
    44     try:
       
    45         raise Exception('test exception')
       
    46     except:
       
    47         log.exception('test exc')
       
    48 
       
    49     log.log(21, 'recv')
       
    50     log.log(22, 'send')
       
    51 
       
    52     log.debug('debug')
       
    53 
       
    54     finish()
       
    55 
       
    56 
       
    57 if __name__ == '__main__':
       
    58     main()
       
    59