Thursday, September 12, 2013

I don't like to reinvent the wheel, and there are many logging codes out there, but still
I couldn't find what I wanted. Those were all either too complex or not exactly what I
wanted. That is why I took my old macros and added some ideas taken from this good tutorial:
http://www.drdobbs.com/cpp/logging-in-c/201804215.

Supports coloring of logs: coloring is implemented using ANSI Escape sequences on
Linux and MacOS. On Windows I disabled it, but you can enable if you're using something
like cygwin or similar. For iOS I use XcodeColors, a great project:
https://github.com/robbiehanson/XcodeColors.
So a specific implementation is reserved for that platform.

It is possible to reimplement the "sink" of the logs by reimplementing an output.

I preferred the printf way of formatting logs to the stream implementation. Anyway
I tried to provide both. The usage of a "null sink" when logs are disabled should,
together with compiler optimizations, make the overhead minimal.

Each log is flushed to avoid issues related to buffering. This might increase the
overhead, but it is simple to remove it.

On Windows/Linux/iOS a stack trace function is also available to show
the current call stack.

Should be entirely thread-safe.

Each log can be associated to a tag; I commonly use this with grep to filter
logs by module.

There a still things I don't like about this approach, like being impossible to use in C
sources, needing Objective-C++ instead of simple Objective-C and so on. Still someone
may find it useful, so I uploaded to github:
https://github.com/carlonluca/LightLogger.

How to Use

Just include in your sources and you're done. Most useful functions are those level-based:

These functions work differently according to the platform: on Android send INFO logs to
logcat, on iOS print colored text to Xcode (and thus the XcodeColors plugin is needed if
you keep colors enabled), on Windows simply print text and on Mac OS/Linux print text with
ANSI colors to the shell. I use the return type to do something like:

There are a few macros I use to configure for each project: COLORING_ENABLED to enable colors,
BUILD_LOG_LEVEL_* to set the logging verbosity and XCODE_COLORING_ENABLED to enable/disable
XcodeColors support.

In github you'll find Qt, iOS/XCode and Android sample projects.

How it Works

Pretty simple: wrapper functions like log_info(...) use the template class LC_Log to
print the string. The LC_Log delegates actual log call to the class of type T, which can
be implemented according to the needs. Delegates I currently implemented are:

LC_Output2Std: outputs to standard output, adding ANSI escape codes.

LC_Output2FILE: write the logs to file (no escape codes here).

LC_OutputAndroid: implements logging to logcat.

LC_Output2XCodeColors: implements logging using XcodeColors format.

Hope you can find this useful. If you improve this, share your work! If you find issues,
report them!
Bye! ;-)