Simple C++ Thread-safe Logging
This project provides a simple way to log information from a C++ project, even from child threads.
The static logger provides a pointer to an object that handles writting printf-style messages to a log file. A date/time (UTC or local time) is automatically included in each log entry, in addition to the log entry level (info, debug, warning and error),
optional source file name, line number and function/method name. The log message may include printf-style formatters (e.g., "%02d", "%s", "%c", etc.) with a variable parameter list.
Since the logger is thread-safe, the logging methods can be called from separate threads within a single application space.
Why should one use this logger project?
Apache has a C++ logger based on a Java project, or some might just subclass the STL iostream. I am sure there are other C++ loggers as well. As for me, I wanted something I could just "drop" into a C++ project with minimum fuss. Apache's project is very
flexible, but also a bit too complicated if all you want to do is drop in a logger and get on with your real work. Also, I still do not like using the STL iostream formatters, which is what I would need to use with a sub-classed iostream; however, I am comfortable
using the "printf" family of C library functions.
Once your project links to the logger, here is how simple it is to use it:
LogFile_t myLog = Logger::GetLog();
myLog->Error(__FILE__, __LINE__, "CallingMethodName", "Oh no! Error code %d resulted from opening file %s", errorNumber, troublesomeFileName);
- Initialize the logger with your log file name (and optional path and a couple of optional flags).
- Get a pointer for log file access.
- Log some errors. __FILE__ and __LINE__ are pre-processor macros defined in ANSI C; the error messages follow the printf syntax.
The resulting log entry looks something like this:
2012-09-14 23:06:16.924 U [ERROR]: Main.cpp, line 13, CallingMethodName(): Oh no! Error code 5 resulted from opening file C:\SomeDatabase\MyAppDatabase.db
The Date is Year-month-day format, and the time is UTC (hence the "U" after the time). Local time is also available when initializing the logger (see the Logger API at the Documentation page). Notice the ease of creating a useful error message using printf
formatters in the message string.
Once Logger::Init() is called successfully, calling Logger::GetLog() will obtain the same single log pointer anywhere in your application (including child threads). There is no need to delete this logging pointer; it auto-deletes when the application terminates.
Comments and contributions are welcome.