Session specific (compressed) log files (or how to know when session ends)

I’m trying to create session specific log files, so that different sessions have their own log files.
I managed to get session ids by using get_script_run_ctx like this.
Problem is that with the solutions to compress the log files (loguru, CompressedFileHandler from plaso the app doesn’t seem to know when to close and compress the log files.
With loguru for example the log files are created and opened, and logs are written on it,
but the app doesn’t seem to know when to end the session even if user closes the tab,
so the file is never compressed.

Is there a good way to tell the app that the session has ended?
Or any other workarounds?