### Complete JSON Logging Configuration Example Source: https://context7.com/3hren/blackhole/llms.txt Provides a comprehensive JSON configuration example for the Blackhole logging library. This example demonstrates the setup of multiple handlers, each with distinct formatters and sinks, showcasing flexibility in routing log messages to different destinations and formats. ```json { "root": [ { "type": "blocking", "formatter": { "type": "string", "sevmap": ["DEBUG", "INFO", "WARN", "ERROR"], "pattern": "[{severity:>5}] [{timestamp:{%Y-%m-%d %H:%M:%S}s}] {message}" }, "sinks": [ {"type": "console"} ] }, { "type": "blocking", "formatter": { "type": "json", "newline": true, "unique": true, "routing": { "": ["message", "severity", "timestamp"], "/context": "*" }, "mapping": { "message": "@message", "timestamp": "@timestamp" }, "mutate": { "timestamp": "%Y-%m-%dT%H:%M:%S.%fZ", "severity": ["debug", "info", "warn", "error"] } }, "sinks": [ { "type": "file", "path": "/var/log/app.json.log", "flush": "1MB" } ] } ] } ``` -------------------------------- ### Blocking Handler Setup in C++ Source: https://context7.com/3hren/blackhole/llms.txt Shows how to configure a blocking handler in C++ that synchronously processes log records. This example demonstrates setting a string formatter and adding both console and file sinks to the handler. ```cpp #include #include #include #include // Build handler with formatter and multiple sinks auto handler = blackhole::builder() .set(blackhole::builder( "[{severity}] {timestamp}: {message}" ).build()) // Add console output .add(blackhole::builder() .stdout() .build()) // Add file output .add(blackhole::builder("/var/log/app.log") .flush_every(blackhole::megabytes_t(1)) .build()) .build(); // Use handler in logger auto log = blackhole::builder() .add(std::move(handler)) .build(); ``` -------------------------------- ### JSON Formatter Configuration Example Source: https://github.com/3hren/blackhole/blob/master/README.md Provides a comprehensive JSON configuration for the Blackhole formatter, demonstrating options for newline, uniqueness, mapping, routing, and mutation of fields. ```json { "formatter": { "type": "json", "newline": true, "unique": true, "mapping": { "message": "@message", "timestamp": "@timestamp" }, "routing": { "": ["message", "timestamp"], "/fields": "*" }, "mutate": { "timestamp": "%Y-%m-%dT%H:%M:%S.%fZ", "severity": ["D", "I", "W", "E"] } } } ``` -------------------------------- ### Compile Blackhole Examples Source: https://github.com/3hren/blackhole/blob/master/CMakeLists.txt This section compiles various example executables for the Blackhole library, including 'Hello World', simple configuration, and JSON configuration with and without a facade. Each example is built with all warnings enabled and linked against the Blackhole library. ```cmake if (ENABLE_EXAMPLES) # Hello World example. add_executable(1-hello examples/1.hello) enable_all_warnings(1-hello) target_link_libraries(1-hello blackhole) # Configuration using manual builder. add_executable(2-simple examples/2.simple) enable_all_warnings(2-simple) target_link_libraries(2-simple blackhole) # Configuration using JSON config file. add_executable(3-config examples/3.config) enable_all_warnings(3-config) target_link_libraries(3-config blackhole) # Configuration using JSON config file with facade. add_executable(4-config_facade examples/4.config_facade) enable_all_warnings(4-config_facade) target_link_libraries(4-config_facade blackhole) file(COPY examples/3.config.json DESTINATION .) endif (ENABLE_EXAMPLES) ``` -------------------------------- ### Blackhole Initialization and Facade Usage (C++) Source: https://github.com/3hren/blackhole/blob/master/README.md Demonstrates initializing the Blackhole logger from a JSON configuration file and wrapping it with the logger facade. This example showcases how to set up the logging pipeline, including severity mapping, and then use the facade for flexible logging. ```cpp /// This example demonstrates how to initialize Blackhole from configuration file using JSON /// builder. /// In this case the entire logging pipeline is initialized from file including severity mapping. /// The logging facade is used to allow runtime formatting and attributes provisioning. #include #include #include #include #include #include #include #include #include using namespace blackhole; /// As always specify severity enumeration. enum severity { debug = 0, info = 1, warning = 2, error = 3 }; auto main(int argc, char** argv) -> int { if (argc != 2) { std::cerr << "Usage: 3.config PATH" << std::endl; return 1; } /// Here we are going to build the logger using registry. The registry's responsibility is to /// track registered handlers, formatter and sinks, but for now we're not going to register /// anything else, since there are predefined types. auto inner = blackhole::registry::configured() /// Specify the concrete builder type we want to use. It may be JSON, XML, YAML or whatever /// else. ->builder(std::ifstream(argv[1])) /// Build the logger named "root". .build("root"); /// Wrap the logger with facade to obtain an ability to format messages and provide attributes. auto log = blackhole::logger_facade(inner); log.log(severity::debug, "{} {} HTTP/1.1 {} {}", "GET", "/static/image.png", 404, 347); log.log(severity::info, "nginx/1.6 configured", { {"elapsed", 32.5} }); log.log(severity::warning, "client stopped connection before send body completed"); log.log(severity::error, "file does not exist: {}", "/var/www/favicon.ico", blackhole::attribute_list{ {"Cache", true}, {"Cache-Duration", 10}, {"User-Agent", "Mozilla Firefox"} }); return 0; } ``` -------------------------------- ### Basic JSON Formatting Example Source: https://github.com/3hren/blackhole/blob/master/README.md Demonstrates the default JSON output for a log record without any specific formatting options. This shows a plain JSON tree with zero level depth. ```json { "message": "fatal error, please try again", "severity": 3, "timestamp": 1449859055, "process": 12345, "thread": 57005, "key": 42, "ip": "[::]" } ``` -------------------------------- ### Formatted Message with Attributes using Facade (C++) Source: https://github.com/3hren/blackhole/blob/master/README.md Combines formatted message logging with attribute provisioning. This example demonstrates logging a message with placeholders and providing additional attributes, with the attribute list expected as the last argument. ```cpp logger.log(0, "{} {} HTTP/1.1 {} {}", "GET", "/static/image.png", 436, 200, attribute_list{ {"cache", true}, {"elapsed", 435.72}, {"user-agent", "Mozilla Firefox"} }); ``` -------------------------------- ### Configure Logger from JSON File in C++ Source: https://context7.com/3hren/blackhole/llms.txt Shows how to configure Blackhole loggers at runtime using a JSON configuration file. This approach utilizes the registry and a JSON parser to dynamically set up logging behavior without recompiling the application. The example assumes a 'config.json' file exists. ```cpp #include #include #include #include // JSON config file (config.json): // { // "root": [{ // "type": "blocking", // "formatter": { // "type": "string", // "sevmap": ["DEBUG", "INFO", "WARN", "ERROR"], // "pattern": "{severity}, [{timestamp}]: {message}" // }, // "sinks": [{ "type": "console" }] // }] // } auto log = blackhole::registry::configured() ->builder(std::ifstream("config.json")) .build("root"); log.log(0, "Loaded configuration from JSON file"); log.log(3, "Critical error occurred in module"); ``` -------------------------------- ### Install Blackhole Library and Headers Source: https://github.com/3hren/blackhole/blob/master/CMakeLists.txt This CMake installation rule defines where the Blackhole library and its header files will be placed on the system. Libraries are installed to 'lib' and headers to 'include', with specific components for runtime and development. ```cmake install( TARGETS blackhole LIBRARY DESTINATION lib COMPONENT runtime ARCHIVE DESTINATION lib COMPONENT development) install( DIRECTORY include/ DESTINATION include COMPONENT development PATTERN "detail" EXCLUDE) ``` -------------------------------- ### Configure Build Options with CMake Source: https://github.com/3hren/blackhole/blob/master/CMakeLists.txt Sets up boolean options for enabling testing, examples, benchmarking, and thread-safety testing. These options control which features are included in the build process. ```cmake OPTION(ENABLE_TESTING "Build the library with tests" OFF) OPTION(ENABLE_EXAMPLES "Build examples" OFF) OPTION(ENABLE_BENCHMARKING "Build the library with benchmarks" OFF) OPTION(ENABLE_TESTING_THREADSAFETY "Build the thread-safety testing suite" OFF) ``` -------------------------------- ### JSON Formatting with Routing Source: https://github.com/3hren/blackhole/blob/master/README.md Illustrates how attribute routing can be used to organize log record attributes into a hierarchical JSON structure. This example routes 'message' and 'severity' into a 'fields' object. ```json { "fields": { "message": "fatal error, please try again", "severity": 3 }, "timestamp": 1449859055, "process": 12345, "thread": 57005, "key": 42, "ip": "[::]" } ``` -------------------------------- ### Socket Sink Configuration (TCP/UDP) in JSON Source: https://context7.com/3hren/blackhole/llms.txt Provides JSON configurations for setting up TCP and UDP socket sinks. These examples specify the target host and port for remote log aggregation, using JSON formatting. ```json // JSON configuration for TCP sink { "root": [{ "type": "blocking", "formatter": { "type": "json", "newline": true }, "sinks": [{ "type": "tcp", "host": "logserver.example.com", "port": 5140 }] }] } // JSON configuration for UDP sink { "root": [{ "type": "blocking", "formatter": { "type": "json", "newline": true }, "sinks": [{ "type": "udp", "host": "logserver.example.com", "port": 5141 }] }] ``` -------------------------------- ### Simple String Logging with Facade (C++) Source: https://github.com/3hren/blackhole/blob/master/README.md Demonstrates the simplest usage of the logging facade, where a string message is logged directly. The facade handles the conversion of the string to a string view and passes it to the underlying logger. ```cpp logger.log(0, "GET /static/image.png HTTP/1.1 436 200"); ``` -------------------------------- ### Logging with Attributes using Facade (C++) Source: https://github.com/3hren/blackhole/blob/master/README.md Shows how to log a message along with additional attributes using an initializer list. The facade allows passing key-value pairs as attributes to enrich log entries. ```cpp logger.log(0, "GET /static/image.png HTTP/1.1 436 200", { {"cache", true}, {"elapsed", 435.72}, {"user-agent", "Mozilla Firefox"} }); ``` -------------------------------- ### Configure Logger with Experimental Builder (C++) Source: https://github.com/3hren/blackhole/blob/master/README.md This C++ snippet demonstrates how to configure a logger using Blackhole's experimental builder. It shows how to set up a blocking handler, configure a string formatter with a specific pattern and severity mapping, and add a console sink. The builder pattern allows for compile-time configuration of the logging system. ```c++ // Here we are going to configure our string/console handler and to build the logger. auto log = blackhole::experimental::partial_builder() // Add the blocking handler. .handler() // Configure string formatter. // // Pattern syntax behaves like as usual substitution for placeholder. For example if // the attribute named `severity` has value `2`, then pattern `{severity}` will invoke // severity mapping function provided and the result will be `W`. .set("{severity}, [{timestamp}]: {message}") .mapping(&sevmap) .build() // Configure console sink to write into stdout (also stderr can be configured). .add() .build() // And build the handler. Multiple handlers can be added to a single logger, but right // now we confine ourselves with a single handler. .build() // Build the logger. .build(); ``` -------------------------------- ### Configure Logger with Factory from JSON (C++) Source: https://github.com/3hren/blackhole/blob/master/README.md This C++ snippet illustrates dynamic logger configuration using Blackhole's registry and a JSON configuration file. It utilizes the `configured()` registry to specify a JSON builder and then builds a logger named 'root' by reading configuration from an input stream. This method is recommended for its flexibility and support for dependency injection. ```c++ // Here we are going to build the logger using registry. The registry's responsibility is to // track registered handlers, formatter and sinks, but for now we're not going to register // anything else, since there are predefined types. auto log = blackhole::registry::configured() // Specify the concrete builder type we want to use. It may be JSON, XML, YAML or whatever // else. ->builder(std::ifstream(argv[1])) // Build the logger named "root". .build("root"); ``` -------------------------------- ### Registry for Component Management and Configuration (C++) Source: https://context7.com/3hren/blackhole/llms.txt Explains the role of the registry in managing formatters, sinks, and handlers, enabling runtime registration of custom components and logger construction from configuration files. It shows how to obtain a preconfigured registry or build one manually, and how to use it to load logger configurations from JSON. ```cpp #include #include #include // Get preconfigured registry with all built-in components auto registry = blackhole::registry::configured(); // Or create empty registry and add components manually auto empty_registry = blackhole::registry::empty(); // empty_registry->add(); // empty_registry->add(); // Build logger from JSON using registry // Assuming 'logging.json' exists and is correctly formatted // auto log = registry // ->builder(std::ifstream("logging.json")) // .build("root"); // Registry provides factories for: // Formatters: string, json, tskv // Sinks: console, file, tcp, udp, syslog, null, asynchronous // Handlers: blocking ``` -------------------------------- ### Formatted Message Logging with Facade (C++) Source: https://github.com/3hren/blackhole/blob/master/README.md Illustrates logging a message with placeholders that are filled with runtime arguments. The facade enables dynamic message formatting, similar to `printf` or string interpolation. ```cpp logger.log(0, "{} {} HTTP/1.1 {} {}", "GET", "/static/image.png", 436, 200); ``` -------------------------------- ### Asynchronous Sink Configuration in C++ Source: https://context7.com/3hren/blackhole/llms.txt Demonstrates how to wrap a synchronous sink with an asynchronous sink for non-blocking logging. It shows configurations for both blocking (wait) and non-blocking (drop) overflow policies, with configurable queue capacities. ```cpp #include #include // Create underlying synchronous sink auto file_sink = blackhole::builder("/var/log/app.log") .flush_every(blackhole::megabytes_t(1)) .build(); // Wrap with asynchronous sink auto async_sink = blackhole::builder(std::move(file_sink)) .factor(10) // Queue capacity = 2^10 = 1024 items .wait() // Block when queue full (default) .build(); // Or use drop policy to never block auto async_drop = blackhole::builder( blackhole::builder("/var/log/app.log").build() ) .factor(12) // Queue capacity = 2^12 = 4096 items .drop() // Silently drop when queue full .build(); ``` -------------------------------- ### Logger Facade with Python-like Formatting in C++ Source: https://context7.com/3hren/blackhole/llms.txt Illustrates using the Blackhole logger facade for convenient Python-like string formatting with runtime argument substitution and optional attribute attachment. This facade wraps an existing logger, enabling dynamic log message construction. ```cpp #include #include #include #include auto inner = blackhole::builder() .add(blackhole::builder() .set(blackhole::builder("{severity}, [{timestamp}]: {message}") .build()) .add(blackhole::builder().build()) .build()) .build(); // Wrap logger with facade for formatting support auto log = blackhole::logger_facade(*inner); // Log with Python-like formatting log.log(0, "{} {} HTTP/1.1 {}", "GET", "/api/users", 200); // Log with formatting and attributes log.log(1, "Request processed in {} ms", 45, blackhole::attribute_list{ {"endpoint", "/api/users"}, {"method", "GET"}, {"client_ip", "192.168.1.100"} }); // Log with attributes only log.log(2, "Rate limit exceeded", { {"user_id", 12345}, {"requests_per_minute", 150}, {"limit", 100} }); ``` -------------------------------- ### Build Logger Programmatically with C++ Source: https://context7.com/3hren/blackhole/llms.txt Demonstrates how to programmatically build a logger using Blackhole's builder pattern. It configures severity levels, a blocking handler, a string formatter, and a console sink. This method is suitable for static logging configurations. ```cpp #include #include #include #include #include // Define severity levels enum severity { debug = 0, info = 1, warning = 2, error = 3 }; // Build a logger programmatically auto log = blackhole::builder() .add(blackhole::builder() .set(blackhole::builder("{severity}, [{timestamp}]: {message}") .build()) .add(blackhole::builder() .build()) .build()) .build(); // Basic logging log->log(severity::info, "Server started successfully"); log->log(severity::error, "Connection failed to database"); ``` -------------------------------- ### Configure Console Sink with Colorization (C++) Source: https://github.com/3hren/blackhole/blob/master/README.md This C++ code snippet demonstrates how to configure the console sink with custom colorization for different severity levels using the builder pattern. It allows specifying colors for debug, info, warning, and error messages. ```cpp enum severity { debug = 0, info, warn, error }; auto console = blackhole::builder() .colorize(severity::debug, blackhole::termcolor_t()) .colorize(severity::info, blackhole::termcolor_t::blue()) .colorize(severity::warn, blackhole::termcolor_t::yellow()) .colorize(severity::error, blackhole::termcolor_t::red()) .stdout() .build(); ``` -------------------------------- ### JSON Formatter Builder API (C++) Source: https://github.com/3hren/blackhole/blob/master/README.md Shows how to construct and configure a JSON formatter instance using a fluent builder API in C++. This approach simplifies the creation of complex formatter configurations. ```c++ auto formatter = blackhole::formatter::json_t::builder_t() .route("/fields", {"message", "severity", "timestamp"}) .route("/other") .rename("message", "#message") .rename("timestamp", "#timestamp") .newline() .unique() .build(); ``` -------------------------------- ### String Formatter Configuration in C++ Source: https://context7.com/3hren/blackhole/llms.txt Configures a string formatter for log records using a pattern with placeholders for message, severity, timestamp, process ID, thread ID, and custom attributes. It includes a custom severity mapping function. ```cpp #include #include // Severity mapping function static auto sevmap(int severity, const std::string& spec, blackhole::writer_t& writer) -> void { static const char* mapping[] = {"DEBUG", "INFO", "WARN", "ERROR"}; if (severity >= 0 && severity < 4) { writer.write(spec, mapping[severity]); } else { writer.write(spec, severity); } } // Build string formatter with pattern auto formatter = blackhole::builder( "[{severity:>5}] [{timestamp:{%Y-%m-%d %H:%M:%S.%f}s}] [{process:d}:{thread::x}] {message} {{{...}}}" ) .mapping(&sevmap) .build(); // Pattern placeholders: // {severity:s} - Mapped severity string // {severity:d} - Numeric severity value // {timestamp:{%Y-%m-%d}s} - Formatted timestamp (strftime) // {timestamp:d} - Microseconds since epoch // {process:d} - Process ID // {process:s} - Process name // {thread::x} - Thread ID (hex) // {thread:s} - Thread name // {message} - Log message // {...} - All user attributes ``` -------------------------------- ### JSON Formatter Configuration in C++ Source: https://context7.com/3hren/blackhole/llms.txt Configures a JSON formatter for log records, enabling attribute routing, renaming, and custom timestamp formatting. It supports mapping severity levels to strings and ensuring unique JSON keys. ```cpp #include // Build JSON formatter with routing and options auto formatter = blackhole::builder() // Route specific attributes to nested paths .route("/fields", {"message", "severity", "timestamp"}) // Default route for all other attributes .route("/metadata") // Rename attributes .rename("message", "@message") .rename("timestamp", "@timestamp") // Format timestamp using strftime pattern .timestamp("%Y-%m-%dT%H:%M:%S.%fZ") // Map severity numbers to strings .severity({"DEBUG", "INFO", "WARN", "ERROR"}) // Ensure unique keys (slower but valid JSON) .unique() // Append newline after JSON .newline() .build(); // Output example: // {"fields":{"@message":"Request completed","severity":"INFO","@timestamp":"2024-01-15T10:30:45.123456Z"},"metadata":{"user_id":123,"endpoint":"/api"}} ``` -------------------------------- ### Syslog Sink Configuration in JSON Source: https://context7.com/3hren/blackhole/llms.txt Illustrates the JSON configuration for a syslog sink, enabling log messages to be sent to the system's syslog daemon. It includes custom string formatting and a mapping of Blackhole severities to syslog priorities. ```json // JSON configuration for syslog sink { "root": [{ "type": "blocking", "formatter": { "type": "string", "pattern": "{message}" }, "sinks": [{ "type": "syslog", "priorities": [7, 6, 4, 3] }] }] } // priorities array maps severity 0,1,2,3 to syslog priorities: // 7 = LOG_DEBUG // 6 = LOG_INFO // 4 = LOG_WARNING // 3 = LOG_ERR ``` -------------------------------- ### Scoped Attributes for Contextual Logging in C++ Source: https://context7.com/3hren/blackhole/llms.txt Demonstrates the use of scoped attributes in C++ to automatically attach key-value pairs to log messages within a specific code scope. This is useful for adding context like request IDs or handler names to logs. ```cpp #include #include void handle_request(blackhole::logger_t& logger, const std::string& request_id) { // Attach attributes for duration of this scope blackhole::scope::holder_t scope(logger, { {"request_id", request_id}, {"handler", "api_endpoint"} }); // All logs in this scope automatically include request_id and handler logger.log(1, "Processing request"); // Nested scopes stack attributes { blackhole::scope::holder_t inner_scope(logger, { {"phase", "validation"} }); // Logs here include: request_id, handler, phase logger.log(0, "Validating input parameters"); } // After inner scope ends, only request_id and handler remain logger.log(1, "Request completed"); } ``` -------------------------------- ### File Sink Configuration in C++ Source: https://context7.com/3hren/blackhole/llms.txt Configures a file sink to write log output to a specified file. It supports configurable flush policies based on size or event count, and automatic file reopening for log rotation. ```cpp #include // Build file sink with flush policy auto sink = blackhole::builder("/var/log/app.log") // Flush every 10 megabytes .flush_every(blackhole::megabytes_t(10)) .build(); // Or flush every N events auto sink2 = blackhole::builder("/var/log/app.log") .flush_every(100) // Flush every 100 log events .build(); // Enable stat-based rotation checking (slower but handles moved files) auto sink3 = blackhole::builder("/var/log/app.log") .flush_every(blackhole::mibibytes_t(5)) .rotate_checking_stat() // Reopen if file is moved .build(); // Available binary units: // bytes_t, kilobytes_t, megabytes_t, gigabytes_t // kibibytes_t, mibibytes_t, gibibytes_t ``` -------------------------------- ### Attribute Value Types and Lazy Evaluation (C++) Source: https://context7.com/3hren/blackhole/llms.txt Illustrates how to create and retrieve attribute values of various types, including booleans, integers, floating-point numbers, and strings. It also shows how to use lazy evaluation functions for expensive computations that should only be performed if the log message passes filtering. ```cpp #include #include #include // Create attributes with different value types blackhole::attribute_list attrs{ {"is_authenticated", true}, // bool {"user_id", 12345}, // int64 {"request_count", 1000000ULL}, // uint64 {"response_time", 45.67}, // double {"endpoint", "/api/users"}, // string }; // Retrieve typed values from attribute value blackhole::attribute::value_t val(42); auto num = blackhole::attribute::get(val); // 42 // Lazy evaluation for expensive operations // Assuming 'log' is an initialized logger instance // log.log(0, "Processing data: {}", // [&](std::ostream& stream) -> std::ostream& { // // This lambda only executes if the log message passes filtering // return stream << expensive_computation(); // } // ); ``` -------------------------------- ### Extend Logger with Persistent Attributes (C++) Source: https://context7.com/3hren/blackhole/llms.txt Demonstrates how to extend a base logger with persistent attributes that are automatically included in every log message. This is useful for adding context like service name, version, or instance ID to all logs originating from a specific logger instance. ```cpp #include #include // Create base logger auto base = blackhole::builder() .add(blackhole::builder() .set(blackhole::builder( "[{severity}] {message} {{{...}}}" ).build()) .add(blackhole::builder().build()) .build()) .build(); // Create wrapper with persistent attributes blackhole::wrapper_t service_logger(*base, { {"service", "payment-gateway"}, {"version", "2.1.0"}, {"instance", "prod-01"} }); // All logs include service, version, instance automatically service_logger.log(1, "Transaction processed"); // Output: [1] Transaction processed {instance=prod-01, version=2.1.0, service=payment-gateway} ``` -------------------------------- ### Console Sink Configuration in C++ Source: https://context7.com/3hren/blackhole/llms.txt Configures a console sink to write log output to stdout or stderr. It supports optional severity-based colorization, with TTY detection to automatically disable colors when output is redirected. ```cpp #include #include // Build console sink with colors auto sink = blackhole::builder() .stdout() // or .stderr() .colorize(0, blackhole::termcolor_t::blue()) // debug = blue .colorize(1, blackhole::termcolor_t::green()) // info = green .colorize(2, blackhole::termcolor_t::yellow()) // warning = yellow .colorize(3, blackhole::termcolor_t::red()) // error = red .build(); // Or use custom colorization function auto custom_sink = blackhole::builder() .stderr() .colorize([](const blackhole::record_t& record) -> blackhole::termcolor_t { // Return color based on record properties return blackhole::termcolor_t::yellow(); }) .build(); ``` -------------------------------- ### Check and Set C++ Standard with CMake Source: https://github.com/3hren/blackhole/blob/master/CMakeLists.txt Checks for compiler support for C++14, C++11, and C++0x standards and sets the appropriate standard for the compiler. If no C++11 support is found, it issues a warning. ```cmake include(CheckCXXCompilerFlag) check_cxx_compiler_flag("-std=c++14" COMPILER_SUPPORTS_CXX14) check_cxx_compiler_flag("-std=c++11" COMPILER_SUPPORTS_CXX11) check_cxx_compiler_flag("-std=c++0x" COMPILER_SUPPORTS_CXX0X) if (COMPILER_SUPPORTS_CXX14) add_definitions(-std=c++14) elseif (COMPILER_SUPPORTS_CXX11) add_definitions(-std=c++11) elseif (COMPILER_SUPPORTS_CXX0X) add_definitions(-std=c++0x) else () message(STATUS "The compiler ${CMAKE_CXX_COMPILER} has no C++11 support. Please use a different C++ compiler.") endif () ``` -------------------------------- ### Configure Google Benchmarks for Blackhole Source: https://github.com/3hren/blackhole/blob/master/CMakeLists.txt This snippet configures the build system to include and enable Google Benchmarking for the Blackhole library. It specifies the executable name, source files for benchmarks, and links necessary libraries. ```cmake add_executable(${LIBRARY_NAME}-benchmarks bench/attribute bench/clock bench/cpp14formatter bench/datetime bench/formatter/json bench/formatter/string bench/formatter/tskv.cpp bench/logger bench/main bench/queue bench/record bench/recordbuf bench/system/thread) enable_google_benchmarking(${LIBRARY_NAME}-benchmarks) target_link_libraries(${LIBRARY_NAME}-benchmarks ${LIBRARY_NAME} benchmark ${CMAKE_THREAD_LIBS_INIT}) ``` -------------------------------- ### Include Directories in CMake Source: https://github.com/3hren/blackhole/blob/master/CMakeLists.txt Configures include paths for the project. It adds system include directories for foreign libraries like libcds and rapidjson, and then adds the project's own include directory. ```cmake include_directories(BEFORE SYSTEM ${PROJECT_SOURCE_DIR}/foreign/libcds ${PROJECT_SOURCE_DIR}/foreign/rapidjson/include) include_directories(${PROJECT_SOURCE_DIR}/include) ``` -------------------------------- ### Configure Syslog Sink for System Logging Source: https://github.com/3hren/blackhole/blob/master/README.md The Syslog sink sends log events to the system logger. It requires a 'priorities' array to map severity numbers to syslog priorities. ```json { "type": "syslog", "priorities": [ 0, 1, 2, 3 ] } ``` -------------------------------- ### Configure File Sink for Log Storage Source: https://github.com/3hren/blackhole/blob/master/README.md The file sink writes formatted log events to a specified file path. It supports custom flushing policies based on time intervals or data volume (e.g., '10MB'). Files are opened in append mode by default and flushed on destruction. ```json { "type": "file", "flush": "10MB", "path": "/var/log/blackhole.log" } ``` -------------------------------- ### Find Boost Dependency with CMake Source: https://github.com/3hren/blackhole/blob/master/CMakeLists.txt Locates the Boost library, requiring version 1.46 or later, and specifies the 'system' and 'thread' components. This ensures that the necessary Boost libraries are available for the project. ```cmake find_package(Boost 1.46 REQUIRED COMPONENTS system thread) ``` -------------------------------- ### Configure Null Sink for Discarding Logs Source: https://github.com/3hren/blackhole/blob/master/README.md The null sink is used to discard all logging events. This is useful for benchmarking or when logging is not desired. It requires no specific configuration beyond its type. ```json { "type": "null" } ``` -------------------------------- ### Configure Compiler Warnings for Clang with CMake Source: https://github.com/3hren/blackhole/blob/master/CMakeLists.txt Sets aggressive warning flags for the Clang compiler, including '-Weverything' and several '-Wno-' options to suppress specific warnings, along with '-pedantic' and '-pedantic-errors'. ```cmake if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang") target_compile_options(${LIBRARY_NAME} PRIVATE -Weverything -Wno-c++98-compat -Wno-c++98-compat-pedantic -Wno-padded -Wno-shadow -Wno-weak-vtables -pedantic -pedantic-errors) endif () ``` -------------------------------- ### Configure UDP Socket Sink for Remote Logging Source: https://github.com/3hren/blackhole/blob/master/README.md The UDP socket sink sends formatted log events to a remote host and port using UDP. It requires the 'host' and 'port' options to be specified. ```json { "type": "socket", "host": "remote.server.com", "port": 12345, "protocol": "udp" } ``` -------------------------------- ### Socket Sinks (TCP/UDP/Syslog) Source: https://github.com/3hren/blackhole/blob/master/README.md Category for sinks that send log events to a remote destination via TCP, UDP, or Syslog. ```APIDOC ## Socket Sinks (TCP/UDP/Syslog) ### Description These sinks transmit log events to a remote host and port using TCP, UDP, or Syslog protocols. ### TCP Sink #### Description Emits formatted log events using a connected TCP socket. #### Parameters ##### Query Parameters - **host** (string) - Required - The hostname or IP address of the remote logging server. - **port** (u16) - Required - The port number on the remote host. ### UDP Sink #### Description Emits formatted log events using UDP. #### Parameters ##### Query Parameters - **host** (string) - Required - The hostname or IP address of the remote logging server. - **port** (u16) - Required - The port number on the remote host. ### Syslog Sink #### Description Emits formatted log events to a Syslog server. #### Parameters ##### Query Parameters - **priorities** ([i16]) - Required - An array of integers mapping severity levels to Syslog priorities. ### Request Example (TCP) ```json { "sinks": [ { "type": "socket", "protocol": "tcp", "host": "remote.log.server.com", "port": 514 } ] } ``` ### Response #### Success Response (200) Not applicable #### Response Example Not applicable ``` -------------------------------- ### Configure Compiler Warnings for Other Compilers with CMake Source: https://github.com/3hren/blackhole/blob/master/CMakeLists.txt Sets standard warning flags like '-Wall' and '-Wextra', along with several specific '-W' flags and '-pedantic' options for compilers other than Clang. It also sets linker flags for a version script. ```cmake else () set_target_properties(${LIBRARY_NAME} PROPERTIES COMPILE_FLAGS "-Wall" COMPILE_FLAGS "-Wextra" COMPILE_FLAGS "-Waddress" COMPILE_FLAGS "-Warray-bounds" COMPILE_FLAGS "-Wbuiltin-macro-redefined" COMPILE_FLAGS "-Wconversion" COMPILE_FLAGS "-Wctor-dtor-privacy" COMPILE_FLAGS "-Winit-self" COMPILE_FLAGS "-Wnon-virtual-dtor" COMPILE_FLAGS "-Wold-style-cast" COMPILE_FLAGS "-Woverloaded-virtual" COMPILE_FLAGS "-Wsuggest-attribute=const" COMPILE_FLAGS "-Wsuggest-attribute=noreturn" COMPILE_FLAGS "-Wsuggest-attribute=pure" COMPILE_FLAGS "-Wswitch" COMPILE_FLAGS "-Wunreachable-code" COMPILE_FLAGS "-pedantic" COMPILE_FLAGS "-pedantic-errors" LINK_FLAGS -Wl,--version-script=${PROJECT_SOURCE_DIR}/libblackhole1.version) endif () ``` -------------------------------- ### Console Sink Source: https://github.com/3hren/blackhole/blob/master/README.md The console sink writes log events directly to the standard output or standard error, with optional colorization. ```APIDOC ## Console Sink ### Description Writes log events to the console (stdout/stderr). It automatically detects TTY to enable/disable colorization and uses a global mutex to prevent message intermixing from multiple threads. ### Method Not applicable (configuration only) ### Endpoint Not applicable ### Parameters None ### Request Example ```json { "sinks": [ { "type": "console" } ] } ``` ### Builder Configuration Example (C++) ```cpp enum severity { debug = 0, info, warn, error }; auto console = blackhole::builder() .colorize(severity::debug, blackhole::termcolor_t()) .colorize(severity::info, blackhole::termcolor_t::blue()) .colorize(severity::warn, blackhole::termcolor_t::yellow()) .colorize(severity::error, blackhole::termcolor_t::red()) .stdout() .build(); ``` ### Response #### Success Response (200) Not applicable #### Response Example Not applicable ``` -------------------------------- ### File Sink Source: https://github.com/3hren/blackhole/blob/master/README.md The file sink writes formatted log events to a specified file path, supporting custom flushing policies and binary units. ```APIDOC ## File Sink ### Description Writes log events to a file. The path can include runtime attributes. Files are opened in append mode. Supports custom flushing policies based on record count or byte count (e.g., '10MB'). Files are opened on demand and flushed on destruction. ### Method Not applicable (configuration only) ### Endpoint Not applicable ### Parameters #### Query Parameters - **path** (string) - Required - The path to the log file. Can include placeholders for runtime attributes. - **flush** (string) - Optional - Specifies the flushing policy. Can be a count (e.g., '100 records') or a size (e.g., '10MB', '2GiB'). Defaults to automatic flushing. ### Request Example ```json { "sinks": [ { "type": "file", "flush": "10MB", "path": "/var/log/blackhole.log" } ] } ``` ### Supported Binary Units for `flush` parameter: - Bytes (B) - Kilobytes (kB) - Megabytes (MB) - Gigabytes (GB) - Kibibytes (KiB) - Mibibytes (MiB) - Gibibytes (GiB) ### Response #### Success Response (200) Not applicable #### Response Example Not applicable ``` -------------------------------- ### Link Libraries in CMake Source: https://github.com/3hren/blackhole/blob/master/CMakeLists.txt Links the Boost libraries to the 'blackhole' target. This ensures that the library can use the functionality provided by Boost. ```cmake target_link_libraries(${LIBRARY_NAME} ${Boost_LIBRARIES} ) ``` -------------------------------- ### Enable All Warnings for a Target Source: https://github.com/3hren/blackhole/blob/master/CMakeLists.txt This CMake function enforces strict compiler warnings for a given target when using Clang. It includes options like -Weverything and specific exclusions for compatibility and pedantic settings. ```cmake function(enable_all_warnings TARGET) if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang") target_compile_options(${TARGET} PRIVATE -Weverything -Wno-c++98-compat -Wno-c++98-compat-pedantic -Wno-padded -Wno-shadow -Wno-weak-vtables -pedantic -pedantic-errors) endif () endfunction() ``` -------------------------------- ### Raw Logger Interface Definition (C++) Source: https://github.com/3hren/blackhole/blob/master/README.md Defines the raw logger interface with methods for logging messages with and without attributes, and with lazy message formatting. This interface is designed for performance and flexibility. ```cpp class logger_t { public: virtual ~logger_t() = 0; virtual auto log(severity_t severity, const message_t& message) -> void = 0; virtual auto log(severity_t severity, const message_t& message, attribute_pack& pack) -> void = 0; virtual auto log(severity_t severity, const lazy_message_t& message, attribute_pack& pack) -> void = 0; virtual auto manager() -> scope::manager_t& = 0; }; ``` -------------------------------- ### Null Sink Source: https://github.com/3hren/blackhole/blob/master/README.md The null sink is used to discard all log events, typically for benchmarking or disabling logging. ```APIDOC ## Null Sink ### Description This sink ignores all incoming log records and is useful for disabling logging or for performance benchmarking. ### Method Not applicable (configuration only) ### Endpoint Not applicable ### Parameters None ### Request Example ```json { "sinks": [ { "type": "null" } ] } ``` ### Response #### Success Response (200) Not applicable #### Response Example Not applicable ``` -------------------------------- ### Configure TCP Socket Sink for Remote Logging Source: https://github.com/3hren/blackhole/blob/master/README.md The TCP socket sink sends formatted log events to a remote host and port using a connected TCP socket. It requires the 'host' and 'port' options to be specified. ```json { "type": "socket", "host": "remote.server.com", "port": 12345, "protocol": "tcp" } ``` -------------------------------- ### Configure Console Sink for Terminal Output Source: https://github.com/3hren/blackhole/blob/master/README.md The console sink writes log events directly to the terminal. It automatically detects TTY to enable or disable colorized output. A global mutex is used to prevent message intermixing when logging from multiple threads. ```json { "type": "console" } ``` -------------------------------- ### Define Shared Library with CMake Source: https://github.com/3hren/blackhole/blob/master/CMakeLists.txt Adds a shared library named 'blackhole' to the build. It lists all the source files that will be compiled into this library, organizing the project's code. ```cmake add_library(${LIBRARY_NAME} SHARED src/attribute.cpp src/config/factory.cpp src/config/json.cpp src/config/node.cpp src/config/option.cpp src/datetime/generator.linux.cpp src/datetime/generator.other.cpp src/essentials.cpp src/filter/severity.cpp src/format.cpp src/formatter/json.cpp src/formatter/mod.cpp src/formatter/string.cpp src/formatter/string/error.cpp src/formatter/string/grammar.cpp src/formatter/string/parser.cpp src/formatter/string/token.cpp src/formatter/tskv.cpp src/handler.cpp src/handler/blocking.cpp src/handler/dev.cpp src/logger.cpp src/procname.cpp src/record.cpp src/registry.cpp src/root.cpp src/scope/holder.cpp src/scope/manager.cpp src/scope/watcher.cpp src/sink/asynchronous.cpp src/sink/asynchronous.p.cpp src/sink/console.cpp src/sink/file.cpp src/sink/null.cpp src/sink/socket/tcp.cpp src/sink/socket/udp.cpp src/sink/syslog.cpp src/termcolor.cpp src/wrapper.cpp ) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.