Skip to content

Examples CallbackBackend

Eduard Mishkurov edited this page Jun 3, 2026 · 2 revisions

CallbackBackend example

CallbackBackend

This example shows how to route log records to a user callback.

CallbackBackend is useful when an application wants to collect records in memory, forward them to an existing telemetry pipeline, or integrate logme with a custom diagnostics system.

The callback receives the original Logme::Context, the owning channel, and the user data pointer supplied when the backend is created. The example formats the record with the owning channel flags and prints it from the callback.

Console output

callback[1]: 2026-06-03 16:33:07:985   main(): first callback record: 1

callback[2]: 2026-06-03 16:33:07:985 W main(): second callback record

records captured by callback: 2

Source code

Sources

Repository folder: examples/CallbackBackend

CallbackBackend.cpp

Open in repository

#include <Logme/Logme.h>
#include <Logme/Backend/CallbackBackend.h>
#include <Logme/Channel.h>

#include <cstdio>
#include <memory>

namespace
{
  struct CallbackState
  {
    size_t Count;
  };

  void StoreRecord(
    Logme::Context& context
    , const Logme::ChannelPtr& owner
    , void* userData
  )
  {
    auto state = static_cast<CallbackState*>(userData);

    int nc = 0;
    const char* text = context.Apply(owner, owner->GetFlags(), nc);

    ++state->Count;
    std::printf(
      "callback[%zu]: %.*s\n"
      , state->Count
      , nc
      , text
    );
  }
}

int main()
{
  Logme::ID id{"callback"};
  auto channel = Logme::Instance->CreateChannel(id);

  CallbackState state{};
  auto backend = std::make_shared<Logme::CallbackBackend>(
    channel
    , StoreRecord
    , &state
  );

  channel->AddBackend(backend);

  LogmeI(channel, "first callback record: %d", 1);
  LogmeW(channel) << "second callback record";

  std::printf("records captured by callback: %zu\n", state.Count);

  return 0;
}

Previous: Basic | Next: CApi

Clone this wiki locally