logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
stage1_log = getlogger.get_logger(name="stage1", logfilename=os.path.join(os.getcwd(), "outputdata/stage1.log"))
(stage1_log == logger.)
stage1_log = None
local_conn = None
try:
# Get error loggers.
stage1_log = getlogger.get_logger(name="stage1", logfilename=os.path.join(os.getcwd(), "outputdata/stage1.log"))
# Stage 1 and Stage 2 requires only local conn.
local_conn = mysql_connect(sie_constants.DCT_LOCAL_DB)
finally:
if local_conn:
local_conn.close()
if stage1_log:
# Close the log file of the logger.
stage1_log.handlers[0].stream.close()
stage1_log.removeHandler(stage1_log.handlers[0])
http://stackoverflow.com/questions/5296130/restart-logging-to-a-new-file-python
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.
| |||
Question:
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.
logger.handlers[0].stream.close()
first. – Mahmoud Abdelkader Mar 14 '11 at 19:06