You will need to create a file handler for each log level. Formatting can be applied to each handler to add the timestamp. Python Logging Cookbook - Multiple handlers and formatters
Also to filter out other log levels other than the one you want (e.g. only DEBUG logging going to debug log file), you'll need to write your own handler object. See similar question answered here.
Here's an example with just debug and info logging.
import logging
# Define handler to omit logs that are not DEBUG level
class DebugFileHandler(logging.FileHandler):
def __init__(self, filename, mode='a', encoding=None, delay=False):
logging.FileHandler.__init__(self, filename, mode, encoding, delay)
def emit(self, record):
if not record.levelno == logging.DEBUG:
return
logging.FileHandler.emit(self, record)
# Define handler to omit logs that are not INFO level
class InfoFileHandler(logging.FileHandler):
def __init__(self, filename, mode='a', encoding=None, delay=False):
logging.FileHandler.__init__(self, filename, mode, encoding, delay)
def emit(self, record):
if not record.levelno == logging.INFO:
return
logging.FileHandler.emit(self, record)
logger = logging.getLogger('simple_example')
logger.setLevel(logging.DEBUG)
# create file handlers
dh = DebugFileHandler('debug.log')
dh.setLevel(logging.DEBUG)
ih = InfoFileHandler('info.log')
ih.setLevel(logging.INFO)
# create formatter and add it to the handlers
formatter = logging.Formatter('%(asctime)s - %(message)s')
dh.setFormatter(formatter)
ih.setFormatter(formatter)
# add the handlers to logger
logger.addHandler(ih)
logger.addHandler(dh)
# 'application' code
logger.debug('debug message')
logger.info('info message')