要求:
代码:
import logging def logging_data(filename, 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')