查看logging.handlers中RotatingFileHandler的代码最终给了我足够的线索来解决这个问题。关键实现是,当记录一条消息时,可以传递一个可选关键字,这是一个要存储在. 这可以从. 在 中,我们可以根据用户提供的值触发输出流的变化。extra
Record
Handler
Handler
import logging
class MultiFileHandler(logging.FileHandler):
def __init__(self, filename, mode, encoding=None, delay=0):
logging.FileHandler.__init__(self, filename, mode, encoding, delay)
def emit(self, record):
if self.should_change_file(record):
self.change_file(record.file_id)
logging.FileHandler.emit(self, record)
def should_change_file(self, record):
if not hasattr(record, 'file_id') or record.file_id == self.baseFilename:
return False
return True
def change_file(self, file_id):
self.stream.close()
self.baseFilename = file_id
self.stream = self._open()
if __name__ == '__main__':
logger = logging.getLogger('request_logger')
logger.setLevel(logging.DEBUG)
handler = MultiFileHandler(filename='out.log', mode='a')
handler.setLevel(logging.DEBUG)
logger.addHandler(handler)
# Log some messages to the original file
logger.debug('debug message')
logger.info('info message')
# Log some messages to a different file
logger.debug('debug message', extra={'file_id':'changed.log'})
logger.info('info message', extra={'file_id':'changed.log'})
logger.warn('warn message', extra={'file_id':'changed.log'})
logger.error('error message', extra={'file_id':'changed.log'})
logger.critical('critical message', extra={'file_id':'changed.log'})