### Install Pkgconfig File Source: https://github.com/abumq/easyloggingpp/blob/master/CMakeLists.txt Installs the generated pkgconfig file to the designated pkgconfig directory. ```cmake install(FILES ${CMAKE_CURRENT_BINARY_DIR}/easyloggingpp.pc DESTINATION "${ELPP_PKGCONFIG_INSTALL_DIR}") ``` -------------------------------- ### Install Custom Log Dispatch Callback with Easylogging++ Source: https://github.com/abumq/easyloggingpp/blob/master/README.md Demonstrates how to install a custom log dispatch callback to intercept and handle log messages. This example uses Boost.Asio to send logs over TCP. Be cautious not to log within the handler to avoid infinite loops. ```cpp // samples/send-to-network/network-logger.cpp #include "easylogging++.h" #include INITIALIZE_EASYLOGGINGPP class Client { boost::asio::io_service* io_service; boost::asio::ip::tcp::socket socket; public: Client(boost::asio::io_service* svc, const std::string& host, const std::string& port) : io_service(svc), socket(*io_service) { boost::asio::ip::tcp::resolver resolver(*io_service); boost::asio::ip::tcp::resolver::iterator endpoint = resolver.resolve(boost::asio::ip::tcp::resolver::query(host, port)); boost::asio::connect(this->socket, endpoint); }; void send(std::string const& message) { socket.send(boost::asio::buffer(message)); } }; class NetworkDispatcher : public el::LogDispatchCallback { public: void updateServer(const std::string& host, int port) { m_client = std::unique_ptr(new Client(&m_svc, host, std::to_string(port))); } protected: void handle(const el::LogDispatchData* data) noexcept override { m_data = data; // Dispatch using default log builder of logger dispatch(m_data->logMessage()->logger()->logBuilder()->build(m_data->logMessage(), m_data->dispatchAction() == el::base::DispatchAction::NormalLog)); } private: const el::LogDispatchData* m_data; boost::asio::io_service m_svc; std::unique_ptr m_client; void dispatch(el::base::type::string_t&& logLine) noexcept { m_client->send(logLine); } }; int main() { el::Helpers::installLogDispatchCallback("NetworkDispatcher"); // you can uninstall default one by // el::Helpers::uninstallLogDispatchCallback("DefaultLogDispatchCallback"); // Set server params NetworkDispatcher* dispatcher = el::Helpers::logDispatchCallback("NetworkDispatcher"); dispatcher->setEnabled(true); dispatcher->updateServer("127.0.0.1", 9090); // Start logging and normal program... LOG(INFO) << "First network log"; // You can even use a different logger, say "network" and send using a different log pattern } ``` -------------------------------- ### Install Library Headers and Source Source: https://github.com/abumq/easyloggingpp/blob/master/CMakeLists.txt Installs the main header file and source file for Easylogging++ into the specified include directory, as part of the 'dev' component. ```cmake install( FILES src/easylogging++.h src/easylogging++.cc DESTINATION "${ELPP_INCLUDE_INSTALL_DIR}" COMPONENT dev ) ``` -------------------------------- ### Configuration File Format Example Source: https://github.com/abumq/easyloggingpp/blob/master/README.md Illustrates the basic structure of an easylogging++ configuration file, including level definitions and key-value pairs for settings. ```plaintext * LEVEL: CONFIGURATION NAME = "VALUE" ## Comment ANOTHER CONFIG NAME = "VALUE" ``` -------------------------------- ### Install Easylogging++ with vcpkg Source: https://github.com/abumq/easyloggingpp/blob/master/README.md Install easylogging++ using the vcpkg dependency manager. This command will download and integrate the library into your system. ```bash git clone https://github.com/Microsoft/vcpkg.git cd vcpkg ./bootstrap-vcpkg.sh ./vcpkg integrate install ./vcpkg install easyloggingpp ``` -------------------------------- ### Basic Logging Example Source: https://github.com/abumq/easyloggingpp/wiki/.md Demonstrates the usage of DEBUG, INFO, and ERR logging macros with EasyLogging++. Shows how to log messages and variable values. ```cpp #include "easylogging++.h" int main(void) { DEBUG("Staring my EasyLogging++ program"); unsigned int i = 0; INFO("Current value is " << i); INFO("Now the value has changed from " << i++ << " to " << i); DEBUG("End of my EasyLoggin++ program"); } ``` -------------------------------- ### Sample Easylogging++ Configuration File Source: https://github.com/abumq/easyloggingpp/blob/master/README.md Provides a concrete example of a configuration file, demonstrating settings for GLOBAL and DEBUG levels, including format, filename, and enabled status. ```plaintext * 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 - Comment starts with two hashes (##) LOG_FLUSH_THRESHOLD = 100 ## Flush after every 100 logs * DEBUG: FORMAT = "%datetime{%d/%M} %func %msg" ``` -------------------------------- ### Configure Installation Directories Source: https://github.com/abumq/easyloggingpp/blob/master/CMakeLists.txt Sets cache variables for installation directories, allowing users to customize where headers and pkgconfig files are placed. ```cmake set(ELPP_INCLUDE_INSTALL_DIR "${CMAKE_INSTALL_PREFIX}/include" CACHE PATH "The directory the headers are installed in") ``` ```cmake set(ELPP_PKGCONFIG_INSTALL_DIR "${CMAKE_INSTALL_PREFIX}/share/pkgconfig" CACHE PATH "Installation directory for pkgconfig (.pc) files") ``` -------------------------------- ### Configure Pkgconfig File Source: https://github.com/abumq/easyloggingpp/blob/master/CMakeLists.txt Configures the pkgconfig file template with project-specific variables, preparing it for installation. ```cmake configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/cmake/easyloggingpp.pc.cmakein ${CMAKE_CURRENT_BINARY_DIR}/easyloggingpp.pc @ONLY) ``` -------------------------------- ### Initialize Easylogging++ and Log Message Source: https://github.com/abumq/easyloggingpp/blob/master/README.md Include the header, initialize the library with INITIALIZE_EASYLOGGINGPP, and start logging. Ensure INITIALIZE_EASYLOGGINGPP is used only once in your application, typically in the main file. ```c++ #include "easylogging++.h" INITIALIZE_EASYLOGGINGPP int main(int argc, char* argv[]) { LOG(INFO) << "My first info log using default logger"; return 0; } ``` -------------------------------- ### Install and Use Custom Format Specifier in C++ Source: https://github.com/abumq/easyloggingpp/blob/master/README.md Demonstrates how to install a custom format specifier for IP addresses and then use it in the logger configuration. This is useful for applications like TCP servers where client IP needs to be logged. ```C++ const char* getIp(const el::LogMessage*) { return "192.168.1.1"; } int main(void) { el::Helpers::installCustomFormatSpecifier(el::CustomFormatSpecifier("%ip_addr", getIp)); el::Loggers::reconfigureAllLoggers(el::ConfigurationType::Format, "%datetime %level %ip_addr : %msg"); LOG(INFO) << "This is request from client"; return 0; } ``` -------------------------------- ### wxWidgets Container Logging Setup Source: https://github.com/abumq/easyloggingpp/blob/master/README.md Set up Easylogging++ to log wxWidgets containers. Use `ELPP_WX_PTR_ENABLED` for containers holding pointers, `ELPP_WX_ENABLED` for containers holding objects, and `ELPP_WX_HASH_MAP_ENABLED` for hash maps. ```c++ #include "easylogging++.h" // wxList example WX_DECLARE_LIST(int, MyList); WX_DEFINE_LIST(MyList); // Following line does the trick ELPP_WX_PTR_ENABLED(MyList); // wxHashSet example WX_DECLARE_HASH_SET(int, wxIntegerHash, wxIntegerEqual, IntHashSet); // Following line does the trick! ELPP_WX_ENABLED(IntHashSet) // wxHashMap example WX_DECLARE_STRING_HASH_MAP(wxString, MyHashMap); // Following line does the trick ELPP_WX_HASH_MAP_ENABLED(MyHashMap) ``` -------------------------------- ### Logging Output With Date/Time Source: https://github.com/abumq/easyloggingpp/wiki/.md Example output of EasyLogging++ when the SHOW_DATE_TIME configuration is enabled. Log messages include date, time, severity, file, and line number. ```text [DEBUG] [Sun Sep 23 14:34:38 2012] [/home/easyloggertest/main.cpp:3] Staring my EasyLogging++ program [INFO] [Sun Sep 23 14:34:38 2012] [/home/easyloggertest/main.cpp:4] Current value is 0 [INFO] [Sun Sep 23 14:34:38 2012] [/home/easyloggertest/main.cpp:5] Now the value has changed from 0 to 1 [DEBUG] [Sun Sep 23 14:34:38 2012] [/home/easyloggertest/main.cpp:6] End of my EasyLoggin++ program ``` -------------------------------- ### Parse Inline Configurations Source: https://github.com/abumq/easyloggingpp/blob/master/README.md Configure loggers by parsing settings from a string. This method is less recommended due to potential messiness but can be useful for simple, dynamic setups. ```c++ el::Configurations c; c.setToDefault(); c.parseFromText("*GLOBAL:\n FORMAT = %level %msg"); ``` -------------------------------- ### Log std::chrono::system_clock::time_point with Easylogging++ Source: https://github.com/abumq/easyloggingpp/blob/master/README.md Example of making std::chrono::system_clock::time_point loggable using MAKE_LOGGABLE. This snippet demonstrates formatting time points into a human-readable string. ```cpp inline MAKE_LOGGABLE(std::chrono::system_clock::time_point, when, os) { time_t t = std::chrono::system_clock::to_time_t(when); auto tm = std::localtime(&t); char buf[1024]; strftime(buf,sizeof(buf), "%F %T (%Z)", tm); os << buf; return os; } ``` -------------------------------- ### Logging Output Without Date/Time Source: https://github.com/abumq/easyloggingpp/wiki/.md Example output of EasyLogging++ when the SHOW_DATE_TIME configuration is set to false. Log messages include severity, file, and line number. ```text [DEBUG] [/home/easyloggertest/main.cpp:3] Staring my EasyLogging++ program [INFO] [/home/easyloggertest/main.cpp:4] Current value is 0 [INFO] [/home/easyloggertest/main.cpp:5] Now the value has changed from 0 to 1 [DEBUG] [/home/easyloggertest/main.cpp:6] End of my EasyLoggin++ program ``` -------------------------------- ### Default Logger Usage Without Macro Definition Source: https://github.com/abumq/easyloggingpp/blob/master/README.md If `ELPP_DEFAULT_LOGGER` is not defined, `LOG` macros will use the 'default' logger. This example shows usage when no custom default logger is set. ```c++ #include "easylogging++.h" UpdateManager::UpdateManager { _TRACE; // Logs using LOG(TRACE) using default logger because no `ELPP_DEFAULT_LOGGER` is defined unless you have it in makefile } ``` -------------------------------- ### Implement Custom Crash Handler in C++ Source: https://github.com/abumq/easyloggingpp/blob/master/README.md Use this to set a custom crash handler. Ensure your handler calls `el::Helpers::crashAbort(sig)` to prevent endless crash loops. This example demonstrates logging an error and then aborting. ```cpp #include "easylogging++.h" INITIALIZE_EASYLOGGINGPP void myCrashHandler(int sig) { LOG(ERROR) << "Woops! Crashed!"; // FOLLOWING LINE IS ABSOLUTELY NEEDED AT THE END IN ORDER TO ABORT APPLICATION el::Helpers::crashAbort(sig); } int main(void) { el::Helpers::setCrashHandler(myCrashHandler); LOG(INFO) << "My crash handler!"; int* i; *i = 0; // Crash! return 0; } ``` -------------------------------- ### Compile and Run Network Logger Source: https://github.com/abumq/easyloggingpp/blob/master/samples/send-to-network/README.md Compile the network logger using the provided script and then run the executable. Ensure the boost path is correctly set. ```bash mkdir bin sh compile.sh network-logger.sh ``` ```bash nc -k -l 9090 ``` ```bash ./bin/network-logger ``` -------------------------------- ### Printf-Like Logging with Easylogging++ Source: https://github.com/abumq/easyloggingpp/blob/master/README.md Demonstrates how to use the Logger class for printf-style logging. Requires C++11 variadic templates. Use %v for arguments and %%v to escape. ```cpp // Use default logger el::Logger* defaultLogger = el::Loggers::getLogger("default"); // STL logging (`ELPP_STL_LOGGING` should be defined) std::vector i; i.push_back(1); defaultLogger->warn("My first ultimate log message %v %v %v", 123, 222, i); // Escaping defaultLogger->info("My first ultimate log message %% %%v %v %v", 123, 222); ``` -------------------------------- ### Set Application Arguments with START_EASYLOGGINGPP Source: https://github.com/abumq/easyloggingpp/blob/master/README.md Use the START_EASYLOGGINGPP macro in your main function to pass application arguments to Easylogging++. This is required for certain features like verbose logging. ```c++ int main(int argc, char* argv[]) { START_EASYLOGGINGPP(argc, argv); ... } ``` -------------------------------- ### Load Configuration from File Source: https://github.com/abumq/easyloggingpp/blob/master/README.md Load and apply logger configurations from an external file. This is useful for managing complex logging settings. ```c++ #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 } ``` -------------------------------- ### Configure Unit Tests Source: https://github.com/abumq/easyloggingpp/blob/master/CMakeLists.txt Sets up the build for unit tests if the 'test' option is enabled. This includes finding Google Test, setting up C++14, and defining test-specific features. ```cmake if (test) # We need C++14 (Google Test requirement) require_cpp14() set (CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_SOURCE_DIR}/cmake") find_package (GTest REQUIRED) include_directories (${GTEST_INCLUDE_DIRS}) enable_testing() if (EMSCRIPTEN) set(CMAKE_EXE_LINKER_FLAGS "-O2 -s TOTAL_MEMORY=134217728") endif() add_executable(easyloggingpp-unit-tests src/easylogging++.cc test/main.cc ) target_compile_definitions(easyloggingpp-unit-tests PUBLIC ELPP_FEATURE_ALL ELPP_LOGGING_FLAGS_FROM_ARG ELPP_NO_DEFAULT_LOG_FILE ELPP_FRESH_LOG_FILE ELPP_STOP_ON_FIRST_ASSERTION ELPP_STL_LOGGING ELPP_FORCE_ENV_VAR_FROM_BASH ELPP_ENABLE_THREADING ELPP_FEATURE_CRASH_LOG ELPP_SYSLOG ) # Standard linking to gtest stuff. target_link_libraries(easyloggingpp-unit-tests ${GTEST_BOTH_LIBRARIES}) add_test(NAME easyloggingppUnitTests COMMAND easyloggingpp-unit-tests -v) endif() ``` -------------------------------- ### Define Build Options Source: https://github.com/abumq/easyloggingpp/blob/master/CMakeLists.txt Sets up boolean options for configuring the build, such as enabling tests, building a static library, or using UTC datetimes. ```cmake option(test "Build all tests" OFF) ``` ```cmake option(build_static_lib "Build easyloggingpp as a static library" OFF) ``` ```cmake option(lib_utc_datetime "Build library with UTC date/time logging" OFF) ``` -------------------------------- ### Build Easylogging++ with CMake Source: https://github.com/abumq/easyloggingpp/blob/master/README.md Build the library using CMake, with options to enable tests and build a static library. The easylogging++.cc file is still required for compilation. ```bash mkdir build cd build cmake -Dtest=ON ../ make make test make install ``` -------------------------------- ### Share Logging Repository in C++ Source: https://github.com/abumq/easyloggingpp/blob/master/README.md Demonstrates how to share the Easylogging++ logging repository between an application and a library. This is useful for maintaining a single, consistent logging configuration across different modules. ```c++ #define SHARE_EASYLOGGINGPP(access-function-to-repository) ``` ```c++ #define INITIALIZE_NULL_EASYLOGGINGPP el::Helpers::setStorage(el::base::type::StoragePointer) ``` -------------------------------- ### Syslog Logging with Easylogging++ Source: https://github.com/abumq/easyloggingpp/blob/master/README.md Enables logging to syslog. Requires defining the ELPP_SYSLOG macro. Initialization is optional but allows specifying syslog options. ```c++ #include "easylogging++.h" INITIALIZE_EASYLOGGINGPP int main(void) { ELPP_INITIALIZE_SYSLOG("my_proc", LOG_PID | LOG_CONS | LOG_PERROR, LOG_USER) // This is optional, you may not add it if you dont want to specify options // Alternatively you may do // el::SysLogInitializer elSyslogInit("my_proc", LOG_PID | LOG_CONS | LOG_PERROR, LOG_USER); SYSLOG(INFO) << "This is syslog - read it from /var/log/syslog" return 0; } ``` -------------------------------- ### Compile Easylogging++ Project Source: https://github.com/abumq/easyloggingpp/blob/master/README.md Compile your C++ application with easylogging++.cc included. Use -std=c++11 or higher for full feature support. ```bash g++ main.cc easylogging++.cc -o prog -std=c++11 ``` -------------------------------- ### Basic Logging with LOG and CLOG Source: https://github.com/abumq/easyloggingpp/blob/master/README.md Use `LOG(LEVEL)` for the default logger or `CLOG(LEVEL, logger ID)` for a custom logger. Ensure easylogging++ is initialized before use. ```c++ LOG(INFO) << "This is info log"; CLOG(ERROR, "performance") << "This is info log using performance logger"; ``` -------------------------------- ### Build Static Library Source: https://github.com/abumq/easyloggingpp/blob/master/CMakeLists.txt Builds Easylogging++ as a static library if 'build_static_lib' is enabled. It also conditionally defines the UTC datetime feature. ```cmake if (build_static_lib) if (lib_utc_datetime) add_definitions(-DELPP_UTC_DATETIME) endif() require_cpp14() add_library(easyloggingpp STATIC src/easylogging++.cc) set_property(TARGET easyloggingpp PROPERTY POSITION_INDEPENDENT_CODE ON) install(TARGETS easyloggingpp ARCHIVE DESTINATION lib) endif() ``` -------------------------------- ### Configure Loggers from Global Configuration File Source: https://github.com/abumq/easyloggingpp/blob/master/README.md Register and configure loggers, including new ones, using a global configuration file. This is efficient for managing configurations across a large project or when integrating with third-party libraries. ```c++ 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; } ``` -------------------------------- ### Set Version Variables Source: https://github.com/abumq/easyloggingpp/blob/master/CMakeLists.txt Defines the major, minor, and patch versions of Easylogging++, and constructs a version string. ```cmake set(ELPP_MAJOR_VERSION "9") set(ELPP_MINOR_VERSION "96") set(ELPP_PATCH_VERSION "7") set(ELPP_VERSION_STRING "${ELPP_MAJOR_VERSION}.${ELPP_MINOR_VERSION}.${ELPP_PATCH_VERSION}") ``` -------------------------------- ### STL Logging with Easylogging++ Source: https://github.com/abumq/easyloggingpp/blob/master/README.md Enables logging of STL containers. Requires defining the ELPP_STL_LOGGING macro. Containers are limited to logging a maximum of 100 entries for performance. -------------------------------- ### Log Custom Class with Easylogging++ Source: https://github.com/abumq/easyloggingpp/blob/master/README.md Extend `el::Loggable` to log custom classes. Implement the `log` method to define how your class should be serialized to the output stream. Ensure `INITIALIZE_EASYLOGGINGPP` is called. ```c++ #include "easylogging++.h" INITIALIZE_EASYLOGGINGPP class Integer : public el::Loggable { public: Integer(int i) : m_underlyingInt(i) { } Integer& operator=(const Integer& integer) { m_underlyingInt = integer.m_underlyingInt; return *this; } // Following line does the trick! // Note: el::base::type::ostream_t is either std::wostream or std::ostream depending on unicode enabled or not virtual void log(el::base::type::ostream_t& os) const { os << m_underlyingInt; } private: int m_underlyingInt; }; int main(void) { Integer count = 5; LOG(INFO) << count; return 0; } ``` -------------------------------- ### Include EasyLogging++ Header Source: https://github.com/abumq/easyloggingpp/wiki/.md Include the main header file to use EasyLogging++ macros in your C++ application. ```cpp #include "easylogging++.h" ``` -------------------------------- ### EasyLogging++ Configuration Flags Source: https://github.com/abumq/easyloggingpp/wiki/.md Defines various boolean and string flags to configure EasyLogging++ behavior, such as enabling/disabling logs, showing timestamps, and specifying log file names. ```cpp /** * Flag for showing log in standard output using std::cout */ const bool SHOW_STD_OUTPUT = true; /** * Flag to set whether to save log to file */ const bool SAVE_TO_FILE = true; /** * Flag to set whether to show date/time */ const bool SHOW_DATE_TIME = false; /** * Flag to set whether to show which function logged the output (some compiler dont support this) */ const bool SHOW_LOG_FUNCTION = false; /** * Flag to set whether to show which file logged the output and what line */ const bool SHOW_LOG_LOCATION = true; /** * Flag to set whether output value of NOT_SUPPORTED_STRING if extra info is not available on machine */ const bool SHOW_NOT_SUPPORTED_ON_NO_EXTRA_INFO = false; /** * outputs if extra info is not available on machine and SHOW_NOT_SUPPORTED_ON_NO_EXTRA_INFO is true */ const std::string NOT_SUPPORTED_STRING = "-not supported-"; /** * If saving to file, this defines the filename */ const std::string LOG_FILENAME = "memory.log"; /** * Flag to set whether to save log file in custom location */ const bool USE_CUSTOM_LOCATION = false; /** * If using custom location, this is where custom location is picked up from. * Note: This should end with last slash */ const std::string CUSTOM_LOG_FILE_LOCATION = ""; ``` -------------------------------- ### Include Project Headers Source: https://github.com/abumq/easyloggingpp/blob/master/CMakeLists.txt Adds the current source directory's include path to the project's include directories. ```cmake include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include) ``` -------------------------------- ### Check for execinfo.h Header Source: https://github.com/abumq/easyloggingpp/blob/master/CMakeLists.txt Checks if the 'execinfo.h' header is available on the system. If found, it defines the HAVE_EXECINFO macro. ```cmake include(CheckIncludeFileCXX) check_include_file_cxx("execinfo.h" HAVE_EXECINFO) if (HAVE_EXECINFO) add_definitions(-DHAVE_EXECINFO) endif() ``` -------------------------------- ### Register New Logger in C++ Source: https://github.com/abumq/easyloggingpp/blob/master/README.md Use this to register a new logger with a unique ID. If the logger does not exist, it will be created. If it already exists, the existing logger will be returned. Logger IDs are case-sensitive. ```c++ el::Logger* businessLogger = el::Loggers::getLogger("business"); ``` -------------------------------- ### Set Logger Configurations Programmatically Source: https://github.com/abumq/easyloggingpp/blob/master/README.md Configure logger settings directly within your C++ code using the el::Configurations class. This allows for dynamic configuration adjustments. ```c++ #include "easylogging++.h" INITIALIZE_EASYLOGGINGPP int main(int argc, const char** argv) { el::Configurations defaultConf; defaultConf.setToDefault(); // Values are always std::string defaultConf.set(el::Level::Info, el::ConfigurationType::Format, "%datetime %level %msg"); // default logger uses default configurations el::Loggers::reconfigureLogger("default", defaultConf); LOG(INFO) << "Log using default file"; // To set GLOBAL configurations you may use defaultConf.setGlobally( el::ConfigurationType::Format, "%date %msg"); el::Loggers::reconfigureLogger("default", defaultConf); return 0; } ``` -------------------------------- ### CHECK_EQ Macro for Equality Source: https://github.com/abumq/easyloggingpp/blob/master/README.md Use CHECK_EQ(a, b) to assert that two values are equal. If not equal, a FATAL log is written. ```cpp CHECK_EQ(getId(), getLoggedOnId()) << "Invalid user logged in"; ``` -------------------------------- ### Make Third-Party Class Loggable with Easylogging++ Source: https://github.com/abumq/easyloggingpp/blob/master/README.md Use MAKE_LOGGABLE to make a third-party class compatible with Easylogging++. Ensure the class has a method to access its data for logging. This is useful when you cannot modify the original class definition. ```cpp #include "easylogging++.h" INITIALIZE_EASYLOGGINGPP class Integer { public: Integer(int i) : m_underlyingInt(i) { } Integer& operator=(const Integer& integer) { m_underlyingInt = integer.m_underlyingInt; return *this; } int getInt(void) const { return m_underlyingInt; } private: int m_underlyingInt; }; // Following line does the trick! inline MAKE_LOGGABLE(Integer, integer, os) { os << integer.getInt(); return os; } int main(void) { Integer count = 5; LOG(INFO) << count; return 0; } ``` -------------------------------- ### CHECK_STRCASEEQ Macro for Case-Insensitive C-String Equality Source: https://github.com/abumq/easyloggingpp/blob/master/README.md Use CHECK_STRCASEEQ(str1, str2) for case-insensitive C-string equality checks. If strings are not equal, a FATAL log is written. ```cpp CHECK_CASESTREQ(argv[1], "Z") << "First arg cannot be 'z' or 'Z'"; ``` -------------------------------- ### Log Crash Reason Parameters in C++ Source: https://github.com/abumq/easyloggingpp/blob/master/README.md These are the default parameters for logging a crash reason using `el::Helpers::logCrashReason`. Adjust `stackTraceIfAvailable`, `level`, and `logger` as needed. ```cpp > bool stackTraceIfAvailable = false > const el::Level& level = el::Level::Fatal > const char* logger = "default" ``` -------------------------------- ### CHECK_STRCASENE Macro for Case-Insensitive C-String Inequality Source: https://github.com/abumq/easyloggingpp/blob/master/README.md Use CHECK_STRCASENE(str1, str2) for case-insensitive C-string inequality checks. If strings are equal, a FATAL log is written. ```cpp CHECK_STRCASENE(username1, username2) << "Same username not allowed"; ``` -------------------------------- ### Read Logger Configurations Source: https://github.com/abumq/easyloggingpp/blob/master/README.md Use `typedConfigurations()` to read enabled status and log format for a specific logger. ```c++ el::Logger* l = el::Loggers::getLogger("default"); bool enabled = l->typedConfigurations()->enabled(el::Level::Info); // Or to read log format/pattern std::string format = l->typedConfigurations()->logFormat(el::Level::Info).format(); ``` -------------------------------- ### CHECK_LT Macro for Less Than Source: https://github.com/abumq/easyloggingpp/blob/master/README.md Use CHECK_LT(a, b) to assert that 'a' is less than 'b'. If not, a FATAL log is written. ```cpp CHECK_LT(1, 2) << "How 1 is not less than 2"; ``` -------------------------------- ### Populate Logger IDs in C++ Source: https://github.com/abumq/easyloggingpp/blob/master/README.md This function populates a provided vector with all currently registered logger IDs. The vector is cleared before being filled. ```c++ el::Loggers::populateAllLoggerIds(std::vector&); ``` -------------------------------- ### Track Function and Block Performance Source: https://github.com/abumq/easyloggingpp/blob/master/README.md Use TIMED_FUNC and TIMED_SCOPE to track the execution time of functions and specific code blocks. Ensure ELPP_FEATURE_PERFORMANCE_TRACKING is defined. TIMED_FUNC is equivalent to TIMED_SCOPE with the block name set to the function name. ```c++ 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); } } ``` -------------------------------- ### CHECK_STREQ Macro for C-String Equality Source: https://github.com/abumq/easyloggingpp/blob/master/README.md Use CHECK_STREQ(str1, str2) for case-sensitive C-string equality checks. If strings are not equal, a FATAL log is written. ```cpp CHECK_STREQ(argv[1], "0") << "First arg cannot be 0"; ``` -------------------------------- ### Print Stack Trace in C++ (GCC) Source: https://github.com/abumq/easyloggingpp/blob/master/README.md Call `el::base::debug::StackTrace()` to print a stack trace. This feature is supported for GCC compilers; non-GCC compilers will produce empty output. Ensure `ELPP_FEATURE_CRASH_LOG` is defined. ```cpp el::base::debug::StackTrace() ``` -------------------------------- ### CHECK_NE Macro for Inequality Source: https://github.com/abumq/easyloggingpp/blob/master/README.md Use CHECK_NE(a, b) to assert that two values are not equal. If they are equal, a FATAL log is written. ```cpp CHECK_NE(isUserBlocked(userId), false) << "User is blocked"; ``` -------------------------------- ### CHECK Macro for Conditionals Source: https://github.com/abumq/easyloggingpp/blob/master/README.md Use CHECK(condition) to assert that a condition is true. If false, a FATAL log is written and the application may stop. ```cpp CHECK(isLoggedIn()) << "Not logged in"; ``` -------------------------------- ### CHECK_BOUNDS Macro for Range Checking Source: https://github.com/abumq/easyloggingpp/blob/master/README.md Use CHECK_BOUNDS(val, min, max) to ensure 'val' is within the inclusive range [min, max]. If not, a FATAL log is written. ```cpp CHECK_BOUNDS(i, 0, list.size() - 1) << "Index out of bounds"; ``` -------------------------------- ### Define Default Logger Macro Source: https://github.com/abumq/easyloggingpp/blob/master/README.md Define `ELPP_DEFAULT_LOGGER` and `ELPP_DEFAULT_PERFORMANCE_LOGGER` in a source file to change the default logger used by `LOG` and associated macros. This should be done before including easylogging++.h. ```c++ #ifndef ELPP_DEFAULT_LOGGER # define ELPP_DEFAULT_LOGGER "update_manager" #endif #ifndef ELPP_DEFAULT_PERFORMANCE_LOGGER # define ELPP_DEFAULT_PERFORMANCE_LOGGER ELPP_DEFAULT_LOGGER #endif #include "easylogging++.h" UpdateManager::UpdateManager { _TRACE; // Logs using LOG(TRACE) provided logger is already registered - i.e, update_manager LOG(INFO) << "This will log using update_manager logger as well"; } ``` -------------------------------- ### CHECK_STRNE Macro for C-String Inequality Source: https://github.com/abumq/easyloggingpp/blob/master/README.md Use CHECK_STRNE(str1, str2) for case-sensitive C-string inequality checks. If strings are equal, a FATAL log is written. ```cpp CHECK_STRNE(username1, username2) << "Usernames cannot be same"; ``` -------------------------------- ### Checking Verbose Logging Status Source: https://github.com/abumq/easyloggingpp/blob/master/README.md Use the VLOG_IS_ON macro to check if a specific verbose logging level is active for the current source file. This is useful for conditional logging. ```cpp if (VLOG_IS_ON(2)) { // Verbosity level 2 is on for this file } ``` -------------------------------- ### CHECK_LE Macro for Less Than or Equal Source: https://github.com/abumq/easyloggingpp/blob/master/README.md Use CHECK_LE(a, b) to assert that 'a' is less than or equal to 'b'. If not, a FATAL log is written. ```cpp CHECK_LE(1, 1) << "1 is not equal or less than 1"; ``` -------------------------------- ### Export Package Source: https://github.com/abumq/easyloggingpp/blob/master/CMakeLists.txt Exports the project for use by other CMake projects, making it discoverable via find_package. ```cmake export(PACKAGE ${PROJECT_NAME}) ``` -------------------------------- ### Record Performance Checkpoints Source: https://github.com/abumq/easyloggingpp/blob/master/README.md Utilize PERFORMANCE_CHECKPOINT and PERFORMANCE_CHECKPOINT_WITH_ID to mark specific points within a timed block for more granular performance analysis. This allows for measuring time elapsed between checkpoints within the same timed object. ```c++ 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 // Notice following sleep varies with each iter usleep(iter * 1000); if (iter % 3) { PERFORMANCE_CHECKPOINT(timerBlkObj); } } } ``` -------------------------------- ### Require C++14 Standard Source: https://github.com/abumq/easyloggingpp/blob/master/CMakeLists.txt Ensures the C++14 standard is used, either through built-in CMake support or compiler flags. This is a prerequisite for Easylogging++. ```cmake macro(require_cpp14) if (${CMAKE_MAJOR_VERSION}.${CMAKE_MINOR_VERSION} GREATER 3.0) # CMake 3.1 has built-in CXX standard checks. message("-- Setting C++14") set(CMAKE_CXX_STANDARD 14) set(CMAKE_CXX_STANDARD_REQUIRED on) else() if (CMAKE_CXX_COMPILER_ID MATCHES "GCC") message ("-- GNU CXX (-std=c++14)") list(APPEND CMAKE_CXX_FLAGS "-std=c++14") elseif (CMAKE_CXX_COMPILER_ID MATCHES "Clang") message ("-- CLang CXX (-std=c++14)") list(APPEND CMAKE_CXX_FLAGS "-std=c++14") else() message ("-- Easylogging++ requires C++14. Your compiler does not support it.") endif() endif() endmacro() ``` -------------------------------- ### Compare Checkpoints in Sub-blocks Source: https://github.com/abumq/easyloggingpp/blob/master/README.md When comparing checkpoints, if the checkpoint is for a sub-block, the output will indicate the time elapsed since the last checkpoint within that sub-block. This provides insight into performance variations within nested operations. ```c++ 06:40:35,522 INFO Performance checkpoint for block [void performHeavyTask(int)] : [51 ms ([1 ms] from last checkpoint)] ``` -------------------------------- ### Compare Checkpoints with IDs Source: https://github.com/abumq/easyloggingpp/blob/master/README.md Use PERFORMANCE_CHECKPOINT_WITH_ID to add a unique identifier to a checkpoint. This is useful for distinguishing between multiple checkpoints within the same block, especially when comparing performance over time or across different runs. ```c++ 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 // Notice following sleep varies with each iter usleep(iter * 1000); if (iter % 3) { PERFORMANCE_CHECKPOINT_WITH_ID(timerObj, "mychkpnt"); } } } ``` -------------------------------- ### PCHECK Macro for perror()-style Checks Source: https://github.com/abumq/easyloggingpp/blob/master/README.md Use PCHECK() for perror()-style checks. If the condition is false, a FATAL log is written along with the system error. ```cpp PCHECK(some_function_that_might_fail()); ``` -------------------------------- ### Conditional Performance Tracking in C++ Source: https://github.com/abumq/easyloggingpp/blob/master/README.md Use TIMED_FUNC_IF to enable performance tracking only when a specific condition, like a verbosity level, is met. Ensure the timer object is properly initialized. ```c++ void performHeavyTask(int iter) { // enable performance tracking for verbosity level 4 or higher TIMED_FUNC_IF( timerObj, VLOG_IS_ON(4) ); // Some more heavy tasks } ``` -------------------------------- ### CHECK_GE Macro for Greater Than or Equal Source: https://github.com/abumq/easyloggingpp/blob/master/README.md Use CHECK_GE(a, b) to assert that 'a' is greater than or equal to 'b'. If not, a FATAL log is written. ```cpp CHECK_GE(1, 1) << "1 is not equal or greater than 1"; ``` -------------------------------- ### Occasional Logging with LOG_N_TIMES Source: https://github.com/abumq/easyloggingpp/blob/master/README.md Log messages a specific number of times (N). Use `LOG_N_TIMES` for the default logger or `CLOG_N_TIMES` for a custom logger. ```c++ for (int i = 1; i <= 100; ++i) { LOG_N_TIMES(3, INFO) << "Log only 3 times; " << i; } // 3 logs writter; 1, 2, 3 ``` -------------------------------- ### Occasional Logging with LOG_EVERY_N Source: https://github.com/abumq/easyloggingpp/blob/master/README.md Log messages at a specified interval (every N times). Use `LOG_EVERY_N` for the default logger or `CLOG_EVERY_N` for a custom logger. ```c++ for (int i = 1; i <= 10; ++i) { LOG_EVERY_N(2, INFO) << "Logged every second iter"; } // 5 logs written; 2, 4, 6, 7, 10 ``` -------------------------------- ### DCHECK Macros for Debug Mode Only Source: https://github.com/abumq/easyloggingpp/blob/master/README.md DCHECK macros (e.g., DCHECK, DCHECK_EQ) provide the same functionality as CHECK macros but are only active in debug builds (when _DEBUG is defined or NDEBUG is undefined). ```cpp #define _DEBUG // ... DCHECK(condition); ``` -------------------------------- ### CHECK_GT Macro for Greater Than Source: https://github.com/abumq/easyloggingpp/blob/master/README.md Use CHECK_GT(a, b) to assert that 'a' is greater than 'b'. If not, a FATAL log is written. ```cpp CHECK_GT(2, 1) << "How 2 is not greater than 1?"; ``` -------------------------------- ### CHECK_NOTNULL Macro for Pointers Source: https://github.com/abumq/easyloggingpp/blob/master/README.md Use CHECK_NOTNULL(pointer) to ensure a pointer is not null. This macro does not return a value. ```cpp CHECK_NOTNULL(pointer); ``` -------------------------------- ### Occasional Logging with LOG_AFTER_N Source: https://github.com/abumq/easyloggingpp/blob/master/README.md Log messages only after a certain number of hits (N). Use `LOG_AFTER_N` for the default logger or `CLOG_AFTER_N` for a custom logger. ```c++ for (int i = 1; i <= 10; ++i) { LOG_AFTER_N(2, INFO) << "Log after 2 hits; " << i; } // 8 logs written; 3, 4, 5, 6, 7, 8, 9, 10 ``` -------------------------------- ### PLOG Macro for perror()-style Logging Source: https://github.com/abumq/easyloggingpp/blob/master/README.md Use PLOG(LEVEL) for perror()-style logging with the default logger. This appends ': log-error [errno]' to the log message. ```cpp PLOG(INFO) << "Error occurred"; ``` -------------------------------- ### CPLOG Macro for Custom Logger perror()-style Logging Source: https://github.com/abumq/easyloggingpp/blob/master/README.md Use CPLOG(LEVEL, LoggerId) for perror()-style logging with a custom logger. This appends ': log-error [errno]' to the log message. ```cpp CPLOG(INFO, "my_custom_logger") << "Error occurred on custom logger"; ``` -------------------------------- ### Conditional Logging with LOG_IF and CLOG_IF Source: https://github.com/abumq/easyloggingpp/blob/master/README.md Log messages only if a specified condition is true. Use `LOG_IF` for the default logger or `CLOG_IF` for a custom logger. ```c++ LOG_IF(condition, INFO) << "Logged if condition is true"; LOG_IF(false, WARNING) << "Never logged"; CLOG_IF(true, INFO, "performance") << "Always logged (performance logger)" ``` -------------------------------- ### Unregister Logger in C++ Source: https://github.com/abumq/easyloggingpp/blob/master/README.md Use this to unregister a logger by its ID. Avoid unregistering default or system-provided loggers to prevent errors. This function should be used with caution. ```c++ el::Loggers::unregisterLogger("logger-id"); ``` -------------------------------- ### PLOG_IF Macro for Conditional perror()-style Logging Source: https://github.com/abumq/easyloggingpp/blob/master/README.md Use PLOG_IF(Condition, LEVEL) for conditional perror()-style logging with the default logger. The log is only written if the condition is true. ```cpp PLOG_IF(true, INFO) << "This will always log"; ```