... or, of course, you could allocate some memory before and write a low memory handler that would free the memory on a low memory situation and right after that would write a log report to disk (and hopefully, the memory you freed would ensure a stable system to write the file back to disk (I believe this operation won't use much memory, if any at all)).
But beware, low memory handlers are also triggered by "avail flush" aka flushlibs.