How can I keep a log for rare use

I have sprinkled diagnostic Serial.print statements throughout my code to produce a history of program flow I could use for understanding failures, finding bugs.

However, I assumed that I could just disconnect the Serial Monitor and all that text would just fall off the end of the buffer onto the floor, and when I reconnected the Serial Monitor I'd see whatever was still in the buffer. Apparently not so.

After some time, my program begins to misbehave. I now suspect that it only kept working properly until the transmit buffer got full.

However, it didn't entirely stop. Some functions still worked.

So, how does Serial.print behave when the buffer is full? It doesn't seem to just block and hang, because parts of my program keep running.

How can I get the effect I want, namely to keep a log of modest length that I can look at after I see a malfunction, without leaving Serial Monitor always connected?

Connecting or disconnecting from the Serial Monitor resets the board. So you'll never be able to see what it was sending before you connected it.

The HardwareSerial instance will happily just keep sending stuff out the line. It has absolutely no way to know whether anything is listening or even whether anything is connected. The buffer isn't going to just fill up. The data is just being sent out into the air if nothing is connected.

If you want to keep a long log of what was happening while your program ran, then the answer is probably to log it to an SD card.

Here is a great tool I use for this purpose. It is a serial logger board - saves data to an SD card.