Lightweight C++ logging class for Linux




Logging is not only a powerful debugging and maintenance tool, but also a basic security  element. In this case I wanted to save telemetry data of a multirotor without sending it to my laptop. Thus I wrote a simple logger that stores everything on the on-board uSD card. Although it's not perfect, it has proven to work as expected and be quite lightweight.

API





Log file access

  • open(file_route)

Together with one of the overloaded constructors, this function allow opening a log file. If for whatever reason it fails opening the log file it will show a warning message but not crash.
  • close(file_route)

Flush and close the log file.
  • isOpen()

Returns true if log file is open (writable)

Logging

  • << operator

Writing to the log is as simple as streaming to it. All ostream compatible classes can be written to the log file as it is templated.
  • endl

Writing LoggerInstance.endl to the log will finish the current log entry, flushing the file buffer.
  • enableTimestamp(bool)

This is by defaul enabled. The logger will write a timestamp for each log entry. Disable it calling this function with false as argument.

Streaming

  • getPreviousEntry()

This returns a string with the previous logged entry. If no previous entry has been written in the current execution of the code an empty string will be returned. Useful for logging and writing to the terminal at the same time.
  • getCurrentEntry()

The same as above, but returns a string with the entry that is being written right now. An entry is not logged to the logging file until endl is appended to it. This can be useful for debugging or when only the first half of a log entry is intended to be shown on screen.
  • enableTimestamp(bool)

This is by defaul enabled. The logger will write a timestamp for each log entry. Disable it calling this function with false as argument.


Code





No comments :

Post a Comment