Dash callback on closing/refresh to close logfile

I am writing to a logfile using my own customization of the Python logger functionality in my dashboard. This opens and writes to a file when the dashboard is started. Is there some way to properly close the file when the page is closed or refreshed using a callback or any other methods?

I can imagine there might not be any time to close the file when the user basically closes the browser but if anyone has an idea that would be more neat because that way it is more clear when a session was closed or for example crashed due to some error.