Search code examples
linuxshellstdoutcan-buscanutils

Shell Script to Log CAN Messages with FIFO


Edit 1-29-25: My goal is to have access to the last N number of actions that happened. To do this, I imagine that I need to continuously log CANbus messages in the Linux environment in a buffer. Then, when commanded by the user, the system would copy the last N number of messages into a different file. I imagine that the buffer would start getting quite big after some time so I would need to delete the oldest lines.

I am trying to create a Linux shell script to log CANbus messages on a CAN network and when the file gets over a certain number of lines or a filesize, the first line will get deleted and the CAN messages will continue logging, AKA a First-In First-Out system.

I am running the following commands while SSH'ed into a Linux PLC via PuTTY.

I am using the command candump -L can0 > test.log to log CANbus messages. While this command is running, the test.log file populates with the CANbus messages on the CAN network.

Then, I log in with a different PuTTY window and use ls -l test.log every few seconds to check that the test.log file is indeed increasing in size, indicating that the file is actively logging CAN traces.

Then, while the CAN traces are still actively logging, I use the command sed -i '1d' test.log to delete the first line of the test.log log file. After this, I run ls -l test.log every few seconds again to check the file size, but now the file size stays the same, indicating that the CAN trace has stopped logging even though the candump command from above is still running.

TLDR: If a file gets edited while the candump command is actively logging CAN traces into the file, the logging seems to stop.

Is there a way to keep the CANbus logging active while deleting lines from the log file? Or is there a more efficient way to create this script/application to log CANbus messages with a FIFO system?


Solution

  • There is the system logger.

    Run in the background or as a systemd service:

    candump -L can0 | logger -t candump
    

    To get last 10 messages, do:

    journalctl -n 10 SYSLOG_IDENTIFIER=candump
    

    No need to do rotation, filtering, caring about disc space, it's all implemented.