Kaspersky IoT Secure Gateway 1000 SDK

Advanced capabilities when sending messages to a log

July 30, 2024

ID 245261

In most cases, you can send messages to the log by simply using macros for quick access to logging functions.

This section describes the additional capabilities of the logrr_cpp library API: merging messages, condition-based message forwarding, and deferred forwarding of messages.

Merging messages

To incrementally build the text of a log entry from parts and then send the entry to the log with one call:

  1. Link the program to the logrr_cpp library.
  2. Include the header file component/logrr/cpp/tools.h.

    C++

    #include <component/logrr/cpp/tools.h>

  3. Create an instance of the LogIface class.

    C++

    auto logger = LogIface(logrr::LogLevel::Warning);

  4. Fill the message buffer with one or more calls of the LogIface::Push() method.

    C++

    logger.Push("a={}", a);

    // ...

    logger.Push(", b={}", b);

    // ...

    logger.Push(", c={}", c);

  5. Send the previously received messages to the log by using the LogIface::Flush() method.

    C++

    logger.Flush();

Sending a message to the log based on a condition

To send a message to the log only when a specified condition is fulfilled:

  1. Link the program to the logrr_cpp library.
  2. Include the header file component/logrr/cpp/tools.h.

    C++

    #include <component/logrr/cpp/tools.h>

  3. Pass the logical value, one of the LogLevel enumerators, and the message text to the LOG_IF() macro.

    C++

    LOG_IF(IsWorldBroken(), logrr::LogLevel::Critical, "World is broken!");

Deferred forwarding of messages to the log

The LOG_DEFER() macro declared in the header file component/logrr/cpp/tools.h lets you avoid duplicating code for logging in the if...else blocks.

To send a pre-formatted message to the log when exiting a function:

  1. Link the program to the logrr_cpp library.
  2. Include the header file component/logrr/cpp/tools.h.

    C++

    #include <component/logrr/cpp/tools.h>

  3. Add a LOG_DEFER() macro call to the beginning of the code for the function that changes the values that need to be sent to the log. Pass the LogLevel value, message formatting string and arguments to be inserted in the formatting string to the macro.

    C++

    int DeferredLoggingExample()

    {

    auto logger = LOG_DEFER(logrr::LogLevel::Info, "a={}, b={}", a, b);

    if (someCondition)

    {

    a = 1;

    b = 2;

    return -1;

    }

    else

    {

    a = 3;

    b = 4;

    return 0;

    }

    }

In this example, a message is sent to the log when the logger object's destructor is called on exit from the DeferredLoggingExample() function. The values a and b at the time of exit from the function are inserted into the message formatting string.

Did you find this article helpful?
What can we do better?
Thank you for your feedback! You're helping us improve.
Thank you for your feedback! You're helping us improve.