How to save pending log information when your application crashes

Do have an application that never crashes? Then you are very lucky and don’t need this tip!

 

For all others: Even when your program crashes you can save (or try to save) all pending logmessages to disk. This even includes the logmessages of the crashing thread that were not sent at the moment of the crash.

 

Simply use an SEH (see below) exception handler like this:

__try ()

{

 MainFunction();

// - This is a function that produces logmessages

// and might crash at a certain point.

}

__except(1)

{

 GetITLogLib().Deinitialize();

 // - writes out all pending output

}

 

SEH means "structured exception handling" and is Visual C++ specific. It catches crashes even in the "Release" configurations of your program.

 

When a crash occurs, normal stack-unwinding will occur and all objects defined locally in the functions on the call stack will be destroyed using their normal destructors. In their destructor, the ITLogMsg smartpointers used by you for logging send the logmessage to its logchannel if not sent before explicitely.

Then, in the __except clause the ITLogLib will be deinitialized, so all pending logmessages will be written to disk -- if the crash has not destroyed too much.

 

Note that you should deinitialize ITLogLib also in the normal case when no exception occurred. Here we assumed that the initialization and deinitialization of ITLogLib is done in MainFunction().