How-To create log output

There are so many logging libraries for C++, the choice is just too great. So of course, liberate adds another one!

Just kidding.

Instead of writing yet another logging library or simply locking everything we do into one, we provide logging via one of the following options:

  1. std::cerr

  2. plog

  3. spdlog

  4. loguru

The reason for these is that they are popular, and available as meson subprojects, so compiling them in is pretty easy. We provide a uniform interface for logging at the following log levels:

Log Level equivalency

Liberate

loguru

plog

spdlog

LIBLOG_LEVEL_TRACE

9

verbose

TRACE

LIBLOG_LEVEL_DEBUG

1

debug

DEBUG

LIBLOG_LEVEL_INFO

INFO

info

INFO

LIBLOG_LEVEL_WARN

WARN

warning

WARN

LIBLOG_LEVEL_ERROR

ERROR

error

ERROR

LIBLOG_LEVEL_FATAL

FATAL

fatal

CRITICAL

Writing to the log is simple. Use the LIBLOG macro, provide a log level and a message. The message is assembled via a std::ostream interface, so you can use everything you know from there.

Logging basics
1#include <liberate/logging.h>
2
3LIBLOG(LIBLOG_LEVEL_DEBUG, "This is a message: " << 42);
4
5// or use a convenience macro
6
7LIBLOG_FATAL("Uh-oh!");

Note

This interface was great for getting started, but we may change it in future. Long story short, it doesn’t make it very easy to switch different log levels for different sub-projects, and we’re starting to need that.

Compile-Time Configuration

You can select the backend to use by providing the log_backend meson option, or setting e.g. -DLIBERATE_LOG_BACKEND=stderr when configuring liberate.

If your build has -DDEBUG configured, these log messages then get produced. If you use one of the logging libraries, you can use its interface to configure the log level you desire. Should you provide -DNDEBUG on the other hand, all log macros get optimized away and no output is produced.

Additional Macros

  1. The LIBLOG_ERR takes an error code and a message. It outputs the message followed by the message the system associates with the error code.

  2. The LIBLOG_ERRNO just takes a message, and uses the last system error code to pass on to LIBLOG_ERR.

  3. The LIBLOG_EXC takes an exception and a message, outputs the message followed by the exception’s what() message.