Easylogging++ Documentation

repository·master·Indexed 26 days ago

https://github.com/abumq/easyloggingpp

A high-performance, single-header C++ logging library designed for extensibility and ease of setup without external dependencies like Boost or Qt. It features custom sinks, thread safety, cross-platform support, and configurable severity levels. Note: This project is archived and no longer actively maintained; the author recommends spdlog for new projects.

Tokens
7.7K
Snippets
18
Records
40
Agent score
86%

What's inside Easylogging++

  1. Overview of Easylogging++

    master
    Easylogging++ is a single-header, efficient, and highly configurable C++ logging library. It is designed for portability and performance, providing features like custom sinks (via LogDispatchCallback), thread safety, and cross-platform support without requiring external dependencies like Boost or Qt for its core functionality. It is suitable for both small utilities and large-scale projects.
  2. Understand shared and static compilation examples

    master

    The samples/STL/shared-static-libs/ directory provides a demonstration of how to compile applications using both shared and static libraries with easylogging++.

    The project structure consists of:

    • compile_shared.sh: Script for shared library compilation.
    • compile_static.sh: Script for static library compilation.
    • lib/include/: Contains easylogging++.h and a custom header mylib.hpp.
    • lib/mylib.cpp: Implementation of the custom library.
    • myapp.cpp: The main application entry point.
  3. Understand Easylogging++ Severity Levels

    master

    Easylogging++ uses severity levels to control logging. By default, it does not use hierarchical logging, meaning each level must be configured explicitly. You can enable hierarchical logging using el::LoggingFlag::HierarchicalLogging.

    LevelDescription
    GlobalRepresents all levels; useful for setting global defaults.
    TraceUseful for back-tracing events.
    DebugInformational events for developers. Only applicable if NDEBUG is not defined (non-VC++) or _DEBUG is defined (VC++).
    FatalSevere errors that likely cause application abort.
    ErrorError information where the application continues running.
    WarningApplication errors where the application continues running.
    InfoRepresents current application progress.
    VerboseHighly useful information; not applicable to hierarchical logging.
    UnknownUsed in hierarchical logging to turn off logging completely.
  4. Quick Start with Easylogging++

    master

    To use Easylogging++ in your project, follow these steps:

    1. Download the latest version.
    2. Include easylogging++.h and easylogging++.cc in your project.
    3. Initialize the library using the INITIALIZE_EASYLOGGINGPP macro. This macro must be used exactly once per application (typically in the file containing main) to avoid compilation errors involving extern variables.
    4. Use the LOG(LEVEL) macro to record messages.

    Note on C++ Versions: If your application does not support C++11, use version v8.91, which is stable for C++98 and C++03.

    #include "easylogging++.h"
    
    INITIALIZE_EASYLOGGINGPP
    
    int main(int argc, char* argv[]) {
       LOG(INFO) << "My first info log using default logger";
       return 0;
    }
  5. Configure All Loggers via a Global Configuration File

    master

    You can use a single file to register new loggers and configure existing ones. In this file, logger IDs are prefixed with two dashes (--).

    Global Configuration File Format:

    -- LOGGER_ID_1
      CONFIGURATION_KEY = "VALUE"
    
    -- LOGGER_ID_2
      CONFIGURATION_KEY = "VALUE"

    Use el::Loggers::configureFromGlobal("filename.conf") to apply this file.

    int main(void) {
       // Registers new and configures it or
       // configures existing logger - everything in global.conf
       el::Loggers::configureFromGlobal("global.conf");
       // .. Your prog
       return 0;
    }
  6. Track function and block performance

    master

    Easylogging++ can track the execution time of functions or specific code blocks.

    Prerequisite: Define the macro ELPP_FEATURE_PERFORMANCE_TRACKING to enable this feature. To enable all features at once, define ELPP_FEATURE_ALL.

    Usage Macros:

    • TIMED_FUNC(obj-name): Tracks the duration of the entire function. The obj-name is a name for the el::base::type::PerformanceTrackerPtr object.
    • TIMED_SCOPE(obj-name, block-name): Tracks a specific scope within a function. The block-name is included in the log output.
    • TIMED_BLOCK(obj-name, block-name): Similar to TIMED_SCOPE but resolves to a single-looped for-loop.

    Conditional Tracking: Use TIMED_FUNC_IF(obj-name, condition) or TIMED_SCOPE_IF(obj-name, condition) to enable tracking only when a specific condition (e.g., a verbosity level) is met.

    void performHeavyTask(int iter) {
       TIMED_FUNC(timerObj);
       // Some initializations
       // Some more heavy tasks
       usleep(5000);
       while (iter-- > 0) {
           TIMED_SCOPE(timerBlkObj, "heavy-iter");
           // Perform some heavy task in each iter
           usleep(10000);
       }
    }
  7. Compile Easylogging++ with g++

    master

    When compiling your application, ensure you include easylogging++.cc in your compilation command and specify the C++11 standard (or higher) if using the latest version.

    g++ main.cc easylogging++.cc -o prog -std=c++11
  8. Use conditional and occasional logging macros

    master

    Easylogging++ provides macros to log only when specific conditions are met or after a certain number of hits.

    Conditional Logging (ends in _IF):

    • LOG_IF(condition, LEVEL)
    • CLOG_IF(condition, LEVEL, logger ID)

    Occasional Logging (hit-count based):

    • LOG_EVERY_N(n, LEVEL): Logs every $n$ hits.
    • LOG_AFTER_N(n, LEVEL): Only logs after $n$ hits have occurred.
    • LOG_N_TIMES(n, LEVEL): Logs exactly $n$ times.

    Note: For debug-only mode, prefix these macros with D (e.g., DLOG_IF, DLOG_EVERY_N).

    // Conditional
    LOG_IF(condition, INFO) << "Logged if condition is true";
    
    // Occasional
    for (int i = 1; i <= 10; ++i) {
       LOG_EVERY_N(2, INFO) << "Logged every second iter";
    }
    
    for (int i = 1; i <= 10; ++i) {
       LOG_AFTER_N(2, INFO) << "Log after 2 hits; " << i;
    }
    
    for (int i = 1; i <= 100; ++i) {
       LOG_N_TIMES(3, INFO) << "Log only 3 times; " << i;
    }
  9. Install Easylogging++ via CMake

    master

    To install Easylogging++ system-wide using CMake, use the following commands. You can enable specific options using -D<option>=ON:

    • lib_utc_datetime: Defines ELPP_UTC_DATETIME.
    • build_static_lib: Builds a static library for Easylogging++.

    Note: Even when installing via CMake, you still need the easylogging++.cc file in your project to compile.

    mkdir build
    cd build
    cmake -Dtest=ON ../
    make
    make test
    make install
  10. Configure Easylogging++ using a Configuration File

    master

    You can load configurations at runtime using a file. The file format uses a level prefix (starting with * and ending with :) and key-value pairs. It is recommended to start with the * GLOBAL: level to set defaults for all other levels.

    Supported Configuration Names:

    • Enabled (bool): Enables/disables the level.
    • To_File (bool): Writes logs to a file.
    • To_Standard_Output (bool): Writes logs to stdout/terminal.
    • Format (char*): The logging pattern.
    • Filename (char*): Full path to the log file.
    • Subsecond_Precision (uint): Precision width (1-6).
    • Performance_Tracking (bool): Enables performance tracking.
    • Max_Log_File_Size (size_t): Truncates file if it reaches this size.
    • Log_Flush_Threshold (size_t): Number of entries to hold before flushing.

    Example Configuration File:

    * GLOBAL:
       FORMAT               =  "%datetime %msg"
       FILENAME             =  "/tmp/logs/my.log"
       ENABLED              =  true
       TO_FILE              =  true
       TO_STANDARD_OUTPUT   =  true
       SUBSECOND_PRECISION  =  6
       PERFORMANCE_TRACKING =  true
       MAX_LOG_FILE_SIZE    =  2097152 ## 2MB
       LOG_FLUSH_THRESHOLD  =  100
    * DEBUG:
       FORMAT               =  "%datetime{%d/%M} %func %msg"
    #include "easylogging++.h"
    
    INITIALIZE_EASYLOGGINGPP
    
    int main(int argc, const char** argv) {
        // Load configuration from file
        el::Configurations conf("/path/to/my-conf.conf");
        // Reconfigure single logger
        el::Loggers::reconfigureLogger("default", conf);
        // Actually reconfigure all loggers instead
        el::Loggers::reconfigureAllLoggers(conf);
        // Now all the loggers will use configuration from file
    }