Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restart logging to a new file (Python)

Tags:

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.

like image 449
compie Avatar asked Mar 14 '11 08:03

compie


People also ask

How do you clear a logger?

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.

How do you clear a log file in Python?

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 .


1 Answers

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) 
like image 200
Mahmoud Abdelkader Avatar answered Sep 17 '22 13:09

Mahmoud Abdelkader