I needed a very simple logging solution for a project that I'm working on. This is what I came up with:
If you have any feedback or want to improve this then be my guest. However, I probably could benefit from those improvements so please branch the github repo and help me improve it!
Simple lightweight logger utility for the Arduino platform.
---
Currently it defaults on the main serial port of the board.
---
Supported formatters:
%b - binary value
%d - int / byte
%f - double / float
%s - char string
%x - hex value
---
To enable the Log, place the following define statement in
the class you are including everthing in:
#define DEVELOPMENT_LOG
To set the log level place the following define statement in
the class you are including everything in:
#define LOG_LEVEL <Log_Level>
Make sure you have the include statements setup properly after
the Log define statements.
Example Usage:
#define DEVELOPMENT_LOG
#define LOG_LEVEL INFO_LEVEL
#include Log.h
Log::fine ("Fine statement");
Log::debug ("Debug statement");
Log::info ("Info statement ");
Log::warn ("Warn statement");
Log::error ("Error Statement");
Log::info ("Int: %d", 5);
Log::info ("Double: %f", 5.5);
Log::info ("Chars: %s", "test string");
Log::info ("Binary of 5: %b", 5);
Log::info ("Hex of 47: %x", 47);
Log::info ("Unrecognized formatter: %p", 1);
The use of cur in the code can be replaced by msg everywhere. these shorter too, or consider to place the fixed strings in progmem to preserve precious RAM. ```
const char Log::fine_prefix[] = "[F] ";
const char Log::debug_prefix[] = "[D] ";
const char Log::info_prefix[] = "[I] ";
const char Log::warn_prefix[] = "[W] ";
const char Log::error_prefix[] = "[E] ";* ``` missing is the number of decimals for a float. Maybe you can use the notation %nf where n is the nr of decimals 0..9 (default 2?) ==> Serial.print (temp_float, n) however from parsing point of view leaving out the f => %1 %2 %3 .. %9 is far easier to parse missing is %% to print a percent sign. 2 cents, update -- optionally a timestamp in millis() ? ==> a %t for millis
Why not just use existing C functionality for string formatting. You can either use sprintf to format to a buffer, or set up your own stdout:
static FILE debugOut = FDEV_SETUP_STREAM(uart_put_char, NULL, _FDEV_SETUP_WRITE);
static int uart_put_char(char c, FILE *stream)
{
//Write 1 character (C) to your Uart or whatever device you want to print to (ethernet, LCD)
return 0;
}
In your main you just use stdout = &debugOut;
Now, any call to printf will just print to whatever device you want it to, including easy string formatting. Doing this will probably make cout work too, but don't quote me on that, i never tried.