diff --git a/README-RU.md b/README-RU.md index 36f33d0..e4e8acb 100644 --- a/README-RU.md +++ b/README-RU.md @@ -1,11 +1,71 @@ # LogIt++ Library ![LogIt++ Logo](docs/logo-640x320.png) -## Введение +## Обзор -**LogIt++** — это гибкая и универсальная библиотека логирования на C++, которая поддерживает различные бэкенды и потоковый вывод. Она предоставляет простой в использовании интерфейс для логирования сообщений с разными уровнями важности и позволяет настраивать форматы и назначения логов. +**LogIt++** — макро-ориентированная библиотека логирования на C++ с поддержкой компиляторов начиная с `C++11`. Она сочетает лёгкие макросы инструментирования с настраиваемыми бэкендами (консоль, вращающиеся файлы, syslog, Windows Event Log или пользовательские приёмники) и направляет сообщения через асинхронную очередь, чтобы приложения оставались отзывчивыми даже при подробной диагностике. Библиотека объединяет удобство макросов, знакомое по **IceCream-Cpp**, и гибкость решений вроде **spdlog**. -Библиотека сочетает простоту макросов для логирования, аналогичную **IceCream-Cpp**, и возможности настройки бэкендов и форматов логов, как в **spdlog**. LogIt++ полностью совместим с `C++11`. +Ключевые особенности: + +- **Макро-ориентированный API.** Единые семейства макросов (`LOGIT_`, `LOGIT_PRINTF_`, `LOGIT_STREAM_` и др.) покрывают мгновенные сообщения, форматирование в стиле `printf`, потоковый вывод, ограничения частоты и работу с тегами. Определите `LOGIT_SHORT_NAME` перед подключением ``, чтобы включить компактные алиасы `LOG_I`, `LOG_WPF`, `LOG_S_INFO` и другие. +- **Гибкое форматирование и маршрутизация.** Настраивайте шаблоны формата, комбинируйте консольные/файловые/системные бэкенды или подключайте собственные реализации логгеров. +- **Асинхронность по умолчанию.** Каждый бэкенд обслуживается исполнителем задач с настраиваемыми размерами очереди и политиками переполнения, а макросы вроде `LOGIT_WARN_ONCE` или `LOGIT_ERROR_THROTTLE` помогают упорядочить повторяющиеся сообщения. + +Ниже приведены примеры макросов; также загляните в каталог `examples/` с отдельными сценариями, включая настройку очереди и обработку аварийного завершения. + +## Примеры макросов + +### Полные макросы + +```cpp +#include + +int main() { + LOGIT_ADD_CONSOLE_DEFAULT(); + LOGIT_SET_MAX_QUEUE(32); + LOGIT_SET_QUEUE_POLICY(LOGIT_QUEUE_DROP); + + const bool verbose = true; + int attempt = 1; + double latency_ms = 12.5; + + LOGIT_TRACE0(); + LOGIT_DEBUG_IF(verbose, "Подробная диагностика включена"); + LOGIT_INFO("Запуск сервиса", attempt); + LOGIT_WARN_ONCE("инициализация подсистемы"); + LOGIT_ERROR_EVERY_N(3, "повторное подключение", attempt); + LOGIT_ERROR_THROTTLE(250, "сбой не устранён"); + LOGIT_PRINTF_WARN("Задержка %.2f ms", latency_ms); + LOGIT_FORMAT_INFO("%.2f", 1.23f, 4.56f); + LOGIT_INFO_TAG(({{"order_id", 123}, {"side", "BUY"}}), "отправлен ордер"); + LOGIT_STREAM_INFO() << "Потоковый вывод: " << attempt; + + LOGIT_WAIT(); +} +``` + +### Короткие алиасы + +Определите `LOGIT_SHORT_NAME` перед подключением ``, чтобы использовать односимвольные префиксы уровней: + +```cpp +#define LOGIT_SHORT_NAME +#include + +void short_names_demo() { + LOGIT_ADD_CONSOLE_DEFAULT(); // вызывайте один раз при инициализации + + int attempt = 2; + + LOG_I("Короткий алиас для INFO"); + LOG_IPF("Попытка %d завершена", attempt); + LOG_W("Предупреждение"); + LOG_WPF("Повтор %d/3", attempt); + LOG_S_INFO() << "Потоковый алиас " << attempt; +} +``` + +Самодостаточный пример, который объединяет настройки и намеренно завершает работу после fatal-сообщения, расположен в `examples/example_logit_minimal_crash.cpp`. ## Возможности diff --git a/README.md b/README.md index 8eee008..1c81ae5 100644 --- a/README.md +++ b/README.md @@ -10,12 +10,71 @@ [Читать на русском](README-RU.md) -## Introduction +## Overview -**LogIt++** is a flexible and versatile C++ logging library that supports various backends and stream-based output. It provides an easy-to-use interface for logging messages with different severity levels and allows customization of log formats and destinations. +**LogIt++** is a macro-first C++ logging library that supports C++11 and newer toolchains. It pairs lightweight instrumentation macros with configurable backends (console, rotating files, syslog, Windows Event Log, or custom sinks) and routes messages through an asynchronous queue so applications remain responsive while recording detailed diagnostics. The library combines the convenience of macro-driven logging similar to **IceCream-Cpp** with the configurability of engines such as **spdlog**. -The library combines the simplicity of macro-based logging similar to **IceCream-Cpp** and the configurability of logging backends and formats like **spdlog**. -LogIt++ is fully compatible with `C++11`. +Key characteristics: + +- **Macro-oriented API.** Consistent macro families (`LOGIT_`, `LOGIT_PRINTF_`, `LOGIT_STREAM_`, etc.) cover immediate messages, printf-style formatting, streaming, throttling, and tagging. Defining `LOGIT_SHORT_NAME` when including `` enables compact aliases like `LOG_I`, `LOG_WPF`, and `LOG_S_INFO`. +- **Flexible formatting and routing.** Customize output patterns, mix console/file/system backends, or supply custom logger implementations. +- **Async by default.** Each backend is served by the task executor with configurable queue sizes and overflow policies, plus helpers such as `LOGIT_WARN_ONCE` or `LOGIT_ERROR_THROTTLE` to keep repeated messages under control. + +See the macro examples below or browse the `examples/` folder for focused demonstrations, including queue tuning and crash handling. + +## Macro Examples + +### Long-form macros + +```cpp +#include + +int main() { + LOGIT_ADD_CONSOLE_DEFAULT(); + LOGIT_SET_MAX_QUEUE(32); + LOGIT_SET_QUEUE_POLICY(LOGIT_QUEUE_DROP); + + const bool verbose = true; + int attempt = 1; + double latency_ms = 12.5; + + LOGIT_TRACE0(); + LOGIT_DEBUG_IF(verbose, "Verbose diagnostics enabled"); + LOGIT_INFO("Starting service", attempt); + LOGIT_WARN_ONCE("initializing subsystem"); + LOGIT_ERROR_EVERY_N(3, "retrying connection", attempt); + LOGIT_ERROR_THROTTLE(250, "still failing"); + LOGIT_PRINTF_WARN("Latency %.2f ms", latency_ms); + LOGIT_FORMAT_INFO("%.2f", 1.23f, 4.56f); + LOGIT_INFO_TAG(({{"order_id", 123}, {"side", "BUY"}}), "sent order"); + LOGIT_STREAM_INFO() << "Streaming value: " << attempt; + + LOGIT_WAIT(); +} +``` + +### Short aliases + +Define `LOGIT_SHORT_NAME` before including `` to enable single-letter level prefixes: + +```cpp +#define LOGIT_SHORT_NAME +#include + +void short_names_demo() { + LOGIT_ADD_CONSOLE_DEFAULT(); // call once during initialization + + int attempt = 2; + + LOG_I("Short alias for info"); + LOG_IPF("Attempt %d finished", attempt); + LOG_W("Warning alias"); + LOG_WPF("Retry %d/3", attempt); + LOG_S_INFO() << "Streaming alias " << attempt; +} +``` + +For a standalone program that brings everything together and intentionally aborts after logging a fatal message, check `examples/example_logit_minimal_crash.cpp`. --- diff --git a/docs/mainpage.dox b/docs/mainpage.dox index b7a235f..32a0840 100644 --- a/docs/mainpage.dox +++ b/docs/mainpage.dox @@ -3,12 +3,71 @@ Version: VERSION_PLACEHOLDER -\section intro_sec Introduction +\section overview_sec Overview -`LogIt++` is a flexible and versatile C++ logging library that supports various backends and stream-based output. It provides an easy-to-use interface for logging messages with different severity levels and allows customization of log formats and destinations. -The library combines the simplicity of macro-based logging similar to **IceCream-Cpp** and the configurability of logging backends and formats like **spdlog**. +`LogIt++` is a macro-first C++ logging library that supports C++11 and newer toolchains. It pairs lightweight instrumentation macros with configurable backends (console, rotating files, syslog, Windows Event Log, or custom sinks) and routes messages through an asynchronous queue so applications remain responsive while recording detailed diagnostics. The library combines the convenience of macro-driven logging similar to **IceCream-Cpp** with the configurability of engines such as **spdlog**. -`LogIt++` is fully compatible with `C++11`, ensuring support for a wide range of compilers and systems. +Key characteristics: + +- **Macro-oriented API.** Consistent macro families (`LOGIT_`, `LOGIT_PRINTF_`, `LOGIT_STREAM_`, etc.) cover immediate messages, `printf`-style formatting, streaming, throttling, and tagging. Defining `LOGIT_SHORT_NAME` when including `` enables compact aliases like `LOG_I`, `LOG_WPF`, and `LOG_S_INFO`. +- **Flexible formatting and routing.** Customize output patterns, mix console/file/system backends, or supply custom logger implementations. +- **Async by default.** Each backend is served by the task executor with configurable queue sizes and overflow policies, plus helpers such as `LOGIT_WARN_ONCE` or `LOGIT_ERROR_THROTTLE` to keep repeated messages under control. + +See the macro examples below or browse the `examples/` directory for focused demonstrations, including queue tuning and crash handling. + +\section macro_examples_sec Macro Examples + +\subsection macro_examples_long Long-form macros + +\code{.cpp} +#include + +int main() { + LOGIT_ADD_CONSOLE_DEFAULT(); + LOGIT_SET_MAX_QUEUE(32); + LOGIT_SET_QUEUE_POLICY(LOGIT_QUEUE_DROP); + + const bool verbose = true; + int attempt = 1; + double latency_ms = 12.5; + + LOGIT_TRACE0(); + LOGIT_DEBUG_IF(verbose, "Verbose diagnostics enabled"); + LOGIT_INFO("Starting service", attempt); + LOGIT_WARN_ONCE("initializing subsystem"); + LOGIT_ERROR_EVERY_N(3, "retrying connection", attempt); + LOGIT_ERROR_THROTTLE(250, "still failing"); + LOGIT_PRINTF_WARN("Latency %.2f ms", latency_ms); + LOGIT_FORMAT_INFO("%.2f", 1.23f, 4.56f); + LOGIT_INFO_TAG(({{"order_id", 123}, {"side", "BUY"}}), "sent order"); + LOGIT_STREAM_INFO() << "Streaming value: " << attempt; + + LOGIT_WAIT(); +} +\endcode + +\subsection macro_examples_short Short aliases + +Define `LOGIT_SHORT_NAME` before including `` to enable single-letter level prefixes: + +\code{.cpp} +#define LOGIT_SHORT_NAME +#include + +void short_names_demo() { + LOGIT_ADD_CONSOLE_DEFAULT(); // call once during initialization + + int attempt = 2; + + LOG_I("Short alias for info"); + LOG_IPF("Attempt %d finished", attempt); + LOG_W("Warning alias"); + LOG_WPF("Retry %d/3", attempt); + LOG_S_INFO() << "Streaming alias " << attempt; +} +\endcode + +For a standalone program that brings everything together and intentionally aborts after logging a fatal message, check `examples/example_logit_minimal_crash.cpp`. \section features_sec Features diff --git a/examples/example_logit_minimal_crash.cpp b/examples/example_logit_minimal_crash.cpp new file mode 100644 index 0000000..b0f4204 --- /dev/null +++ b/examples/example_logit_minimal_crash.cpp @@ -0,0 +1,38 @@ +/// \file example_logit_minimal_crash.cpp +/// \brief Minimal LogIt++ setup that intentionally aborts after logging a fatal message. + +#include + +#define LOGIT_SHORT_NAME +#include + +namespace { + +[[noreturn]] void crash_demo(int attempt) { + LOG_WPF("Attempt %d exceeded retry budget", attempt); + LOG_F("Triggering abort to demonstrate fatal logging"); + LOGIT_WAIT(); + std::abort(); +} + +} // namespace + +int main() { + LOGIT_ADD_CONSOLE_DEFAULT(); + LOGIT_SET_MAX_QUEUE(16); + LOGIT_SET_QUEUE_POLICY(LOGIT_QUEUE_DROP); + + double progress = 0.42; + LOG_I("Minimal setup ready"); + LOG_IF("%.0f%% ready", progress * 100.0); + LOG_S_INFO() << "Streaming alias demo"; + + LOGIT_WARN_ONCE("initializing subsystem"); // duplicates suppressed automatically + + // Rapid retries trigger the throttle macro; only the first message is printed. + for (int retry = 1; retry <= 3; ++retry) { + LOGIT_ERROR_THROTTLE(200, "Retrying connection to upstream service"); + } + + crash_demo(3); +}