Logging and Serial Intermix Workarounds

Hello,

I use Serial to receive/send messages for testing and am having some trouble figuring out how to prevent intermixing with logger (SerialLogHandler) messages.

The main issue I am facing is that I have no way of preventing logging messages from mixing into message sent with Serial.write. Unfortunately, locking Serial does not prevent logging from sending messages at the same time, there doesn't seem to be a way to lock the logger and using SERIAL_THREAD_BLOCK deadlocks the system when used before Serial.write.

I have read the post: Is this a Particle OS bug, or my bad? Serial vs Log - #9

Building a buffer and using Log.write does prevent intermixing, I want to check if this is the best way to solve this problem.

Yes, that is the correct solution.

Since neither the SerialLogHandler nor your code (presumably) lock the serial port around an entire record, there is no way to prevent the intermixing other than buffering your data into log messages.

2 Likes

I am fine with the Log.write solution, but I am wondering if it is even possible to lock the serial port from the user application?

You can lock the Serial port using Serial.lock() and Serial.unlock(). However SerialLogHandler does not lock the serial port, so it won't help even if you did.

In theory you could make a locking version of SerialLogHandler, but the problem is that SerialLogHandler is just based on StreamLogHandler, and you'd have to replace that as well because you SerialLogHandler is only called per-byte, and locking at the byte level doesn't help. You'd need to go all the way up to the level where a full log transaction is managed.

The other advantage of switching from writing directly to Serial to writing to a buffer that writes to the log is that it will work when you switch log handlers. For example, if you use Serial1LogHandler to log to Serial1. Or one of the network log handers. All of the Wi-Fi devices than run my house log to Papertrail, for example.

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.