Quick-Start Guide

Installing

The easiest way to install XTR is via Conan. If you are not using Conan, see the INSTALL guide, or for the truly impatient there is a single-include file here.

Overview

The logger is split into two main components, the logger class and the sink class. The logger takes care of opening and closing the log file, and is thread-safe. The sink class is used to write to the log. Sinks are created by calling xtr::logger::get_sink() and are not thread safe—the idea is that applications have many sinks, so threads should each have their own set of separate sinks.

Log messages are written using various macros which accept a sink as their first argument, followed by a Python str.format style format string. The {fmt} library is used for formatting.

Examples

Creating a sink:

#include <xtr/logger.hpp>

xtr::logger log;

xtr::sink s = log.get_sink("Main");

Writing to the log, blocking if the sink is full, reading the timestamp in the background thread [1]:

XTR_LOG(s, "Hello world");

Write to the log, discarding the message if the sink is full, reading the timestamp in the background thread:

XTR_TRY_LOG(s, "Hello world");

Write to the log, immediately reading the timestamp from the TSC:

XTR_LOG_TSC(s, "Hello world");

Write to the log, immediately reading the timestamp using clock_gettime(3) with a clock source of either CLOCK_REALTIME_COARSE on Linux or CLOCK_REALTIME_FAST on FreeBSD:

XTR_LOG_RTC(s, "Hello world");

Write to the log if the log level of the sink is at the ‘info’ level or a level with lower importance than ‘info’. The default sink level ‘info’ so this message will be logged:

XTR_LOGL(info, s, "Hello world");

Set the log level of the sink ‘s’ to ‘error’, causing messages with importance lower than ‘error’ to be dropped. Available log levels are debug, info, warning, error and fatal—see xtr::log_level_t.

s.set_level(xtr::log_level_t::error);

XTR_LOGL(info, s, "Hello world"); // Dropped

Fatal errors will log and then terminate the program using abort(3):

XTR_LOGL(fatal, s, "Goodbye cruel world");
// NOTREACHED

By default, objects and strings are copied into the sink. This is so that the default behaviour is safe—i.e. to avoid creating dangling references the logger does not assume anything about the lifetime of objects passed as arguments:

const std::string str1 = "Hello";
const char* str2 = "world";
XTR_LOG("{} {}", str1, str2);

To avoid copying, wrap arguments in a call to xtr::nocopy():

XTR_LOG("{} {}", nocopy(str1), nocopy(str2));

Arguments may also be moved in to the logger:

std::string str3 = "world";
XTR_LOG("Hello {}", std::move(str3));

Footnotes