Update on_close statistics log to run before log structure is cleaned up.

Also add a Python test case.