Restart logging to a new file (Python)

Posted by compie on Stack Overflow See other posts from Stack Overflow or by compie
Published on 2011-03-14T08:07:58Z Indexed on 2011/03/14 8:09 UTC
Read the original article Hit count: 219

Filed under:
|
|

I'm using the following code to initialize logging in my application.

logger = logging.getLogger()
logger.setLevel(logging.DEBUG)

# log to a file
directory = '/reserved/DYPE/logfiles'
now = datetime.now().strftime("%Y%m%d_%H%M%S")
filename = os.path.join(directory, 'dype_%s.log' % now)
file_handler = logging.FileHandler(filename)
file_handler.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s %(filename)s, %(lineno)d, %(funcName)s: %(message)s")
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)

# log to the console
console_handler = logging.StreamHandler()
level = logging.INFO
console_handler.setLevel(level)
logger.addHandler(console_handler)

logging.debug('logging initialized')

How can I close the current logging file and restart logging to a new file?

Note: I don't want to use RotatingFileHandler, because I want full control over all the filenames and the moment of rotation.

© Stack Overflow or respective owner

Related posts about python

Related posts about logging