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.
Open Administrative Tools, and then Computer Management. In the left frame, double-click Event Viewer, and then Windows Logs. Right-click Security and choose Clear Log.... You will have the option to save the details of the log.
You'd have to signal to the daemon that the log file's been removed so it can close/reopen the log file handle and start using the new log file. Otherwise it'll just keep writing to the old one, which will still exist somewhere until all filehandles on it are closed. Give mode="w" to logging. FileHandler .
You can manually re-assign the handler if you want using the removeHandler
and addHandler
OR, you can access logger.handlers[index_of_handler_here].stream
and replace the stream manually, but I'd recommend the former over the latter.
logger.handlers[0].stream.close() logger.removeHandler(logger.handlers[0]) 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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With