1. 程式人生 > >通過生成器寫一個日誌呼叫方法

通過生成器寫一個日誌呼叫方法

要求:

 

 

程式碼:

import logging


def logging_data(filename=None, channel='terminal'):
    logger = logging.getLogger()
    logger.setLevel(logging.DEBUG)

    ch = logging.StreamHandler()
    ch.setLevel(logging.DEBUG)

    fh = logging.FileHandler(filename)
    fh.setLevel(logging.DEBUG)

    formatter 
= logging.Formatter('%(asctime)s %(message)s') ch.setFormatter(formatter) fh.setFormatter(formatter) count = 0 while True: count += 1 msg = yield count if msg and channel == 'terminal': logger.addHandler(ch) logger.info('[{0}] {1}'.format(count, msg))
elif msg and channel == 'file': logger.addHandler(fh) logger.info('[{0}] {1}'.format(count, msg)) elif msg and channel == 'both': logger.addHandler(ch) logger.addHandler(fh) logger.info('[{0}] {1}'.format(count, msg)) else: exit(
'輸入不合法') log_obj = logging_data('web.db', 'both') next(log_obj) log_obj.send('user alex login success') log_obj.send('user wusir login success') log_obj.send('user haifeng login success')