From 564982c818666787096e5ad7a81a2d2f036aba36 Mon Sep 17 00:00:00 2001 From: Abtin Keshavarzian Date: Thu, 17 Feb 2022 15:50:45 -0800 Subject: [PATCH] [log] implement new logging model with module name support (#7385) This commit implements new logging model in OpenThread. Each core module can specify its own module name using `RegisterLogModule()`. The registered log module name is then included in the all the log messages emitted from the specific file. This model replaces and enhances the log region model. --- Android.mk | 2 +- etc/cmake/options.cmake | 1 - examples/apps/cli/cli_uart.cpp | 2 +- examples/apps/cli/main.c | 10 +- examples/common-switches.mk | 2 +- examples/platforms/cc2538/radio.c | 2 +- examples/platforms/simulation/alarm.c | 2 +- examples/platforms/simulation/flash.c | 2 +- examples/platforms/simulation/logging.c | 27 +- examples/platforms/utils/otns_utils.cpp | 6 +- .../platforms/utils/soft_source_match_table.c | 3 +- include/openthread/cli.h | 10 - include/openthread/instance.h | 2 +- include/openthread/logging.h | 138 + include/openthread/platform/logging.h | 20 +- src/cli/cli.cpp | 16 - src/cli/cli.hpp | 3 +- src/cli/cli_output.cpp | 8 +- src/core/BUILD.gn | 6 +- src/core/CMakeLists.txt | 4 +- src/core/Makefile.am | 5 +- src/core/api/instance_api.cpp | 2 - src/core/api/ip6_api.cpp | 1 - src/core/api/logging_api.cpp | 170 +- src/core/api/tasklet_api.cpp | 1 - src/core/backbone_router/backbone_tmf.cpp | 8 +- src/core/backbone_router/bbr_leader.cpp | 18 +- src/core/backbone_router/bbr_leader.hpp | 2 +- src/core/backbone_router/bbr_local.cpp | 14 +- src/core/backbone_router/bbr_local.hpp | 2 +- src/core/backbone_router/bbr_manager.cpp | 51 +- .../multicast_listeners_table.cpp | 8 +- src/core/backbone_router/ndproxy_table.cpp | 20 +- src/core/border_router/routing_manager.cpp | 148 +- src/core/coap/coap.cpp | 34 +- src/core/coap/coap_secure.cpp | 8 +- src/core/common/instance.cpp | 3 +- src/core/common/instance.hpp | 14 +- src/core/common/log.cpp | 262 ++ src/core/common/log.hpp | 346 +++ src/core/common/logging.cpp | 351 --- src/core/common/logging.hpp | 2547 ----------------- src/core/common/message.cpp | 6 +- src/core/common/notifier.cpp | 17 +- src/core/common/random_manager.cpp | 1 - src/core/common/settings.cpp | 58 +- src/core/common/settings.hpp | 4 +- src/core/common/timer.cpp | 1 - src/core/config/logging.h | 228 +- .../config/openthread-core-config-check.h | 84 + src/core/mac/data_poll_handler.cpp | 12 +- src/core/mac/data_poll_sender.cpp | 24 +- src/core/mac/link_raw.cpp | 17 +- src/core/mac/link_raw.hpp | 2 +- src/core/mac/mac.cpp | 84 +- src/core/mac/mac_frame.cpp | 4 +- src/core/mac/sub_mac.cpp | 34 +- src/core/meshcop/announce_begin_client.cpp | 6 +- src/core/meshcop/border_agent.cpp | 34 +- src/core/meshcop/commissioner.cpp | 53 +- src/core/meshcop/dataset.cpp | 7 +- src/core/meshcop/dataset_local.cpp | 8 +- src/core/meshcop/dataset_manager.cpp | 20 +- src/core/meshcop/dataset_manager_ftd.cpp | 8 +- src/core/meshcop/dataset_updater.cpp | 2 +- src/core/meshcop/dtls.cpp | 40 +- src/core/meshcop/energy_scan_client.cpp | 10 +- src/core/meshcop/joiner.cpp | 38 +- src/core/meshcop/joiner.hpp | 2 +- src/core/meshcop/joiner_router.cpp | 24 +- src/core/meshcop/meshcop.cpp | 9 +- src/core/meshcop/meshcop.hpp | 2 +- src/core/meshcop/meshcop_leader.cpp | 16 +- src/core/meshcop/panid_query_client.cpp | 10 +- src/core/net/dhcp6_client.cpp | 10 +- src/core/net/dhcp6_server.cpp | 6 +- src/core/net/dns_client.cpp | 6 +- src/core/net/dns_dso.cpp | 34 +- src/core/net/dns_types.cpp | 1 - src/core/net/dnssd_server.cpp | 22 +- src/core/net/icmp6.cpp | 14 +- src/core/net/ip6.cpp | 42 +- src/core/net/ip6_filter.cpp | 8 +- src/core/net/sntp_client.cpp | 8 +- src/core/net/srp_client.cpp | 56 +- src/core/net/srp_client.hpp | 2 +- src/core/net/srp_server.cpp | 78 +- src/core/net/tcp6.cpp | 24 +- src/core/radio/trel_interface.cpp | 24 +- src/core/radio/trel_link.cpp | 20 +- src/core/radio/trel_packet.cpp | 1 - src/core/thread/address_resolver.cpp | 50 +- src/core/thread/announce_begin_server.cpp | 6 +- src/core/thread/announce_sender.cpp | 14 +- src/core/thread/csl_tx_scheduler.cpp | 8 +- src/core/thread/discover_scanner.cpp | 1 - src/core/thread/dua_manager.cpp | 40 +- src/core/thread/energy_scan_server.cpp | 8 +- src/core/thread/indirect_sender.cpp | 1 - src/core/thread/key_manager.cpp | 6 +- src/core/thread/link_metrics.cpp | 20 +- src/core/thread/mesh_forwarder.cpp | 75 +- src/core/thread/mesh_forwarder.hpp | 15 +- src/core/thread/mesh_forwarder_ftd.cpp | 47 +- src/core/thread/mle.cpp | 81 +- src/core/thread/mle.hpp | 12 +- src/core/thread/mle_router.cpp | 72 +- src/core/thread/mlr_manager.cpp | 38 +- src/core/thread/network_data.cpp | 6 +- src/core/thread/network_data_leader.cpp | 4 +- src/core/thread/network_data_leader_ftd.cpp | 22 +- src/core/thread/network_data_local.cpp | 12 +- src/core/thread/network_data_publisher.cpp | 31 +- src/core/thread/network_diagnostic.cpp | 34 +- src/core/thread/panid_query_server.cpp | 8 +- src/core/thread/radio_selector.cpp | 36 +- src/core/thread/radio_selector.hpp | 5 +- src/core/thread/router_table.cpp | 8 +- src/core/thread/src_match_controller.cpp | 26 +- src/core/thread/time_sync_service.cpp | 29 +- src/core/thread/topology.cpp | 1 - src/core/utils/channel_manager.cpp | 52 +- src/core/utils/channel_monitor.cpp | 16 +- src/core/utils/child_supervision.cpp | 12 +- src/core/utils/jam_detector.cpp | 16 +- src/core/utils/otns.cpp | 10 +- src/core/utils/slaac_address.cpp | 22 +- src/lib/spinel/radio_spinel_impl.hpp | 2 +- src/ncp/ncp_base.cpp | 10 - src/posix/main.c | 1 - src/posix/platform/firewall.cpp | 4 +- src/posix/platform/firewall.hpp | 1 - src/posix/platform/hdlc_interface.cpp | 3 +- src/posix/platform/misc.cpp | 2 +- src/posix/platform/multicast_routing.cpp | 3 +- src/posix/platform/netif.cpp | 6 +- src/posix/platform/platform-posix.h | 3 +- src/posix/platform/settings.cpp | 12 + src/posix/platform/spi_interface.cpp | 12 +- src/posix/platform/system.cpp | 9 - src/posix/platform/trel.cpp | 6 +- src/posix/platform/utils.cpp | 3 +- tests/scripts/thread-cert/node.py | 2 +- tests/toranj/openthread-core-toranj-config.h | 8 - tests/unit/test_pskc.cpp | 1 - tools/harness-thci/OpenThread.py | 18 +- 146 files changed, 2170 insertions(+), 4282 deletions(-) create mode 100644 src/core/common/log.cpp create mode 100644 src/core/common/log.hpp delete mode 100644 src/core/common/logging.cpp diff --git a/Android.mk b/Android.mk index dba15249f..4e3fa7df0 100644 --- a/Android.mk +++ b/Android.mk @@ -228,7 +228,7 @@ LOCAL_SRC_FILES := \ src/core/common/heap_data.cpp \ src/core/common/heap_string.cpp \ src/core/common/instance.cpp \ - src/core/common/logging.cpp \ + src/core/common/log.cpp \ src/core/common/message.cpp \ src/core/common/notifier.cpp \ src/core/common/random_manager.cpp \ diff --git a/etc/cmake/options.cmake b/etc/cmake/options.cmake index e8c921262..6eec0d623 100644 --- a/etc/cmake/options.cmake +++ b/etc/cmake/options.cmake @@ -381,7 +381,6 @@ if(OT_FULL_LOGS) target_compile_definitions(ot-config INTERFACE "OPENTHREAD_CONFIG_LOG_LEVEL=OT_LOG_LEVEL_DEBG") endif() target_compile_definitions(ot-config INTERFACE "OPENTHREAD_CONFIG_LOG_PREPEND_LEVEL=1") - target_compile_definitions(ot-config INTERFACE "OPENTHREAD_CONFIG_LOG_PREPEND_REGION=1") endif() option(OT_OTNS "enable OTNS support") diff --git a/examples/apps/cli/cli_uart.cpp b/examples/apps/cli/cli_uart.cpp index 2b3b10f1b..b7fa5028d 100644 --- a/examples/apps/cli/cli_uart.cpp +++ b/examples/apps/cli/cli_uart.cpp @@ -33,11 +33,11 @@ #include #include +#include #include "cli/cli_config.h" #include "common/code_utils.hpp" #include "common/debug.hpp" -#include "common/logging.hpp" #include "utils/uart.h" #if OPENTHREAD_POSIX diff --git a/examples/apps/cli/main.c b/examples/apps/cli/main.c index 4d0440c12..bdb071579 100644 --- a/examples/apps/cli/main.c +++ b/examples/apps/cli/main.c @@ -150,21 +150,13 @@ pseudo_reset: return 0; } -/* - * Provide, if required an "otPlatLog()" function - */ #if OPENTHREAD_CONFIG_LOG_OUTPUT == OPENTHREAD_CONFIG_LOG_OUTPUT_APP void otPlatLog(otLogLevel aLogLevel, otLogRegion aLogRegion, const char *aFormat, ...) { va_list ap; + va_start(ap, aFormat); otCliPlatLogv(aLogLevel, aLogRegion, aFormat, ap); va_end(ap); } - -void otPlatLogLine(otLogLevel aLogLevel, otLogRegion aLogRegion, const char *aLogLine) -{ - otCliPlatLogLine(aLogLevel, aLogRegion, aLogLine); -} - #endif diff --git a/examples/common-switches.mk b/examples/common-switches.mk index 1795f88db..2e947b0df 100644 --- a/examples/common-switches.mk +++ b/examples/common-switches.mk @@ -388,5 +388,5 @@ endif COMMONCFLAGS += -DOPENTHREAD_SPINEL_CONFIG_RCP_RESTORATION_MAX_COUNT=${RCP_RESTORATION_MAX_COUNT} ifeq ($(FULL_LOGS),1) -COMMONCFLAGS += -DOPENTHREAD_CONFIG_LOG_LEVEL=OT_LOG_LEVEL_DEBG -DOPENTHREAD_CONFIG_LOG_PREPEND_LEVEL=1 -DOPENTHREAD_CONFIG_LOG_PREPEND_REGION=1 +COMMONCFLAGS += -DOPENTHREAD_CONFIG_LOG_LEVEL=OT_LOG_LEVEL_DEBG -DOPENTHREAD_CONFIG_LOG_PREPEND_LEVEL=1 endif diff --git a/examples/platforms/cc2538/radio.c b/examples/platforms/cc2538/radio.c index a8bbd99e7..0878f115d 100644 --- a/examples/platforms/cc2538/radio.c +++ b/examples/platforms/cc2538/radio.c @@ -33,12 +33,12 @@ */ #include +#include #include #include #include #include "platform-cc2538.h" -#include "common/logging.hpp" #include "utils/code_utils.h" #define RFCORE_XREG_RFIRQM0 0x4008868C // RF interrupt masks diff --git a/examples/platforms/simulation/alarm.c b/examples/platforms/simulation/alarm.c index e71ddd49f..2795672b6 100644 --- a/examples/platforms/simulation/alarm.c +++ b/examples/platforms/simulation/alarm.c @@ -47,11 +47,11 @@ timer_t sMicroTimer; #endif // __linux__ +#include #include #include #include -#include "core/common/logging.hpp" #include "lib/platform/exit_code.h" #define MS_PER_S 1000 diff --git a/examples/platforms/simulation/flash.c b/examples/platforms/simulation/flash.c index 561ad45da..ce07f3a70 100644 --- a/examples/platforms/simulation/flash.c +++ b/examples/platforms/simulation/flash.c @@ -37,9 +37,9 @@ #include #include +#include #include -#include "core/common/logging.hpp" #include "lib/platform/exit_code.h" static int sFlashFd = -1; diff --git a/examples/platforms/simulation/logging.c b/examples/platforms/simulation/logging.c index 5b0d6eab3..8b90c4334 100644 --- a/examples/platforms/simulation/logging.c +++ b/examples/platforms/simulation/logging.c @@ -43,37 +43,22 @@ #include "utils/code_utils.h" -// Macro to append content to end of the log string. - -#define LOG_PRINTF(...) \ - charsWritten = snprintf(&logString[offset], sizeof(logString) - offset, __VA_ARGS__); \ - otEXPECT_ACTION(charsWritten >= 0, logString[offset] = 0); \ - offset += (unsigned int)charsWritten; \ - otEXPECT_ACTION(offset < sizeof(logString), logString[sizeof(logString) - 1] = 0) - #if (OPENTHREAD_CONFIG_LOG_OUTPUT == OPENTHREAD_CONFIG_LOG_OUTPUT_PLATFORM_DEFINED) OT_TOOL_WEAK void otPlatLog(otLogLevel aLogLevel, otLogRegion aLogRegion, const char *aFormat, ...) { OT_UNUSED_VARIABLE(aLogLevel); OT_UNUSED_VARIABLE(aLogRegion); - char logString[512]; - unsigned int offset; - int charsWritten; - va_list args; + char logString[512]; + int offset; + va_list args; - offset = 0; - - LOG_PRINTF("[%d] ", gNodeId); + offset = snprintf(logString, sizeof(logString), "[%d]", gNodeId); va_start(args, aFormat); - charsWritten = vsnprintf(&logString[offset], sizeof(logString) - offset, aFormat, args); + vsnprintf(&logString[offset], sizeof(logString) - (uint16_t)offset, aFormat, args); va_end(args); - otEXPECT_ACTION(charsWritten >= 0, logString[offset] = 0); - -exit: syslog(LOG_CRIT, "%s", logString); } - -#endif // #if (OPENTHREAD_CONFIG_LOG_OUTPUT == OPENTHREAD_CONFIG_LOG_OUTPUT_PLATFORM_DEFINED) +#endif diff --git a/examples/platforms/utils/otns_utils.cpp b/examples/platforms/utils/otns_utils.cpp index b2875e1b5..e343503d1 100644 --- a/examples/platforms/utils/otns_utils.cpp +++ b/examples/platforms/utils/otns_utils.cpp @@ -31,7 +31,9 @@ #include #include -#include "common/logging.hpp" +#include "common/log.hpp" + +using namespace ot; /* * Implementation note: @@ -43,7 +45,7 @@ OT_TOOL_WEAK void otPlatOtnsStatus(const char *aStatus) { - otLogOtns("[OTNS] %s", aStatus); + LogAlways("[OTNS] %s", aStatus); } #endif // OPENTHREAD_CONFIG_OTNS_ENABLE diff --git a/examples/platforms/utils/soft_source_match_table.c b/examples/platforms/utils/soft_source_match_table.c index 67fbdcad7..458d1b5c5 100644 --- a/examples/platforms/utils/soft_source_match_table.c +++ b/examples/platforms/utils/soft_source_match_table.c @@ -39,7 +39,8 @@ #include #include -#include "common/logging.hpp" +#include + #include "utils/code_utils.h" #if RADIO_CONFIG_SRC_MATCH_SHORT_ENTRY_NUM || RADIO_CONFIG_SRC_MATCH_EXT_ENTRY_NUM diff --git a/include/openthread/cli.h b/include/openthread/cli.h index 56c986828..5878ac4de 100644 --- a/include/openthread/cli.h +++ b/include/openthread/cli.h @@ -146,16 +146,6 @@ void otCliAppendResult(otError aError); */ void otCliPlatLogv(otLogLevel aLogLevel, otLogRegion aLogRegion, const char *aFormat, va_list aArgs); -/** - * Function to write the OpenThread Log to the CLI console. - * - * @param[in] aLogLevel The log level. - * @param[in] aLogRegion The log region. - * @param[in] aLogLine A pointer to the log line string. - * - */ -void otCliPlatLogLine(otLogLevel aLogLevel, otLogRegion aLogRegion, const char *aLogLine); - /** * @} * diff --git a/include/openthread/instance.h b/include/openthread/instance.h index 246d132a6..06800a5b7 100644 --- a/include/openthread/instance.h +++ b/include/openthread/instance.h @@ -53,7 +53,7 @@ extern "C" { * @note This number versions both OpenThread platform and user APIs. * */ -#define OPENTHREAD_API_VERSION (192) +#define OPENTHREAD_API_VERSION (193) /** * @addtogroup api-instance diff --git a/include/openthread/logging.h b/include/openthread/logging.h index b40630139..b07e64367 100644 --- a/include/openthread/logging.h +++ b/include/openthread/logging.h @@ -76,6 +76,144 @@ otLogLevel otLoggingGetLevel(void); */ otError otLoggingSetLevel(otLogLevel aLogLevel); +/** + * This function emits a log message at critical log level. + * + * This function is intended for use by platform. If `OPENTHREAD_CONFIG_LOG_PLATFORM` is not set or the current log + * level is below critical, this function does not emit any log message. + * + * @param[in] aFormat The format string. + * @param[in] ... Arguments for the format specification. + * + */ +void otLogCritPlat(const char *aFormat, ...); + +/** + * This function emits a log message at warning log level. + * + * This function is intended for use by platform. If `OPENTHREAD_CONFIG_LOG_PLATFORM` is not set or the current log + * level is below warning, this function does not emit any log message. + * + * @param[in] aFormat The format string. + * @param[in] ... Arguments for the format specification. + * + */ +void otLogWarnPlat(const char *aFormat, ...); + +/** + * This function emits a log message at note log level. + * + * This function is intended for use by platform. If `OPENTHREAD_CONFIG_LOG_PLATFORM` is not set or the current log + * level is below note, this function does not emit any log message. + * + * @param[in] aFormat The format string. + * @param[in] ... Arguments for the format specification. + * + */ +void otLogNotePlat(const char *aFormat, ...); + +/** + * This function emits a log message at info log level. + * + * This function is intended for use by platform. If `OPENTHREAD_CONFIG_LOG_PLATFORM` is not set or the current log + * level is below info, this function does not emit any log message. + * + * @param[in] aFormat The format string. + * @param[in] ... Arguments for the format specification. + * + */ +void otLogInfoPlat(const char *aFormat, ...); + +/** + * This function emits a log message at debug log level. + * + * This function is intended for use by platform. If `OPENTHREAD_CONFIG_LOG_PLATFORM` is not set or the current log + * level is below debug, this function does not emit any log message. + * + * @param[in] aFormat The format string. + * @param[in] ... Arguments for the format specification. + * + */ +void otLogDebgPlat(const char *aFormat, ...); + +/** + * This function generates a memory dump at critical log level. + * + * If `OPENTHREAD_CONFIG_LOG_PLATFORM` or `OPENTHREAD_CONFIG_LOG_PKT_DUMP` is not set or the current log level is below + * critical this function does not emit any log message. + * + * @param[in] aText A string that is printed before the bytes. + * @param[in] aData A pointer to the data buffer. + * @param[in] aDataLength Number of bytes in @p aData. + * + */ +void otDumpCritPlat(const char *aText, const void *aData, uint16_t aDataLength); + +/** + * This function generates a memory dump at warning log level. + * + * If `OPENTHREAD_CONFIG_LOG_PLATFORM` or `OPENTHREAD_CONFIG_LOG_PKT_DUMP` is not set or the current log level is below + * warning this function does not emit any log message. + * + * @param[in] aText A string that is printed before the bytes. + * @param[in] aData A pointer to the data buffer. + * @param[in] aDataLength Number of bytes in @p aData. + * + */ +void otDumpWarnPlat(const char *aText, const void *aData, uint16_t aDataLength); + +/** + * This function generates a memory dump at note log level. + * + * If `OPENTHREAD_CONFIG_LOG_PLATFORM` or `OPENTHREAD_CONFIG_LOG_PKT_DUMP` is not set or the current log level is below + * note this function does not emit any log message. + * + * @param[in] aText A string that is printed before the bytes. + * @param[in] aData A pointer to the data buffer. + * @param[in] aDataLength Number of bytes in @p aData. + * + */ +void otDumpNotePlat(const char *aText, const void *aData, uint16_t aDataLength); + +/** + * This function generates a memory dump at info log level. + * + * If `OPENTHREAD_CONFIG_LOG_PLATFORM` or `OPENTHREAD_CONFIG_LOG_PKT_DUMP` is not set or the current log level is below + * info this function does not emit any log message. + * + * @param[in] aText A string that is printed before the bytes. + * @param[in] aData A pointer to the data buffer. + * @param[in] aDataLength Number of bytes in @p aData. + * + */ +void otDumpInfoPlat(const char *aText, const void *aData, uint16_t aDataLength); + +/** + * This function generates a memory dump at debug log level. + * + * If `OPENTHREAD_CONFIG_LOG_PLATFORM` or `OPENTHREAD_CONFIG_LOG_PKT_DUMP` is not set or the current log level is below + * debug this function does not emit any log message. + * + * @param[in] aText A string that is printed before the bytes. + * @param[in] aData A pointer to the data buffer. + * @param[in] aDataLength Number of bytes in @p aData. + * + */ +void otDumpDebgPlat(const char *aText, const void *aData, uint16_t aDataLength); + +/** + * This function emits a log message at a given log level. + * + * This function is intended for use by CLI only. If `OPENTHREAD_CONFIG_LOG_CLI` is not set or the current log + * level is below the given log level, this function does not emit any log message. + * + * @param[in] aLogLevel The log level. + * @param[in] aFormat The format string. + * @param[in] ... Arguments for the format specification. + * + */ +void otLogCli(otLogLevel aLogLevel, const char *aFormat, ...); + /** * @} * diff --git a/include/openthread/platform/logging.h b/include/openthread/platform/logging.h index 4c62744c3..8d9d36f11 100644 --- a/include/openthread/platform/logging.h +++ b/include/openthread/platform/logging.h @@ -115,6 +115,10 @@ typedef int otLogLevel; /** * This enumeration represents log regions. * + * The support for log region is removed and instead each core module can define its own name to appended to the logs. + * However, the `otLogRegion` enumeration is still defined as before to help with platforms which we may be using it + * in their `otPlatLog()` implementation. The OT core will always emit all logs with `OT_LOG_REGION_CORE`. + * */ typedef enum otLogRegion { @@ -146,6 +150,9 @@ typedef enum otLogRegion /** * This function outputs logs. * + * Note that the support for log region is removed. The OT core will always emit all logs with `OT_LOG_REGION_CORE` + * as @p aLogRegion. + * * @param[in] aLogLevel The log level. * @param[in] aLogRegion The log region. * @param[in] aFormat A pointer to the format string. @@ -154,19 +161,6 @@ typedef enum otLogRegion */ void otPlatLog(otLogLevel aLogLevel, otLogRegion aLogRegion, const char *aFormat, ...); -/** - * This (optional) platform function outputs a prepared log line. - * - * Note that this function is optional and if not provided by platform layer, a default (weak) implementation is - * provided and used by OpenThread core as `otPlatLog(aLogLevel, aLogResion, "%s", aLogLine)`. - * - * @param[in] aLogLevel The log level. - * @param[in] aLogRegion The log region. - * @param[in] aLogLine A pointer to a log line string. - * - */ -void otPlatLogLine(otLogLevel aLogLevel, otLogRegion aLogRegion, const char *aLogLine); - /** * @} * diff --git a/src/cli/cli.cpp b/src/cli/cli.cpp index 74713cdfe..f74931c06 100644 --- a/src/cli/cli.cpp +++ b/src/cli/cli.cpp @@ -85,7 +85,6 @@ #include #endif -#include "common/logging.hpp" #include "common/new.hpp" #include "common/string.hpp" #include "mac/channel_mask.hpp" @@ -5049,21 +5048,6 @@ exit: return; } -extern "C" void otCliPlatLogLine(otLogLevel aLogLevel, otLogRegion aLogRegion, const char *aLogLine) -{ - OT_UNUSED_VARIABLE(aLogLevel); - OT_UNUSED_VARIABLE(aLogRegion); - - VerifyOrExit(Interpreter::IsInitialized()); - - Interpreter::GetInterpreter().SetEmittingCommandOutput(false); - Interpreter::GetInterpreter().OutputLine(aLogLine); - Interpreter::GetInterpreter().SetEmittingCommandOutput(true); - -exit: - return; -} - } // namespace Cli } // namespace ot diff --git a/src/cli/cli.hpp b/src/cli/cli.hpp index 0f5784725..439ea0899 100644 --- a/src/cli/cli.hpp +++ b/src/cli/cli.hpp @@ -46,6 +46,7 @@ #include #include #include +#include #include #include #if OPENTHREAD_CONFIG_TCP_ENABLE && OPENTHREAD_CONFIG_CLI_TCP_ENABLE @@ -89,7 +90,6 @@ namespace ot { namespace Cli { extern "C" void otCliPlatLogv(otLogLevel, otLogRegion, const char *, va_list); -extern "C" void otCliPlatLogLine(otLogLevel, otLogRegion, const char *); extern "C" void otCliAppendResult(otError aError); extern "C" void otCliOutputBytes(const uint8_t *aBytes, uint8_t aLength); extern "C" void otCliOutputFormat(const char *aFmt, ...); @@ -107,7 +107,6 @@ class Interpreter : public Output friend class SrpClient; #endif friend void otCliPlatLogv(otLogLevel, otLogRegion, const char *, va_list); - friend void otCliPlatLogLine(otLogLevel, otLogRegion, const char *); friend void otCliAppendResult(otError aError); friend void otCliOutputBytes(const uint8_t *aBytes, uint8_t aLength); friend void otCliOutputFormat(const char *aFmt, ...); diff --git a/src/cli/cli_output.cpp b/src/cli/cli_output.cpp index e4d8f4c21..9fc87aea4 100644 --- a/src/cli/cli_output.cpp +++ b/src/cli/cli_output.cpp @@ -40,8 +40,8 @@ #if OPENTHREAD_FTD || OPENTHREAD_MTD #include #endif +#include -#include "common/logging.hpp" #include "common/string.hpp" namespace ot { @@ -279,7 +279,7 @@ void Output::OutputFormatV(const char *aFormat, va_list aArguments) if (lineEnd > mOutputString) { - otLogNoteCli("Output: %s", mOutputString); + otLogCli(OT_LOG_LEVEL_NOTE, "Output: %s", mOutputString); } lineEnd++; @@ -320,7 +320,7 @@ void Output::OutputFormatV(const char *aFormat, va_list aArguments) if (truncated) { - otLogNoteCli("Output: %s ...", mOutputString); + otLogCli(OT_LOG_LEVEL_NOTE, "Output: %s ...", mOutputString); mOutputLength = 0; } @@ -339,7 +339,7 @@ void Output::LogInput(const Arg *aArgs) inputString.Append(isFirst ? "%s" : " %s", aArgs->GetCString()); } - otLogNoteCli("Input: %s", inputString.AsCString()); + otLogCli(OT_LOG_LEVEL_NOTE, "Input: %s", inputString.AsCString()); } #endif diff --git a/src/core/BUILD.gn b/src/core/BUILD.gn index 283691972..15a75fc1a 100644 --- a/src/core/BUILD.gn +++ b/src/core/BUILD.gn @@ -259,7 +259,6 @@ if (openthread_enable_core_config_args) { if (openthread_config_full_logs) { defines += [ "OPENTHREAD_CONFIG_LOG_LEVEL=OT_LOG_LEVEL_DEBG" ] defines += [ "OPENTHREAD_CONFIG_LOG_PREPEND_LEVEL=1" ] - defines += [ "OPENTHREAD_CONFIG_LOG_PREPEND_REGION=1" ] } if (openthread_config_otns_enable) { @@ -405,7 +404,8 @@ openthread_core_files = [ "common/linked_list.hpp", "common/locator.hpp", "common/locator_getters.hpp", - "common/logging.cpp", + "common/log.cpp", + "common/log.hpp", "common/logging.hpp", "common/message.cpp", "common/message.hpp", @@ -699,7 +699,7 @@ openthread_radio_sources = [ "common/binary_search.hpp", "common/error.hpp", "common/instance.cpp", - "common/logging.cpp", + "common/log.cpp", "common/random_manager.cpp", "common/string.cpp", "common/tasklet.cpp", diff --git a/src/core/CMakeLists.txt b/src/core/CMakeLists.txt index 95ac99841..032d61c2e 100644 --- a/src/core/CMakeLists.txt +++ b/src/core/CMakeLists.txt @@ -101,7 +101,7 @@ set(COMMON_SOURCES common/heap_data.cpp common/heap_string.cpp common/instance.cpp - common/logging.cpp + common/log.cpp common/message.cpp common/notifier.cpp common/random_manager.cpp @@ -246,7 +246,7 @@ set(RADIO_COMMON_SOURCES common/binary_search.cpp common/error.cpp common/instance.cpp - common/logging.cpp + common/log.cpp common/random_manager.cpp common/string.cpp common/tasklet.cpp diff --git a/src/core/Makefile.am b/src/core/Makefile.am index 253ad90d9..60d577538 100644 --- a/src/core/Makefile.am +++ b/src/core/Makefile.am @@ -191,7 +191,7 @@ SOURCES_COMMON = \ common/heap_data.cpp \ common/heap_string.cpp \ common/instance.cpp \ - common/logging.cpp \ + common/log.cpp \ common/message.cpp \ common/notifier.cpp \ common/random_manager.cpp \ @@ -336,7 +336,7 @@ RADIO_SOURCES_COMMON = \ common/binary_search.cpp \ common/error.cpp \ common/instance.cpp \ - common/logging.cpp \ + common/log.cpp \ common/random_manager.cpp \ common/string.cpp \ common/tasklet.cpp \ @@ -442,6 +442,7 @@ HEADERS_COMMON = \ common/linked_list.hpp \ common/locator.hpp \ common/locator_getters.hpp \ + common/log.hpp \ common/logging.hpp \ common/message.hpp \ common/new.hpp \ diff --git a/src/core/api/instance_api.cpp b/src/core/api/instance_api.cpp index 76ec953ca..5557f687f 100644 --- a/src/core/api/instance_api.cpp +++ b/src/core/api/instance_api.cpp @@ -38,7 +38,6 @@ #include "common/as_core_type.hpp" #include "common/locator_getters.hpp" -#include "common/logging.hpp" #include "common/new.hpp" #include "radio/radio.hpp" @@ -64,7 +63,6 @@ otInstance *otInstanceInit(void *aInstanceBuffer, size_t *aInstanceBufferSize) Instance *instance; instance = Instance::Init(aInstanceBuffer, aInstanceBufferSize); - otLogInfoApi("otInstance Initialized"); return instance; } diff --git a/src/core/api/ip6_api.cpp b/src/core/api/ip6_api.cpp index a65dc552c..b12b35ec5 100644 --- a/src/core/api/ip6_api.cpp +++ b/src/core/api/ip6_api.cpp @@ -37,7 +37,6 @@ #include "common/as_core_type.hpp" #include "common/locator_getters.hpp" -#include "common/logging.hpp" #include "utils/slaac_address.hpp" using namespace ot; diff --git a/src/core/api/logging_api.cpp b/src/core/api/logging_api.cpp index b00147c52..ce0aff146 100644 --- a/src/core/api/logging_api.cpp +++ b/src/core/api/logging_api.cpp @@ -33,19 +33,17 @@ #include "openthread-core-config.h" -#include +#include "common/code_utils.hpp" +#include "common/debug.hpp" #include "common/instance.hpp" #include "common/locator_getters.hpp" +#include "common/log.hpp" using namespace ot; otLogLevel otLoggingGetLevel(void) { -#if OPENTHREAD_CONFIG_LOG_LEVEL_DYNAMIC_ENABLE - return Instance::GetLogLevel(); -#else - return static_cast(OPENTHREAD_CONFIG_LOG_LEVEL); -#endif + return static_cast(Instance::GetLogLevel()); } #if OPENTHREAD_CONFIG_LOG_LEVEL_DYNAMIC_ENABLE @@ -53,15 +51,159 @@ otError otLoggingSetLevel(otLogLevel aLogLevel) { Error error = kErrorNone; - if (aLogLevel <= OT_LOG_LEVEL_DEBG && aLogLevel >= OT_LOG_LEVEL_NONE) - { - Instance::SetLogLevel(aLogLevel); - } - else - { - error = kErrorInvalidArgs; - } + VerifyOrExit(aLogLevel <= kLogLevelDebg && aLogLevel >= kLogLevelNone, error = kErrorInvalidArgs); + Instance::SetLogLevel(static_cast(aLogLevel)); +exit: return error; } #endif + +static const char kPlatformModuleName[] = "Platform"; + +void otLogCritPlat(const char *aFormat, ...) +{ +#if (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_CRIT) && OPENTHREAD_CONFIG_LOG_PLATFORM + va_list args; + + va_start(args, aFormat); + Logger::LogVarArgs(kPlatformModuleName, kLogLevelCrit, aFormat, args); + va_end(args); +#else + OT_UNUSED_VARIABLE(aFormat); + OT_UNUSED_VARIABLE(kPlatformModuleName); +#endif +} + +void otLogWarnPlat(const char *aFormat, ...) +{ +#if (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_WARN) && OPENTHREAD_CONFIG_LOG_PLATFORM + va_list args; + + va_start(args, aFormat); + Logger::LogVarArgs(kPlatformModuleName, kLogLevelWarn, aFormat, args); + va_end(args); +#else + OT_UNUSED_VARIABLE(aFormat); +#endif +} + +void otLogNotePlat(const char *aFormat, ...) +{ +#if (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_NOTE) && OPENTHREAD_CONFIG_LOG_PLATFORM + va_list args; + + va_start(args, aFormat); + Logger::LogVarArgs(kPlatformModuleName, kLogLevelNote, aFormat, args); + va_end(args); +#else + OT_UNUSED_VARIABLE(aFormat); +#endif +} + +void otLogInfoPlat(const char *aFormat, ...) +{ +#if (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO) && OPENTHREAD_CONFIG_LOG_PLATFORM + va_list args; + + va_start(args, aFormat); + Logger::LogVarArgs(kPlatformModuleName, kLogLevelInfo, aFormat, args); + va_end(args); +#else + OT_UNUSED_VARIABLE(aFormat); +#endif +} + +void otLogDebgPlat(const char *aFormat, ...) +{ +#if (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_DEBG) && OPENTHREAD_CONFIG_LOG_PLATFORM + va_list args; + + va_start(args, aFormat); + Logger::LogVarArgs(kPlatformModuleName, kLogLevelDebg, aFormat, args); + va_end(args); +#else + OT_UNUSED_VARIABLE(aFormat); +#endif +} + +void otDumpCritPlat(const char *aText, const void *aData, uint16_t aDataLength) +{ +#if (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_CRIT) && OPENTHREAD_CONFIG_LOG_PLATFORM && \ + OPENTHREAD_CONFIG_LOG_PKT_DUMP + Logger::DumpInModule(kPlatformModuleName, kLogLevelCrit, aText, aData, aDataLength); +#else + OT_UNUSED_VARIABLE(aText); + OT_UNUSED_VARIABLE(aData); + OT_UNUSED_VARIABLE(aDataLength); +#endif +} + +void otDumpWarnPlat(const char *aText, const void *aData, uint16_t aDataLength) +{ +#if (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_WARN) && OPENTHREAD_CONFIG_LOG_PLATFORM && \ + OPENTHREAD_CONFIG_LOG_PKT_DUMP + Logger::DumpInModule(kPlatformModuleName, kLogLevelWarn, aText, aData, aDataLength); +#else + OT_UNUSED_VARIABLE(aText); + OT_UNUSED_VARIABLE(aData); + OT_UNUSED_VARIABLE(aDataLength); +#endif +} + +void otDumpNotePlat(const char *aText, const void *aData, uint16_t aDataLength) +{ +#if (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_NOTE) && OPENTHREAD_CONFIG_LOG_PLATFORM && \ + OPENTHREAD_CONFIG_LOG_PKT_DUMP + Logger::DumpInModule(kPlatformModuleName, kLogLevelNote, aText, aData, aDataLength); +#else + OT_UNUSED_VARIABLE(aText); + OT_UNUSED_VARIABLE(aData); + OT_UNUSED_VARIABLE(aDataLength); +#endif +} + +void otDumpInfoPlat(const char *aText, const void *aData, uint16_t aDataLength) +{ +#if (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO) && OPENTHREAD_CONFIG_LOG_PLATFORM && \ + OPENTHREAD_CONFIG_LOG_PKT_DUMP + Logger::DumpInModule(kPlatformModuleName, kLogLevelInfo, aText, aData, aDataLength); +#else + OT_UNUSED_VARIABLE(aText); + OT_UNUSED_VARIABLE(aData); + OT_UNUSED_VARIABLE(aDataLength); +#endif +} + +void otDumpDebgPlat(const char *aText, const void *aData, uint16_t aDataLength) +{ +#if (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_DEBG) && OPENTHREAD_CONFIG_LOG_PLATFORM && \ + OPENTHREAD_CONFIG_LOG_PKT_DUMP + Logger::DumpInModule(kPlatformModuleName, kLogLevelDebg, aText, aData, aDataLength); +#else + OT_UNUSED_VARIABLE(aText); + OT_UNUSED_VARIABLE(aData); + OT_UNUSED_VARIABLE(aDataLength); +#endif +} + +void otLogCli(otLogLevel aLogLevel, const char *aFormat, ...) +{ +#if OPENTHREAD_CONFIG_LOG_CLI + static const char kCliModuleName[] = "Cli"; + + va_list args; + + OT_ASSERT(aLogLevel >= kLogLevelNone && aLogLevel <= kLogLevelDebg); + VerifyOrExit(aLogLevel >= kLogLevelNone && aLogLevel <= kLogLevelDebg); + + va_start(args, aFormat); + Logger::LogVarArgs(kCliModuleName, static_cast(aLogLevel), aFormat, args); + va_end(args); +exit: +#else + OT_UNUSED_VARIABLE(aLogLevel); + OT_UNUSED_VARIABLE(aFormat); +#endif + return; +} diff --git a/src/core/api/tasklet_api.cpp b/src/core/api/tasklet_api.cpp index 6f8a0dedc..e5213c816 100644 --- a/src/core/api/tasklet_api.cpp +++ b/src/core/api/tasklet_api.cpp @@ -38,7 +38,6 @@ #include "common/as_core_type.hpp" #include "common/code_utils.hpp" #include "common/locator_getters.hpp" -#include "common/logging.hpp" using namespace ot; diff --git a/src/core/backbone_router/backbone_tmf.cpp b/src/core/backbone_router/backbone_tmf.cpp index 676906f81..293793f04 100644 --- a/src/core/backbone_router/backbone_tmf.cpp +++ b/src/core/backbone_router/backbone_tmf.cpp @@ -36,11 +36,13 @@ #if OPENTHREAD_FTD && OPENTHREAD_CONFIG_BACKBONE_ROUTER_ENABLE #include "common/locator_getters.hpp" -#include "common/logging.hpp" +#include "common/log.hpp" namespace ot { namespace BackboneRouter { +RegisterLogModule("Bbr"); + Error BackboneTmfAgent::Start(void) { Error error = kErrorNone; @@ -96,11 +98,11 @@ void BackboneTmfAgent::LogError(const char *aText, const Ip6::Address &aAddress, if (aError == kErrorNone) { - otLogInfoBbr("%s %s: %s", aText, aAddress.ToString().AsCString(), ErrorToString(aError)); + LogInfo("%s %s: %s", aText, aAddress.ToString().AsCString(), ErrorToString(aError)); } else { - otLogWarnBbr("%s %s: %s", aText, aAddress.ToString().AsCString(), ErrorToString(aError)); + LogWarn("%s %s: %s", aText, aAddress.ToString().AsCString(), ErrorToString(aError)); } } diff --git a/src/core/backbone_router/bbr_leader.cpp b/src/core/backbone_router/bbr_leader.cpp index 41df0c184..6387b840f 100644 --- a/src/core/backbone_router/bbr_leader.cpp +++ b/src/core/backbone_router/bbr_leader.cpp @@ -37,11 +37,13 @@ #include "common/instance.hpp" #include "common/locator_getters.hpp" -#include "common/logging.hpp" +#include "common/log.hpp" namespace ot { namespace BackboneRouter { +RegisterLogModule("BbrLeader"); + Leader::Leader(Instance &aInstance) : InstanceLocator(aInstance) { @@ -81,24 +83,24 @@ exit: return error; } -#if (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO) && (OPENTHREAD_CONFIG_LOG_BBR == 1) +#if OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO void Leader::LogBackboneRouterPrimary(State aState, const BackboneRouterConfig &aConfig) const { OT_UNUSED_VARIABLE(aConfig); - otLogInfoBbr("PBBR state: %s", StateToString(aState)); + LogInfo("PBBR state: %s", StateToString(aState)); if (aState != kStateRemoved && aState != kStateNone) { - otLogInfoBbr("Rloc16: 0x%4X, seqno: %d, delay: %d, timeout %d", aConfig.mServer16, aConfig.mSequenceNumber, - aConfig.mReregistrationDelay, aConfig.mMlrTimeout); + LogInfo("Rloc16: 0x%4X, seqno: %d, delay: %d, timeout %d", aConfig.mServer16, aConfig.mSequenceNumber, + aConfig.mReregistrationDelay, aConfig.mMlrTimeout); } } void Leader::LogDomainPrefix(DomainPrefixState aState, const Ip6::Prefix &aPrefix) const { - otLogInfoBbr("Domain Prefix: %s, state: %s", aPrefix.ToString().AsCString(), DomainPrefixStateToString(aState)); + LogInfo("Domain Prefix: %s, state: %s", aPrefix.ToString().AsCString(), DomainPrefixStateToString(aState)); } const char *Leader::StateToString(State aState) @@ -141,7 +143,7 @@ const char *Leader::DomainPrefixStateToString(DomainPrefixState aState) return kPrefixStateStrings[aState]; } -#endif // (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO) && (OPENTHREAD_CONFIG_LOG_BBR == 1) +#endif // OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO void Leader::Update(void) { @@ -204,7 +206,7 @@ void Leader::UpdateBackboneRouterPrimary(void) if (config.mMlrTimeout != origMlrTimeout) { - otLogNoteBbr("Leader MLR Timeout is normalized from %u to %u", origMlrTimeout, config.mMlrTimeout); + LogNote("Leader MLR Timeout is normalized from %u to %u", origMlrTimeout, config.mMlrTimeout); } } diff --git a/src/core/backbone_router/bbr_leader.hpp b/src/core/backbone_router/bbr_leader.hpp index 823d619e5..096706dca 100644 --- a/src/core/backbone_router/bbr_leader.hpp +++ b/src/core/backbone_router/bbr_leader.hpp @@ -175,7 +175,7 @@ public: private: void UpdateBackboneRouterPrimary(void); void UpdateDomainPrefixConfig(void); -#if (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO) && (OPENTHREAD_CONFIG_LOG_BBR == 1) +#if OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO void LogBackboneRouterPrimary(State aState, const BackboneRouterConfig &aConfig) const; void LogDomainPrefix(DomainPrefixState aState, const Ip6::Prefix &aPrefix) const; static const char *StateToString(State aState); diff --git a/src/core/backbone_router/bbr_local.cpp b/src/core/backbone_router/bbr_local.cpp index 862860fef..3e3e2ce16 100644 --- a/src/core/backbone_router/bbr_local.cpp +++ b/src/core/backbone_router/bbr_local.cpp @@ -38,7 +38,7 @@ #include "common/code_utils.hpp" #include "common/instance.hpp" #include "common/locator_getters.hpp" -#include "common/logging.hpp" +#include "common/log.hpp" #include "common/random.hpp" #include "thread/mle_types.hpp" #include "thread/thread_netif.hpp" @@ -47,6 +47,8 @@ namespace ot { namespace BackboneRouter { +RegisterLogModule("BbrLocal"); + Local::Local(Instance &aInstance) : InstanceLocator(aInstance) , mState(OT_BACKBONE_ROUTER_STATE_DISABLED) @@ -458,17 +460,17 @@ void Local::AddDomainPrefixToNetworkData(void) LogDomainPrefix("Add", error); } -#if (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO) && (OPENTHREAD_CONFIG_LOG_BBR == 1) +#if OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO void Local::LogDomainPrefix(const char *aAction, Error aError) { - otLogInfoBbr("%s Domain Prefix: %s, %s", aAction, mDomainPrefixConfig.GetPrefix().ToString().AsCString(), - ErrorToString(aError)); + LogInfo("%s Domain Prefix: %s, %s", aAction, mDomainPrefixConfig.GetPrefix().ToString().AsCString(), + ErrorToString(aError)); } void Local::LogBackboneRouterService(const char *aAction, Error aError) { - otLogInfoBbr("%s BBR Service: seqno (%d), delay (%ds), timeout (%ds), %s", aAction, mSequenceNumber, - mReregistrationDelay, mMlrTimeout, ErrorToString(aError)); + LogInfo("%s BBR Service: seqno (%d), delay (%ds), timeout (%ds), %s", aAction, mSequenceNumber, + mReregistrationDelay, mMlrTimeout, ErrorToString(aError)); } #endif diff --git a/src/core/backbone_router/bbr_local.hpp b/src/core/backbone_router/bbr_local.hpp index 23c337a35..a453ba947 100644 --- a/src/core/backbone_router/bbr_local.hpp +++ b/src/core/backbone_router/bbr_local.hpp @@ -274,7 +274,7 @@ private: void AddDomainPrefixToNetworkData(void); void RemoveDomainPrefixFromNetworkData(void); void SequenceNumberIncrease(void); -#if (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO) && (OPENTHREAD_CONFIG_LOG_BBR == 1) +#if OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO void LogBackboneRouterService(const char *aAction, Error aError); void LogDomainPrefix(const char *aAction, Error aError); #else diff --git a/src/core/backbone_router/bbr_manager.cpp b/src/core/backbone_router/bbr_manager.cpp index 405d12e7f..d67793550 100644 --- a/src/core/backbone_router/bbr_manager.cpp +++ b/src/core/backbone_router/bbr_manager.cpp @@ -39,7 +39,7 @@ #include "common/code_utils.hpp" #include "common/instance.hpp" #include "common/locator_getters.hpp" -#include "common/logging.hpp" +#include "common/log.hpp" #include "common/random.hpp" #include "thread/mle_types.hpp" #include "thread/thread_netif.hpp" @@ -50,6 +50,8 @@ namespace ot { namespace BackboneRouter { +RegisterLogModule("BbrManager"); + Manager::Manager(Instance &aInstance) : InstanceLocator(aInstance) #if OPENTHREAD_CONFIG_BACKBONE_ROUTER_MULTICAST_ROUTING_ENABLE @@ -108,11 +110,11 @@ void Manager::HandleNotifierEvents(Events aEvents) if (error != kErrorNone) { - otLogWarnBbr("Stop Backbone TMF agent: %s", ErrorToString(error)); + LogWarn("Stop Backbone TMF agent: %s", ErrorToString(error)); } else { - otLogInfoBbr("Stop Backbone TMF agent: %s", ErrorToString(error)); + LogInfo("Stop Backbone TMF agent: %s", ErrorToString(error)); } } else @@ -226,7 +228,7 @@ void Manager::HandleMulticastListenerRegistration(const Coap::Message &aMessage, if (timeout != origTimeout) { - otLogNoteBbr("MLR.req: MLR timeout is normalized from %u to %u", origTimeout, timeout); + LogNote("MLR.req: MLR timeout is normalized from %u to %u", origTimeout, timeout); } } } @@ -328,7 +330,7 @@ void Manager::SendMulticastListenerRegistrationResponse(const Coap::Message & exit: FreeMessageOnError(message, error); - otLogInfoBbr("Sent MLR.rsp (status=%d): %s", aStatus, ErrorToString(error)); + LogInfo("Sent MLR.rsp (status=%d): %s", aStatus, ErrorToString(error)); } void Manager::SendBackboneMulticastListenerRegistration(const Ip6::Address *aAddresses, @@ -365,7 +367,7 @@ void Manager::SendBackboneMulticastListenerRegistration(const Ip6::Address *aAdd exit: FreeMessageOnError(message, error); - otLogInfoBbr("Sent BMLR.ntf: %s", ErrorToString(error)); + LogInfo("Sent BMLR.ntf: %s", ErrorToString(error)); } #endif // OPENTHREAD_CONFIG_BACKBONE_ROUTER_MULTICAST_ROUTING_ENABLE @@ -430,7 +432,7 @@ void Manager::HandleDuaRegistration(const Coap::Message &aMessage, const Ip6::Me } exit: - otLogInfoBbr("Received DUA.req on %s: %s", (isPrimary ? "PBBR" : "SBBR"), ErrorToString(error)); + LogInfo("Received DUA.req on %s: %s", (isPrimary ? "PBBR" : "SBBR"), ErrorToString(error)); if (error == kErrorNone) { @@ -467,8 +469,7 @@ void Manager::SendDuaRegistrationResponse(const Coap::Message & aMessage, exit: FreeMessageOnError(message, error); - otLogInfoBbr("Sent DUA.rsp for DUA %s, status %d %s", aTarget.ToString().AsCString(), aStatus, - ErrorToString(error)); + LogInfo("Sent DUA.rsp for DUA %s, status %d %s", aTarget.ToString().AsCString(), aStatus, ErrorToString(error)); } #endif // OPENTHREAD_CONFIG_BACKBONE_ROUTER_DUA_NDPROXYING_ENABLE @@ -555,8 +556,7 @@ Error Manager::SendBackboneQuery(const Ip6::Address &aDua, uint16_t aRloc16) error = mBackboneTmfAgent.SendMessage(*message, messageInfo); exit: - otLogInfoBbr("SendBackboneQuery for %s (rloc16=%04x): %s", aDua.ToString().AsCString(), aRloc16, - ErrorToString(error)); + LogInfo("SendBackboneQuery for %s (rloc16=%04x): %s", aDua.ToString().AsCString(), aRloc16, ErrorToString(error)); FreeMessageOnError(message, error); return error; } @@ -583,8 +583,8 @@ void Manager::HandleBackboneQuery(const Coap::Message &aMessage, const Ip6::Mess error = Tlv::Find(aMessage, rloc16); VerifyOrExit(error == kErrorNone || error == kErrorNotFound); - otLogInfoBbr("Received BB.qry from %s for %s (rloc16=%04x)", aMessageInfo.GetPeerAddr().ToString().AsCString(), - dua.ToString().AsCString(), rloc16); + LogInfo("Received BB.qry from %s for %s (rloc16=%04x)", aMessageInfo.GetPeerAddr().ToString().AsCString(), + dua.ToString().AsCString(), rloc16); ndProxy = mNdProxyTable.ResolveDua(dua); VerifyOrExit(ndProxy != nullptr && !ndProxy->GetDadFlag(), error = kErrorNotFound); @@ -592,7 +592,7 @@ void Manager::HandleBackboneQuery(const Coap::Message &aMessage, const Ip6::Mess error = SendBackboneAnswer(aMessageInfo, dua, rloc16, *ndProxy); exit: - otLogInfoBbr("HandleBackboneQuery: %s", ErrorToString(error)); + LogInfo("HandleBackboneQuery: %s", ErrorToString(error)); } void Manager::HandleBackboneAnswer(void *aContext, otMessage *aMessage, const otMessageInfo *aMessageInfo) @@ -643,7 +643,7 @@ void Manager::HandleBackboneAnswer(const Coap::Message &aMessage, const Ip6::Mes SuccessOrExit(error = mBackboneTmfAgent.SendEmptyAck(aMessage, aMessageInfo)); exit: - otLogInfoBbr("HandleBackboneAnswer: %s", ErrorToString(error)); + LogInfo("HandleBackboneAnswer: %s", ErrorToString(error)); } Error Manager::SendProactiveBackboneNotification(const Ip6::Address & aDua, @@ -706,8 +706,8 @@ Error Manager::SendBackboneAnswer(const Ip6::Address & aDstAddr, error = mBackboneTmfAgent.SendMessage(*message, messageInfo); exit: - otLogInfoBbr("Send %s for %s (rloc16=%04x): %s", proactive ? "PRO_BB.ntf" : "BB.ans", aDua.ToString().AsCString(), - aSrcRloc16, ErrorToString(error)); + LogInfo("Send %s for %s (rloc16=%04x): %s", proactive ? "PRO_BB.ntf" : "BB.ans", aDua.ToString().AsCString(), + aSrcRloc16, ErrorToString(error)); FreeMessageOnError(message, error); return error; @@ -736,8 +736,8 @@ void Manager::HandleDadBackboneAnswer(const Ip6::Address &aDua, const Ip6::Inter ot::BackboneRouter::NdProxyTable::NotifyDadComplete(*ndProxy, duplicate); exit: - otLogInfoBbr("HandleDadBackboneAnswer: %s, target=%s, mliid=%s, duplicate=%s", ErrorToString(error), - aDua.ToString().AsCString(), aMeshLocalIid.ToString().AsCString(), duplicate ? "Y" : "N"); + LogInfo("HandleDadBackboneAnswer: %s, target=%s, mliid=%s, duplicate=%s", ErrorToString(error), + aDua.ToString().AsCString(), aMeshLocalIid.ToString().AsCString(), duplicate ? "Y" : "N"); } void Manager::HandleExtendedBackboneAnswer(const Ip6::Address & aDua, @@ -750,9 +750,8 @@ void Manager::HandleExtendedBackboneAnswer(const Ip6::Address & aDua, dest.SetToRoutingLocator(Get().GetMeshLocalPrefix(), aSrcRloc16); Get().SendAddressQueryResponse(aDua, aMeshLocalIid, &aTimeSinceLastTransaction, dest); - otLogInfoBbr("HandleExtendedBackboneAnswer: target=%s, mliid=%s, LTT=%lds, rloc16=%04x", - aDua.ToString().AsCString(), aMeshLocalIid.ToString().AsCString(), aTimeSinceLastTransaction, - aSrcRloc16); + LogInfo("HandleExtendedBackboneAnswer: target=%s, mliid=%s, LTT=%lds, rloc16=%04x", aDua.ToString().AsCString(), + aMeshLocalIid.ToString().AsCString(), aTimeSinceLastTransaction, aSrcRloc16); } void Manager::HandleProactiveBackboneNotification(const Ip6::Address & aDua, @@ -788,8 +787,8 @@ void Manager::HandleProactiveBackboneNotification(const Ip6::Address & } exit: - otLogInfoBbr("HandleProactiveBackboneNotification: %s, target=%s, mliid=%s, LTT=%lds", ErrorToString(error), - aDua.ToString().AsCString(), aMeshLocalIid.ToString().AsCString(), aTimeSinceLastTransaction); + LogInfo("HandleProactiveBackboneNotification: %s, target=%s, mliid=%s, LTT=%lds", ErrorToString(error), + aDua.ToString().AsCString(), aMeshLocalIid.ToString().AsCString(), aTimeSinceLastTransaction); } #endif // OPENTHREAD_CONFIG_BACKBONE_ROUTER_DUA_NDPROXYING_ENABLE @@ -799,11 +798,11 @@ void Manager::LogError(const char *aText, Error aError) const if (aError == kErrorNone) { - otLogInfoBbr("%s: %s", aText, ErrorToString(aError)); + LogInfo("%s: %s", aText, ErrorToString(aError)); } else { - otLogWarnBbr("%s: %s", aText, ErrorToString(aError)); + LogWarn("%s: %s", aText, ErrorToString(aError)); } } diff --git a/src/core/backbone_router/multicast_listeners_table.cpp b/src/core/backbone_router/multicast_listeners_table.cpp index fe15d47a3..35a497263 100644 --- a/src/core/backbone_router/multicast_listeners_table.cpp +++ b/src/core/backbone_router/multicast_listeners_table.cpp @@ -39,7 +39,7 @@ #include "common/code_utils.hpp" #include "common/instance.hpp" #include "common/locator_getters.hpp" -#include "common/logging.hpp" +#include "common/log.hpp" #include "common/random.hpp" #include "thread/mle_types.hpp" #include "thread/thread_netif.hpp" @@ -49,6 +49,8 @@ namespace ot { namespace BackboneRouter { +RegisterLogModule("BbrMlt"); + Error MulticastListenersTable::Add(const Ip6::Address &aAddress, Time aExpireTime) { Error error = kErrorNone; @@ -155,8 +157,8 @@ void MulticastListenersTable::LogMulticastListenersTable(const char * aAc OT_UNUSED_VARIABLE(aExpireTime); OT_UNUSED_VARIABLE(aError); - otLogDebgBbr("MulticastListenersTable: %s %s expire %u: %s", aAction, aAddress.ToString().AsCString(), - aExpireTime.GetValue(), ErrorToString(aError)); + LogDebg("%s %s expire %u: %s", aAction, aAddress.ToString().AsCString(), aExpireTime.GetValue(), + ErrorToString(aError)); } void MulticastListenersTable::FixHeap(uint16_t aIndex) diff --git a/src/core/backbone_router/ndproxy_table.cpp b/src/core/backbone_router/ndproxy_table.cpp index b1e97be8d..519bc8355 100644 --- a/src/core/backbone_router/ndproxy_table.cpp +++ b/src/core/backbone_router/ndproxy_table.cpp @@ -37,12 +37,14 @@ #include "common/array.hpp" #include "common/locator_getters.hpp" -#include "common/logging.hpp" +#include "common/log.hpp" namespace ot { namespace BackboneRouter { +RegisterLogModule("BbrNdProxy"); + void NdProxyTable::NdProxy::Init(const Ip6::InterfaceIdentifier &aAddressIid, const Ip6::InterfaceIdentifier &aMeshLocalIid, uint16_t aRloc16, @@ -147,7 +149,7 @@ void NdProxyTable::Clear(void) mCallback(mCallbackContext, OT_BACKBONE_ROUTER_NDPROXY_CLEARED, nullptr); } - otLogNoteBbr("NdProxyTable::Clear!"); + LogNote("NdProxyTable::Clear!"); } Error NdProxyTable::Register(const Ip6::InterfaceIdentifier &aAddressIid, @@ -186,8 +188,8 @@ Error NdProxyTable::Register(const Ip6::InterfaceIdentifier &aAddressIid, mIsAnyDadInProcess = true; exit: - otLogInfoBbr("NdProxyTable::Register %s MLIID %s RLOC16 %04x LTT %u => %s", aAddressIid.ToString().AsCString(), - aMeshLocalIid.ToString().AsCString(), aRloc16, timeSinceLastTransaction, ErrorToString(error)); + LogInfo("NdProxyTable::Register %s MLIID %s RLOC16 %04x LTT %u => %s", aAddressIid.ToString().AsCString(), + aMeshLocalIid.ToString().AsCString(), aRloc16, timeSinceLastTransaction, ErrorToString(error)); return error; } @@ -204,8 +206,8 @@ NdProxyTable::NdProxy *NdProxyTable::FindByAddressIid(const Ip6::InterfaceIdenti } exit: - otLogDebgBbr("NdProxyTable::FindByAddressIid(%s) => %s", aAddressIid.ToString().AsCString(), - found ? found->mMeshLocalIid.ToString().AsCString() : "NOT_FOUND"); + LogDebg("NdProxyTable::FindByAddressIid(%s) => %s", aAddressIid.ToString().AsCString(), + found ? found->mMeshLocalIid.ToString().AsCString() : "NOT_FOUND"); return found; } @@ -222,8 +224,8 @@ NdProxyTable::NdProxy *NdProxyTable::FindByMeshLocalIid(const Ip6::InterfaceIden } exit: - otLogDebgBbr("NdProxyTable::FindByMeshLocalIid(%s) => %s", aMeshLocalIid.ToString().AsCString(), - found ? found->mAddressIid.ToString().AsCString() : "NOT_FOUND"); + LogDebg("NdProxyTable::FindByMeshLocalIid(%s) => %s", aMeshLocalIid.ToString().AsCString(), + found ? found->mAddressIid.ToString().AsCString() : "NOT_FOUND"); return found; } @@ -237,7 +239,7 @@ NdProxyTable::NdProxy *NdProxyTable::FindInvalid(void) } exit: - otLogDebgBbr("NdProxyTable::FindInvalid() => %s", found ? "OK" : "NOT_FOUND"); + LogDebg("NdProxyTable::FindInvalid() => %s", found ? "OK" : "NOT_FOUND"); return found; } diff --git a/src/core/border_router/routing_manager.cpp b/src/core/border_router/routing_manager.cpp index f861681e9..bab03a7f4 100644 --- a/src/core/border_router/routing_manager.cpp +++ b/src/core/border_router/routing_manager.cpp @@ -44,7 +44,7 @@ #include "common/debug.hpp" #include "common/instance.hpp" #include "common/locator_getters.hpp" -#include "common/logging.hpp" +#include "common/log.hpp" #include "common/random.hpp" #include "common/settings.hpp" #include "net/ip6.hpp" @@ -56,6 +56,8 @@ namespace ot { namespace BorderRouter { +RegisterLogModule("BorderRouter"); + RoutingManager::RoutingManager(Instance &aInstance) : InstanceLocator(aInstance) , mIsRunning(false) @@ -168,13 +170,13 @@ Error RoutingManager::LoadOrGenerateRandomOmrPrefix(void) { Ip6::NetworkPrefix randomOmrPrefix; - otLogNoteBr("No valid OMR prefix found in settings, generating new one"); + LogNote("No valid OMR prefix found in settings, generating new one"); // TODO: generate OMR prefix from the /48 BR ULA prefix error = randomOmrPrefix.GenerateRandomUla(); if (error != kErrorNone) { - otLogCritBr("Failed to generate random OMR prefix"); + LogCrit("Failed to generate random OMR prefix"); ExitNow(); } @@ -195,12 +197,12 @@ Error RoutingManager::LoadOrGenerateRandomOnLinkPrefix(void) { Ip6::NetworkPrefix randomOnLinkPrefix; - otLogNoteBr("No valid on-link prefix found in settings, generating new one"); + LogNote("No valid on-link prefix found in settings, generating new one"); error = randomOnLinkPrefix.GenerateRandomUla(); if (error != kErrorNone) { - otLogCritBr("Failed to generate random on-link prefix"); + LogCrit("Failed to generate random on-link prefix"); ExitNow(); } @@ -226,13 +228,13 @@ Error RoutingManager::LoadOrGenerateRandomNat64Prefix(void) Ip6::NetworkPrefix randomNat64Prefix; constexpr uint8_t nat64PrefixLength = 96; - otLogNoteBr("No valid NAT64 prefix found in settings, generating new one"); + LogNote("No valid NAT64 prefix found in settings, generating new one"); // TODO: generate NAT64 prefix from the /48 BR ULA prefix error = randomNat64Prefix.GenerateRandomUla(); if (error != kErrorNone) { - otLogCritBr("Failed to generate random NAT64 prefix"); + LogCrit("Failed to generate random NAT64 prefix"); ExitNow(); } @@ -264,7 +266,7 @@ void RoutingManager::Start(void) { if (!mIsRunning) { - otLogInfoBr("Border Routing manager started"); + LogInfo("Border Routing manager started"); mIsRunning = true; StartRouterSolicitationDelay(); @@ -315,7 +317,7 @@ void RoutingManager::Stop(void) mRoutingPolicyTimer.Stop(); - otLogInfoBr("Border Routing manager stopped"); + LogInfo("Border Routing manager stopped"); mIsRunning = false; @@ -352,7 +354,7 @@ void RoutingManager::RecvIcmp6Message(uint32_t aInfraIfIndex, exit: if (error != kErrorNone) { - otLogDebgBr("Dropped ICMPv6 message: %s", ErrorToString(error)); + LogDebg("Dropped ICMPv6 message: %s", ErrorToString(error)); } } @@ -364,8 +366,8 @@ Error RoutingManager::HandleInfraIfStateChanged(uint32_t aInfraIfIndex, bool aIs VerifyOrExit(aInfraIfIndex == mInfraIfIndex, error = kErrorInvalidArgs); VerifyOrExit(aIsRunning != mInfraIfIsRunning); - otLogInfoBr("Infra interface (%u) state changed: %sRUNNING -> %sRUNNING", aInfraIfIndex, - (mInfraIfIsRunning ? "" : "NOT "), (aIsRunning ? "" : "NOT ")); + LogInfo("Infra interface (%u) state changed: %sRUNNING -> %sRUNNING", aInfraIfIndex, + (mInfraIfIsRunning ? "" : "NOT "), (aIsRunning ? "" : "NOT ")); mInfraIfIsRunning = aIsRunning; EvaluateState(); @@ -420,7 +422,7 @@ void RoutingManager::EvaluateOmrPrefix(OmrPrefixArray &aNewOmrPrefixes) if (aNewOmrPrefixes.PushBack(prefix) != kErrorNone) { - otLogWarnBr("EvaluateOmrPrefix: Too many OMR prefixes, ignoring prefix %s", prefix.ToString().AsCString()); + LogWarn("EvaluateOmrPrefix: Too many OMR prefixes, ignoring prefix %s", prefix.ToString().AsCString()); continue; } @@ -439,7 +441,7 @@ void RoutingManager::EvaluateOmrPrefix(OmrPrefixArray &aNewOmrPrefixes) if (aNewOmrPrefixes.IsEmpty()) { - otLogInfoBr("EvaluateOmrPrefix: No valid OMR prefixes found in Thread network"); + LogInfo("EvaluateOmrPrefix: No valid OMR prefixes found in Thread network"); if (PublishLocalOmrPrefix() == kErrorNone) { @@ -451,8 +453,8 @@ void RoutingManager::EvaluateOmrPrefix(OmrPrefixArray &aNewOmrPrefixes) } else if (publishedLocalOmrPrefix != nullptr && smallestOmrPrefix != publishedLocalOmrPrefix) { - otLogInfoBr("EvaluateOmrPrefix: There is already a smaller OMR prefix %s in the Thread network", - smallestOmrPrefix->ToString().AsCString()); + LogInfo("EvaluateOmrPrefix: There is already a smaller OMR prefix %s in the Thread network", + smallestOmrPrefix->ToString().AsCString()); UnpublishLocalOmrPrefix(); @@ -483,13 +485,13 @@ Error RoutingManager::PublishLocalOmrPrefix(void) error = Get().AddOnMeshPrefix(omrPrefixConfig); if (error != kErrorNone) { - otLogWarnBr("Failed to publish local OMR prefix %s in Thread network: %s", - mLocalOmrPrefix.ToString().AsCString(), ErrorToString(error)); + LogWarn("Failed to publish local OMR prefix %s in Thread network: %s", mLocalOmrPrefix.ToString().AsCString(), + ErrorToString(error)); } else { Get().HandleServerDataUpdated(); - otLogInfoBr("Publishing local OMR prefix %s in Thread network", mLocalOmrPrefix.ToString().AsCString()); + LogInfo("Publishing local OMR prefix %s in Thread network", mLocalOmrPrefix.ToString().AsCString()); } return error; @@ -504,13 +506,13 @@ void RoutingManager::UnpublishLocalOmrPrefix(void) SuccessOrExit(error = Get().RemoveOnMeshPrefix(mLocalOmrPrefix)); Get().HandleServerDataUpdated(); - otLogInfoBr("Unpublishing local OMR prefix %s from Thread network", mLocalOmrPrefix.ToString().AsCString()); + LogInfo("Unpublishing local OMR prefix %s from Thread network", mLocalOmrPrefix.ToString().AsCString()); exit: if (error != kErrorNone) { - otLogWarnBr("Failed to unpublish local OMR prefix %s from Thread network: %s", - mLocalOmrPrefix.ToString().AsCString(), ErrorToString(error)); + LogWarn("Failed to unpublish local OMR prefix %s from Thread network: %s", + mLocalOmrPrefix.ToString().AsCString(), ErrorToString(error)); } } @@ -530,12 +532,12 @@ Error RoutingManager::AddExternalRoute(const Ip6::Prefix &aPrefix, RoutePreferen error = Get().AddHasRoutePrefix(routeConfig); if (error != kErrorNone) { - otLogWarnBr("Failed to add external route %s: %s", aPrefix.ToString().AsCString(), ErrorToString(error)); + LogWarn("Failed to add external route %s: %s", aPrefix.ToString().AsCString(), ErrorToString(error)); } else { Get().HandleServerDataUpdated(); - otLogInfoBr("Adding external route %s", aPrefix.ToString().AsCString()); + LogInfo("Adding external route %s", aPrefix.ToString().AsCString()); } return error; @@ -550,12 +552,12 @@ void RoutingManager::RemoveExternalRoute(const Ip6::Prefix &aPrefix) SuccessOrExit(error = Get().RemoveHasRoutePrefix(aPrefix)); Get().HandleServerDataUpdated(); - otLogInfoBr("Removing external route %s", aPrefix.ToString().AsCString()); + LogInfo("Removing external route %s", aPrefix.ToString().AsCString()); exit: if (error != kErrorNone) { - otLogWarnBr("Failed to remove external route %s: %s", aPrefix.ToString().AsCString(), ErrorToString(error)); + LogWarn("Failed to remove external route %s: %s", aPrefix.ToString().AsCString(), ErrorToString(error)); } } @@ -604,8 +606,8 @@ const Ip6::Prefix *RoutingManager::EvaluateOnLinkPrefix(void) } else { - otLogInfoBr("EvaluateOnLinkPrefix: There is already smaller on-link prefix %s on interface %u", - smallestOnLinkPrefix->ToString().AsCString(), mInfraIfIndex); + LogInfo("EvaluateOnLinkPrefix: There is already smaller on-link prefix %s on interface %u", + smallestOnLinkPrefix->ToString().AsCString(), mInfraIfIndex); DeprecateOnLinkPrefix(); } } @@ -621,7 +623,7 @@ void RoutingManager::HandleOnLinkPrefixDeprecateTimer(Timer &aTimer) void RoutingManager::HandleOnLinkPrefixDeprecateTimer(void) { - otLogInfoBr("Local on-link prefix %s expired", mLocalOnLinkPrefix.ToString().AsCString()); + LogInfo("Local on-link prefix %s expired", mLocalOnLinkPrefix.ToString().AsCString()); RemoveExternalRoute(mLocalOnLinkPrefix); } @@ -629,7 +631,7 @@ void RoutingManager::DeprecateOnLinkPrefix(void) { OT_ASSERT(mIsAdvertisingLocalOnLinkPrefix); - otLogInfoBr("Deprecate local on-link prefix %s", mLocalOnLinkPrefix.ToString().AsCString()); + LogInfo("Deprecate local on-link prefix %s", mLocalOnLinkPrefix.ToString().AsCString()); mOnLinkPrefixDeprecateTimer.StartAt(mTimeAdvertisedOnLinkPrefix, TimeMilli::SecToMsec(kDefaultOnLinkPrefixLifetime)); } @@ -643,7 +645,7 @@ void RoutingManager::EvaluateNat64Prefix(void) NetworkData::ExternalRouteConfig config; Ip6::Prefix smallestNat64Prefix; - otLogInfoBr("Evaluating NAT64 prefix"); + LogInfo("Evaluating NAT64 prefix"); smallestNat64Prefix.Clear(); while (Get().GetNextExternalRoute(iterator, config) == kErrorNone) @@ -661,8 +663,8 @@ void RoutingManager::EvaluateNat64Prefix(void) if (smallestNat64Prefix.GetLength() == 0 || smallestNat64Prefix == mLocalNat64Prefix) { - otLogInfoBr("No NAT64 prefix in Network Data is smaller than the local NAT64 prefix %s", - mLocalNat64Prefix.ToString().AsCString()); + LogInfo("No NAT64 prefix in Network Data is smaller than the local NAT64 prefix %s", + mLocalNat64Prefix.ToString().AsCString()); // Advertise local NAT64 prefix. if (!mIsAdvertisingLocalNat64Prefix && @@ -675,8 +677,8 @@ void RoutingManager::EvaluateNat64Prefix(void) { // Withdraw local NAT64 prefix if it's not the smallest one in Network Data. // TODO: remove the prefix with lower preference after discovering upstream NAT64 prefix is supported - otLogNoteBr("Withdrawing local NAT64 prefix since a smaller one %s exists.", - smallestNat64Prefix.ToString().AsCString()); + LogNote("Withdrawing local NAT64 prefix since a smaller one %s exists.", + smallestNat64Prefix.ToString().AsCString()); RemoveExternalRoute(mLocalNat64Prefix); mIsAdvertisingLocalNat64Prefix = false; @@ -695,7 +697,7 @@ void RoutingManager::EvaluateRoutingPolicy(void) const Ip6::Prefix *newOnLinkPrefix = nullptr; OmrPrefixArray newOmrPrefixes; - otLogInfoBr("Evaluating routing policy"); + LogInfo("Evaluating routing policy"); // 0. Evaluate on-link & OMR prefixes. newOnLinkPrefix = EvaluateOnLinkPrefix(); @@ -713,7 +715,7 @@ void RoutingManager::EvaluateRoutingPolicy(void) // our local OMR prefix to the Thread network. We schedule the Router Advertisement // timer to re-evaluate our routing policy in the future. - otLogWarnBr("No OMR prefix advertised! Start Router Advertisement timer for future evaluation"); + LogWarn("No OMR prefix advertised! Start Router Advertisement timer for future evaluation"); } // 2. Schedule Router Advertisement timer with random interval. @@ -727,7 +729,7 @@ void RoutingManager::EvaluateRoutingPolicy(void) nextSendDelay = kMaxInitRtrAdvInterval; } - otLogInfoBr("Router advertisement scheduled in %u seconds", nextSendDelay); + LogInfo("Router advertisement scheduled in %u seconds", nextSendDelay); StartRoutingPolicyEvaluationDelay(Time::SecToMsec(nextSendDelay)); } @@ -745,7 +747,7 @@ void RoutingManager::StartRoutingPolicyEvaluationJitter(uint32_t aJitterMilli) void RoutingManager::StartRoutingPolicyEvaluationDelay(uint32_t aDelayMilli) { - otLogInfoBr("Start evaluating routing policy, scheduled in %u milliseconds", aDelayMilli); + LogInfo("Start evaluating routing policy, scheduled in %u milliseconds", aDelayMilli); mRoutingPolicyTimer.FireAtIfEarlier(TimerMilli::GetNow() + aDelayMilli); } @@ -766,7 +768,7 @@ void RoutingManager::StartRouterSolicitationDelay(void) static_assert(kMaxRtrSolicitationDelay > 0, "invalid maximum Router Solicitation delay"); randomDelay = Random::NonCrypto::GetUint32InRange(0, Time::SecToMsec(kMaxRtrSolicitationDelay)); - otLogInfoBr("Start Router Solicitation, scheduled in %u milliseconds", randomDelay); + LogInfo("Start Router Solicitation, scheduled in %u milliseconds", randomDelay); mTimeRouterSolicitStart = TimerMilli::GetNow(); mRouterSolicitTimer.Start(randomDelay); @@ -823,12 +825,12 @@ void RoutingManager::SendRouterAdvertisement(const OmrPrefixArray &aNewOmrPrefix if (!mIsAdvertisingLocalOnLinkPrefix) { - otLogInfoBr("Start advertising new on-link prefix %s on interface %u", - aNewOnLinkPrefix->ToString().AsCString(), mInfraIfIndex); + LogInfo("Start advertising new on-link prefix %s on interface %u", aNewOnLinkPrefix->ToString().AsCString(), + mInfraIfIndex); } - otLogInfoBr("Send on-link prefix %s in PIO (preferred lifetime = %u seconds, valid lifetime = %u seconds)", - aNewOnLinkPrefix->ToString().AsCString(), pio.GetPreferredLifetime(), pio.GetValidLifetime()); + LogInfo("Send on-link prefix %s in PIO (preferred lifetime = %u seconds, valid lifetime = %u seconds)", + aNewOnLinkPrefix->ToString().AsCString(), pio.GetPreferredLifetime(), pio.GetValidLifetime()); mTimeAdvertisedOnLinkPrefix = TimerMilli::GetNow(); } @@ -848,8 +850,8 @@ void RoutingManager::SendRouterAdvertisement(const OmrPrefixArray &aNewOmrPrefix memcpy(buffer + bufferLength, &pio, pio.GetSize()); bufferLength += pio.GetSize(); - otLogInfoBr("Send on-link prefix %s in PIO (preferred lifetime = %u seconds, valid lifetime = %u seconds)", - mLocalOnLinkPrefix.ToString().AsCString(), pio.GetPreferredLifetime(), pio.GetValidLifetime()); + LogInfo("Send on-link prefix %s in PIO (preferred lifetime = %u seconds, valid lifetime = %u seconds)", + mLocalOnLinkPrefix.ToString().AsCString(), pio.GetPreferredLifetime(), pio.GetValidLifetime()); } // Invalidate the advertised OMR prefixes if they are no longer in the new OMR prefix array. @@ -868,8 +870,8 @@ void RoutingManager::SendRouterAdvertisement(const OmrPrefixArray &aNewOmrPrefix memcpy(buffer + bufferLength, &rio, rio.GetSize()); bufferLength += rio.GetSize(); - otLogInfoBr("Stop advertising OMR prefix %s on interface %u", advertisedOmrPrefix.ToString().AsCString(), - mInfraIfIndex); + LogInfo("Stop advertising OMR prefix %s on interface %u", advertisedOmrPrefix.ToString().AsCString(), + mInfraIfIndex); } } @@ -884,8 +886,8 @@ void RoutingManager::SendRouterAdvertisement(const OmrPrefixArray &aNewOmrPrefix memcpy(buffer + bufferLength, &rio, rio.GetSize()); bufferLength += rio.GetSize(); - otLogInfoBr("Send OMR prefix %s in RIO (valid lifetime = %u seconds)", newOmrPrefix.ToString().AsCString(), - kDefaultOmrPrefixLifetime); + LogInfo("Send OMR prefix %s in RIO (valid lifetime = %u seconds)", newOmrPrefix.ToString().AsCString(), + kDefaultOmrPrefixLifetime); } // Send the message only when there are options. @@ -901,12 +903,12 @@ void RoutingManager::SendRouterAdvertisement(const OmrPrefixArray &aNewOmrPrefix if (error == kErrorNone) { - otLogInfoBr("Sent Router Advertisement on interface %u", mInfraIfIndex); - otDumpDebgBr("[BR-CERT] direction=send | type=RA |", buffer, bufferLength); + LogInfo("Sent Router Advertisement on interface %u", mInfraIfIndex); + DumpDebg("[BR-CERT] direction=send | type=RA |", buffer, bufferLength); } else { - otLogWarnBr("Failed to send Router Advertisement on interface %u: %s", mInfraIfIndex, ErrorToString(error)); + LogWarn("Failed to send Router Advertisement on interface %u: %s", mInfraIfIndex, ErrorToString(error)); } } } @@ -941,7 +943,7 @@ void RoutingManager::HandleVicariousRouterSolicitTimer(Timer &aTimer) void RoutingManager::HandleVicariousRouterSolicitTimer(void) { - otLogInfoBr("Vicarious router solicitation time out"); + LogInfo("Vicarious router solicitation time out"); for (const ExternalPrefix &prefix : mDiscoveredPrefixes) { @@ -961,7 +963,7 @@ void RoutingManager::HandleRouterSolicitTimer(Timer &aTimer) void RoutingManager::HandleRouterSolicitTimer(void) { - otLogInfoBr("Router solicitation times out"); + LogInfo("Router solicitation times out"); if (mRouterSolicitCount < kMaxRtrSolicitations) { @@ -972,14 +974,14 @@ void RoutingManager::HandleRouterSolicitTimer(void) if (error == kErrorNone) { - otLogDebgBr("Successfully sent %uth Router Solicitation", mRouterSolicitCount); + LogDebg("Successfully sent %uth Router Solicitation", mRouterSolicitCount); ++mRouterSolicitCount; nextSolicitationDelay = (mRouterSolicitCount == kMaxRtrSolicitations) ? kMaxRtrSolicitationDelay : kRtrSolicitationInterval; } else { - otLogCritBr("Failed to send %uth Router Solicitation: %s", mRouterSolicitCount, ErrorToString(error)); + LogCrit("Failed to send %uth Router Solicitation: %s", mRouterSolicitCount, ErrorToString(error)); // It's unexpected that RS will fail and we will retry sending RS messages in 60 seconds. // Notice that `mRouterSolicitCount` is not incremented for failed RS and thus we will @@ -989,7 +991,7 @@ void RoutingManager::HandleRouterSolicitTimer(void) mRouterSolicitCount = 0; } - otLogDebgBr("Router solicitation timer scheduled in %u seconds", nextSolicitationDelay); + LogDebg("Router solicitation timer scheduled in %u seconds", nextSolicitationDelay); mRouterSolicitTimer.Start(Time::SecToMsec(nextSolicitationDelay)); } else @@ -1033,7 +1035,7 @@ void RoutingManager::HandleDiscoveredPrefixStaleTimer(Timer &aTimer) void RoutingManager::HandleDiscoveredPrefixStaleTimer(void) { - otLogInfoBr("Stale On-Link or OMR Prefixes or RA messages are detected"); + LogInfo("Stale On-Link or OMR Prefixes or RA messages are detected"); StartRouterSolicitationDelay(); } @@ -1060,8 +1062,7 @@ void RoutingManager::HandleRouterSolicit(const Ip6::Address &aSrcAddress, OT_UNUSED_VARIABLE(aBuffer); OT_UNUSED_VARIABLE(aBufferLength); - otLogInfoBr("Received Router Solicitation from %s on interface %u", aSrcAddress.ToString().AsCString(), - mInfraIfIndex); + LogInfo("Received Router Solicitation from %s on interface %u", aSrcAddress.ToString().AsCString(), mInfraIfIndex); #if OPENTHREAD_CONFIG_BORDER_ROUTING_VICARIOUS_RS_ENABLE if (!mVicariousRouterSolicitTimer.IsRunning()) @@ -1111,9 +1112,8 @@ void RoutingManager::HandleRouterAdvertisement(const Ip6::Address &aSrcAddress, VerifyOrExit(aBufferLength >= sizeof(RouterAdvMessage)); - otLogInfoBr("Received Router Advertisement from %s on interface %u", aSrcAddress.ToString().AsCString(), - mInfraIfIndex); - otDumpDebgBr("[BR-CERT] direction=recv | type=RA |", aBuffer, aBufferLength); + LogInfo("Received Router Advertisement from %s on interface %u", aSrcAddress.ToString().AsCString(), mInfraIfIndex); + DumpDebg("[BR-CERT] direction=recv | type=RA |", aBuffer, aBufferLength); routerAdvMessage = reinterpret_cast(aBuffer); optionsBegin = aBuffer + sizeof(RouterAdvMessage); @@ -1179,14 +1179,14 @@ bool RoutingManager::UpdateDiscoveredOnLinkPrefix(const RouterAdv::PrefixInfoOpt if (!IsValidOnLinkPrefix(aPio)) { - otLogInfoBr("Ignore invalid on-link prefix in PIO: %s", prefix.ToString().AsCString()); + LogInfo("Ignore invalid on-link prefix in PIO: %s", prefix.ToString().AsCString()); ExitNow(); } VerifyOrExit(!mIsAdvertisingLocalOnLinkPrefix || prefix != mLocalOnLinkPrefix); - otLogInfoBr("Discovered on-link prefix (%s, %u seconds) from interface %u", prefix.ToString().AsCString(), - aPio.GetValidLifetime(), mInfraIfIndex); + LogInfo("Discovered on-link prefix (%s, %u seconds) from interface %u", prefix.ToString().AsCString(), + aPio.GetValidLifetime(), mInfraIfIndex); onLinkPrefix.mIsOnLinkPrefix = true; onLinkPrefix.mPrefix = prefix; @@ -1218,7 +1218,7 @@ bool RoutingManager::UpdateDiscoveredOnLinkPrefix(const RouterAdv::PrefixInfoOpt } else { - otLogWarnBr("Discovered too many prefixes, ignore new on-link prefix %s", prefix.ToString().AsCString()); + LogWarn("Discovered too many prefixes, ignore new on-link prefix %s", prefix.ToString().AsCString()); ExitNow(); } } @@ -1271,7 +1271,7 @@ void RoutingManager::UpdateDiscoveredOmrPrefix(const RouterAdv::RouteInfoOption if (!IsValidOmrPrefix(prefix)) { - otLogInfoBr("Ignore invalid OMR prefix in RIO: %s", prefix.ToString().AsCString()); + LogInfo("Ignore invalid OMR prefix in RIO: %s", prefix.ToString().AsCString()); ExitNow(); } @@ -1291,8 +1291,8 @@ void RoutingManager::UpdateDiscoveredOmrPrefix(const RouterAdv::RouteInfoOption VerifyOrExit(!mAdvertisedOmrPrefixes.Contains(prefix)); VerifyOrExit(!NetworkDataContainsOmrPrefix(prefix)); - otLogInfoBr("Discovered OMR prefix (%s, %u seconds) from interface %u", prefix.ToString().AsCString(), - aRio.GetRouteLifetime(), mInfraIfIndex); + LogInfo("Discovered OMR prefix (%s, %u seconds) from interface %u", prefix.ToString().AsCString(), + aRio.GetRouteLifetime(), mInfraIfIndex); if (aRio.GetRouteLifetime() == 0) { @@ -1328,7 +1328,7 @@ void RoutingManager::UpdateDiscoveredOmrPrefix(const RouterAdv::RouteInfoOption } else { - otLogWarnBr("Discovered too many prefixes, ignore new prefix %s", prefix.ToString().AsCString()); + LogWarn("Discovered too many prefixes, ignore new prefix %s", prefix.ToString().AsCString()); ExitNow(); } } @@ -1493,14 +1493,14 @@ void RoutingManager::ResetDiscoveredPrefixStaleTimer(void) { if (mDiscoveredPrefixStaleTimer.IsRunning()) { - otLogDebgBr("Prefix stale timer stopped"); + LogDebg("Prefix stale timer stopped"); } mDiscoveredPrefixStaleTimer.Stop(); } else { mDiscoveredPrefixStaleTimer.FireAt(nextStaleTime); - otLogDebgBr("Prefix stale timer scheduled in %lu ms", nextStaleTime - now); + LogDebg("Prefix stale timer scheduled in %lu ms", nextStaleTime - now); } } diff --git a/src/core/coap/coap.cpp b/src/core/coap/coap.cpp index 20108d925..92375c729 100644 --- a/src/core/coap/coap.cpp +++ b/src/core/coap/coap.cpp @@ -34,7 +34,7 @@ #include "common/debug.hpp" #include "common/instance.hpp" #include "common/locator_getters.hpp" -#include "common/logging.hpp" +#include "common/log.hpp" #include "common/random.hpp" #include "net/ip6.hpp" #include "net/udp6.hpp" @@ -48,6 +48,8 @@ namespace ot { namespace Coap { +RegisterLogModule("Coap"); + CoapBase::CoapBase(Instance &aInstance, Sender aSender) : InstanceLocator(aInstance) , mMessageId(Random::NonCrypto::GetUint16()) @@ -677,8 +679,8 @@ Error CoapBase::SendNextBlock1Request(Message & aRequest, DequeueMessage(aRequest); - otLogInfoCoap("Send Block1 Nr. %d, Size: %d bytes, More Blocks Flag: %d", request->GetBlockWiseBlockNumber(), - otCoapBlockSizeFromExponent(request->GetBlockWiseBlockSize()), request->IsMoreBlocksFlagSet()); + LogInfo("Send Block1 Nr. %d, Size: %d bytes, More Blocks Flag: %d", request->GetBlockWiseBlockNumber(), + otCoapBlockSizeFromExponent(request->GetBlockWiseBlockSize()), request->IsMoreBlocksFlagSet()); SuccessOrExit(error = SendMessage(*request, aMessageInfo, TxParameters::GetDefault(), aCoapMetadata.mResponseHandler, aCoapMetadata.mResponseContext, @@ -719,8 +721,8 @@ Error CoapBase::SendNextBlock2Request(Message & aRequest, bufLen, aMessage.IsMoreBlocksFlagSet(), aTotalLength)); // CoAP Block-Wise Transfer continues - otLogInfoCoap("Received Block2 Nr. %d , Size: %d bytes, More Blocks Flag: %d", aMessage.GetBlockWiseBlockNumber(), - otCoapBlockSizeFromExponent(aMessage.GetBlockWiseBlockSize()), aMessage.IsMoreBlocksFlagSet()); + LogInfo("Received Block2 Nr. %d , Size: %d bytes, More Blocks Flag: %d", aMessage.GetBlockWiseBlockNumber(), + otCoapBlockSizeFromExponent(aMessage.GetBlockWiseBlockSize()), aMessage.IsMoreBlocksFlagSet()); // Conclude block-wise transfer if last block has been received if (!aMessage.IsMoreBlocksFlagSet()) @@ -739,8 +741,8 @@ Error CoapBase::SendNextBlock2Request(Message & aRequest, DequeueMessage(aRequest); } - otLogInfoCoap("Request Block2 Nr. %d, Size: %d bytes", request->GetBlockWiseBlockNumber(), - otCoapBlockSizeFromExponent(request->GetBlockWiseBlockSize())); + LogInfo("Request Block2 Nr. %d, Size: %d bytes", request->GetBlockWiseBlockNumber(), + otCoapBlockSizeFromExponent(request->GetBlockWiseBlockSize())); SuccessOrExit(error = SendMessage(*request, aMessageInfo, TxParameters::GetDefault(), aCoapMetadata.mResponseHandler, @@ -790,8 +792,8 @@ Error CoapBase::ProcessBlock1Request(Message & aMessage, SuccessOrExit(error = CacheLastBlockResponse(response)); - otLogInfoCoap("Acknowledge Block1 Nr. %d, Size: %d bytes", response->GetBlockWiseBlockNumber(), - otCoapBlockSizeFromExponent(response->GetBlockWiseBlockSize())); + LogInfo("Acknowledge Block1 Nr. %d, Size: %d bytes", response->GetBlockWiseBlockNumber(), + otCoapBlockSizeFromExponent(response->GetBlockWiseBlockSize())); SuccessOrExit(error = SendMessage(*response, aMessageInfo)); @@ -827,8 +829,8 @@ Error CoapBase::ProcessBlock2Request(Message & aMessage, SuccessOrExit(error = aMessage.ReadBlockOptionValues(kOptionBlock2)); - otLogInfoCoap("Request for Block2 Nr. %d, Size: %d bytes received", aMessage.GetBlockWiseBlockNumber(), - otCoapBlockSizeFromExponent(aMessage.GetBlockWiseBlockSize())); + LogInfo("Request for Block2 Nr. %d, Size: %d bytes received", aMessage.GetBlockWiseBlockNumber(), + otCoapBlockSizeFromExponent(aMessage.GetBlockWiseBlockSize())); if (aMessage.GetBlockWiseBlockNumber() == 0) { @@ -927,8 +929,8 @@ Error CoapBase::ProcessBlock2Request(Message & aMessage, FreeLastBlockResponse(); } - otLogInfoCoap("Send Block2 Nr. %d, Size: %d bytes, More Blocks Flag %d", response->GetBlockWiseBlockNumber(), - otCoapBlockSizeFromExponent(response->GetBlockWiseBlockSize()), response->IsMoreBlocksFlagSet()); + LogInfo("Send Block2 Nr. %d, Size: %d bytes, More Blocks Flag %d", response->GetBlockWiseBlockNumber(), + otCoapBlockSizeFromExponent(response->GetBlockWiseBlockSize()), response->IsMoreBlocksFlagSet()); SuccessOrExit(error = SendMessage(*response, aMessageInfo)); @@ -954,7 +956,7 @@ exit: if (error != kErrorNone) { - otLogWarnCoap("Failed to send copy: %s", ErrorToString(error)); + LogWarn("Failed to send copy: %s", ErrorToString(error)); FreeMessage(messageCopy); } } @@ -1007,7 +1009,7 @@ void CoapBase::Receive(ot::Message &aMessage, const Ip6::MessageInfo &aMessageIn if (message.ParseHeader() != kErrorNone) { - otLogDebgCoap("Failed to parse CoAP header"); + LogDebg("Failed to parse CoAP header"); if (!aMessageInfo.GetSockAddr().IsMulticast() && message.IsConfirmable()) { @@ -1399,7 +1401,7 @@ exit: if (error != kErrorNone) { - otLogInfoCoap("Failed to process request: %s", ErrorToString(error)); + LogInfo("Failed to process request: %s", ErrorToString(error)); if (error == kErrorNotFound && !aMessageInfo.GetSockAddr().IsMulticast()) { diff --git a/src/core/coap/coap_secure.cpp b/src/core/coap/coap_secure.cpp index b4b519757..d15873147 100644 --- a/src/core/coap/coap_secure.cpp +++ b/src/core/coap/coap_secure.cpp @@ -32,7 +32,7 @@ #include "common/instance.hpp" #include "common/locator_getters.hpp" -#include "common/logging.hpp" +#include "common/log.hpp" #include "common/new.hpp" #include "meshcop/dtls.hpp" #include "thread/thread_netif.hpp" @@ -45,6 +45,8 @@ namespace ot { namespace Coap { +RegisterLogModule("CoapSecure"); + CoapSecure::CoapSecure(Instance &aInstance, bool aLayerTwoSecurity) : CoapBase(aInstance, &CoapSecure::Send) , mDtls(aInstance, aLayerTwoSecurity) @@ -221,12 +223,12 @@ void CoapSecure::HandleTransmit(void) exit: if (error != kErrorNone) { - otLogNoteMeshCoP("CoapSecure Transmit: %s", ErrorToString(error)); + LogNote("Transmit: %s", ErrorToString(error)); message->Free(); } else { - otLogDebgMeshCoP("CoapSecure Transmit: %s", ErrorToString(error)); + LogDebg("Transmit: %s", ErrorToString(error)); } } diff --git a/src/core/common/instance.cpp b/src/core/common/instance.cpp index fb543e4e4..bb2b4a745 100644 --- a/src/core/common/instance.cpp +++ b/src/core/common/instance.cpp @@ -35,7 +35,6 @@ #include -#include "common/logging.hpp" #include "common/new.hpp" #include "radio/trel_link.hpp" #include "utils/heap.hpp" @@ -59,7 +58,7 @@ bool Instance::sDnsNameCompressionEnabled = true; #endif #if OPENTHREAD_CONFIG_LOG_LEVEL_DYNAMIC_ENABLE -otLogLevel Instance::sLogLevel = static_cast(OPENTHREAD_CONFIG_LOG_LEVEL_INIT); +LogLevel Instance::sLogLevel = static_cast(OPENTHREAD_CONFIG_LOG_LEVEL_INIT); #endif Instance::Instance(void) diff --git a/src/core/common/instance.hpp b/src/core/common/instance.hpp index 478f03b03..5706cf2f0 100644 --- a/src/core/common/instance.hpp +++ b/src/core/common/instance.hpp @@ -40,7 +40,6 @@ #include #include -#include #if OPENTHREAD_CONFIG_HEAP_EXTERNAL_ENABLE #include #endif @@ -49,6 +48,7 @@ #include "common/as_core_type.hpp" #include "common/error.hpp" #include "common/extension.hpp" +#include "common/log.hpp" #include "common/message.hpp" #include "common/non_copyable.hpp" #include "common/random_manager.hpp" @@ -181,14 +181,14 @@ public: * @returns The log level. * */ - static otLogLevel GetLogLevel(void) + static LogLevel GetLogLevel(void) #if OPENTHREAD_CONFIG_LOG_LEVEL_DYNAMIC_ENABLE { return sLogLevel; } #else { - return static_cast(OPENTHREAD_CONFIG_LOG_LEVEL); + return static_cast(OPENTHREAD_CONFIG_LOG_LEVEL); } #endif @@ -199,11 +199,7 @@ public: * @param[in] aLogLevel A log level. * */ - static void SetLogLevel(otLogLevel aLogLevel) - { - OT_ASSERT(aLogLevel <= OT_LOG_LEVEL_DEBG && aLogLevel >= OT_LOG_LEVEL_NONE); - sLogLevel = aLogLevel; - } + static void SetLogLevel(LogLevel aLogLevel) { sLogLevel = aLogLevel; } #endif /** @@ -396,7 +392,7 @@ private: #endif // OPENTHREAD_RADIO || OPENTHREAD_CONFIG_LINK_RAW_ENABLE #if OPENTHREAD_CONFIG_LOG_LEVEL_DYNAMIC_ENABLE - static otLogLevel sLogLevel; + static LogLevel sLogLevel; #endif #if OPENTHREAD_ENABLE_VENDOR_EXTENSION Extension::ExtensionBase &mExtension; diff --git a/src/core/common/log.cpp b/src/core/common/log.cpp new file mode 100644 index 000000000..fa60f140e --- /dev/null +++ b/src/core/common/log.cpp @@ -0,0 +1,262 @@ +/* + * Copyright (c) 2017-2022, The OpenThread Authors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +/** + * @file + * This file implements the logging related functions. + */ + +#include "log.hpp" + +#include + +#include + +#include "common/code_utils.hpp" +#include "common/instance.hpp" +#include "common/string.hpp" + +/* + * Verify debug UART dependency. + * + * It is reasonable to only enable the debug UART and not enable logs to the DEBUG UART. + */ +#if (OPENTHREAD_CONFIG_LOG_OUTPUT == OPENTHREAD_CONFIG_LOG_OUTPUT_DEBUG_UART) && (!OPENTHREAD_CONFIG_ENABLE_DEBUG_UART) +#error "OPENTHREAD_CONFIG_ENABLE_DEBUG_UART_LOG requires OPENTHREAD_CONFIG_ENABLE_DEBUG_UART" +#endif + +#if OPENTHREAD_CONFIG_LOG_PREPEND_UPTIME && !OPENTHREAD_CONFIG_UPTIME_ENABLE +#error "OPENTHREAD_CONFIG_LOG_PREPEND_UPTIME requires OPENTHREAD_CONFIG_UPTIME_ENABLE" +#endif + +#if OPENTHREAD_CONFIG_LOG_PREPEND_UPTIME && OPENTHREAD_CONFIG_MULTIPLE_INSTANCE_ENABLE +#error "OPENTHREAD_CONFIG_LOG_PREPEND_UPTIME is not supported under OPENTHREAD_CONFIG_MULTIPLE_INSTANCE_ENABLE" +#endif + +namespace ot { + +template void Logger::LogAtLevel(const char *aModuleName, const char *aFormat, ...) +{ + va_list args; + + va_start(args, aFormat); + LogVarArgs(aModuleName, kLogLevel, aFormat, args); + va_end(args); +} + +// Explicit instantiations +template void Logger::LogAtLevel(const char *aModuleName, const char *aFormat, ...); +template void Logger::LogAtLevel(const char *aModuleName, const char *aFormat, ...); +template void Logger::LogAtLevel(const char *aModuleName, const char *aFormat, ...); +template void Logger::LogAtLevel(const char *aModuleName, const char *aFormat, ...); +template void Logger::LogAtLevel(const char *aModuleName, const char *aFormat, ...); +template void Logger::LogAtLevel(const char *aModuleName, const char *aFormat, ...); + +void Logger::LogInModule(const char *aModuleName, LogLevel aLogLevel, const char *aFormat, ...) +{ + va_list args; + + va_start(args, aFormat); + LogVarArgs(aModuleName, aLogLevel, aFormat, args); + va_end(args); +} + +void Logger::LogVarArgs(const char *aModuleName, LogLevel aLogLevel, const char *aFormat, va_list aArgs) +{ + static const char kModuleNamePadding[] = "--------------"; + + ot::String logString; + + static_assert(sizeof(kModuleNamePadding) == kMaxLogModuleNameLength + 1, "Padding string is not correct"); + +#if OPENTHREAD_CONFIG_LOG_PREPEND_UPTIME + ot::Uptime::UptimeToString(ot::Instance::Get().Get().GetUptime(), logString); + logString.Append(" "); +#endif + +#if OPENTHREAD_CONFIG_LOG_LEVEL_DYNAMIC_ENABLE + VerifyOrExit(Instance::GetLogLevel() >= aLogLevel); +#endif + +#if OPENTHREAD_CONFIG_LOG_PREPEND_LEVEL + { + static const char kLevelChars[] = { + '-', /* kLogLevelNone */ + 'C', /* kLogLevelCrit */ + 'W', /* kLogLevelWarn */ + 'N', /* kLogLevelNote */ + 'I', /* kLogLevelInfo */ + 'D', /* kLogLevelDebg */ + }; + + logString.Append("[%c] ", kLevelChars[aLogLevel]); + } +#endif + + logString.Append("%.*s%s: ", kMaxLogModuleNameLength, aModuleName, + &kModuleNamePadding[StringLength(aModuleName, kMaxLogModuleNameLength)]); + + logString.AppendVarArgs(aFormat, aArgs); + + logString.Append("%s", OPENTHREAD_CONFIG_LOG_SUFFIX); + otPlatLog(aLogLevel, OT_LOG_REGION_CORE, "%s", logString.AsCString()); + + ExitNow(); + +exit: + return; +} + +#if OPENTHREAD_CONFIG_LOG_PKT_DUMP + +template +void Logger::DumpAtLevel(const char *aModuleName, const char *aText, const void *aData, uint16_t aDataLength) +{ + DumpInModule(aModuleName, kLogLevel, aText, aData, aDataLength); +} + +// Explicit instantiations +template void Logger::DumpAtLevel(const char *aModuleName, + const char *aText, + const void *aData, + uint16_t aDataLength); +template void Logger::DumpAtLevel(const char *aModuleName, + const char *aText, + const void *aData, + uint16_t aDataLength); +template void Logger::DumpAtLevel(const char *aModuleName, + const char *aText, + const void *aData, + uint16_t aDataLength); +template void Logger::DumpAtLevel(const char *aModuleName, + const char *aText, + const void *aData, + uint16_t aDataLength); +template void Logger::DumpAtLevel(const char *aModuleName, + const char *aText, + const void *aData, + uint16_t aDataLength); +template void Logger::DumpAtLevel(const char *aModuleName, + const char *aText, + const void *aData, + uint16_t aDataLength); + +void Logger::DumpLine(const char *aModuleName, LogLevel aLogLevel, const uint8_t *aData, const uint16_t aDataLength) +{ + ot::String string; + + string.Append("|"); + + for (uint8_t i = 0; i < kDumpBytesPerLine; i++) + { + if (i < aDataLength) + { + string.Append(" %02X", aData[i]); + } + else + { + string.Append(" .."); + } + + if (!((i + 1) % 8)) + { + string.Append(" |"); + } + } + + string.Append(" "); + + for (uint8_t i = 0; i < kDumpBytesPerLine; i++) + { + char c = '.'; + + if (i < aDataLength) + { + char byteAsChar = static_cast(0x7f & aData[i]); + + if (isprint(byteAsChar)) + { + c = byteAsChar; + } + } + + string.Append("%c", c); + } + + LogInModule(aModuleName, aLogLevel, "%s", string.AsCString()); +} + +void Logger::DumpInModule(const char *aModuleName, + LogLevel aLogLevel, + const char *aText, + const void *aData, + uint16_t aDataLength) +{ + constexpr uint16_t kWidth = 72; + constexpr uint16_t kTextSuffixLen = sizeof("[ len=000]") - 1; + + uint16_t txtLen = StringLength(aText, kWidth - kTextSuffixLen) + kTextSuffixLen; + ot::String string; + + VerifyOrExit(otLoggingGetLevel() >= aLogLevel); + + for (uint16_t i = 0; i < static_cast((kWidth - txtLen) / 2); i++) + { + string.Append("="); + } + + string.Append("[%s len=%03u]", aText, aDataLength); + + for (uint16_t i = 0; i < static_cast(kWidth - txtLen - (kWidth - txtLen) / 2); i++) + { + string.Append("="); + } + + LogInModule(aModuleName, aLogLevel, "%s", string.AsCString()); + + for (uint16_t i = 0; i < aDataLength; i += kDumpBytesPerLine) + { + DumpLine(aModuleName, aLogLevel, static_cast(aData) + i, + OT_MIN((aDataLength - i), kDumpBytesPerLine)); + } + + string.Clear(); + + for (uint16_t i = 0; i < kWidth; i++) + { + string.Append("-"); + } + + LogInModule(aModuleName, aLogLevel, "%s", string.AsCString()); + +exit: + return; +} +#endif // OPENTHREAD_CONFIG_LOG_PKT_DUMP + +} // namespace ot diff --git a/src/core/common/log.hpp b/src/core/common/log.hpp new file mode 100644 index 000000000..6bb03c4bd --- /dev/null +++ b/src/core/common/log.hpp @@ -0,0 +1,346 @@ +/* + * Copyright (c) 2022, The OpenThread Authors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +/** + * @file + * This file includes logging related definitions. + */ + +#ifndef LOG_HPP_ +#define LOG_HPP_ + +#include "openthread-core-config.h" + +#include +#include +#include + +namespace ot { + +/** + * This enumeration represents the log level. + * + */ +enum LogLevel : uint8_t +{ + kLogLevelNone = OT_LOG_LEVEL_NONE, ///< None (disable logs) + kLogLevelCrit = OT_LOG_LEVEL_CRIT, ///< Critical log level + kLogLevelWarn = OT_LOG_LEVEL_WARN, ///< Warning log level + kLogLevelNote = OT_LOG_LEVEL_NOTE, ///< Note log level + kLogLevelInfo = OT_LOG_LEVEL_INFO, ///< Info log level + kLogLevelDebg = OT_LOG_LEVEL_DEBG, ///< Debug log level +}; + +constexpr uint8_t kMaxLogModuleNameLength = 14; ///< Maximum module name length + +/** + * This macro registers log module name. + * + * This macro is used in a `cpp` file to register the log module name for that file before using any other logging + * functions or macros (e.g., `LogInfo()` or `DumpInfo()`, ...) in the file. + * + * @param[in] aName The log module name string (MUST be shorter than `kMaxLogModuleNameLength`). + * + */ +#define RegisterLogModule(aName) \ + constexpr char kLogModuleName[] = aName; \ + namespace { \ + /* Defining this type to silence "unused constant" warning/error \ + * for `kLogModuleName` under any log level config. \ + */ \ + using DummyType = char[sizeof(kLogModuleName)]; \ + } \ + static_assert(sizeof(kLogModuleName) <= kMaxLogModuleNameLength + 1, "Log module name is too long") + +#if OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_CRIT + +/** + * This macro emits a log message at critical log level. + * + * @param[in] ... Arguments for the format specification. + * + */ +#define LogCrit(...) Logger::Log(__VA_ARGS__) +#else +#define LogCrit(...) +#endif + +#if OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_WARN +/** + * This macro emits a log message at warning log level. + * + * @param[in] ... Arguments for the format specification. + * + */ +#define LogWarn(...) Logger::Log(__VA_ARGS__) +#else +#define LogWarn(...) +#endif + +#if OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_NOTE +/** + * This macro emits a log message at note log level. + * + * @param[in] ... Arguments for the format specification. + * + */ +#define LogNote(...) Logger::Log(__VA_ARGS__) +#else +#define LogNote(...) +#endif + +#if OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO +/** + * This macro emits a log message at info log level. + * + * @param[in] ... Arguments for the format specification. + * + */ +#define LogInfo(...) Logger::Log(__VA_ARGS__) +#else +#define LogInfo(...) +#endif + +#if OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_DEBG +/** + * This macro emits a log message at debug log level. + * + * @param[in] ... Arguments for the format specification. + * + */ +#define LogDebg(...) Logger::Log(__VA_ARGS__) +#else +#define LogDebg(...) +#endif + +/** + * This macro emits a log message at a given log level. + * + * @param[in] aLogLevel The log level to use. + * @param[in] ... Argument for the format specification. + * + */ +#define LogAt(aLogLevel, ...) Logger::LogInModule(kLogModuleName, aLogLevel, __VA_ARGS__) + +/** + * This macro emits a log message independent of the configured log level. + * + * @param[in] ... Arguments for the format specification. + * + */ +#define LogAlways(...) Logger::LogInModule("", kLogLevelNone, __VA_ARGS__) + +#if OPENTHREAD_CONFIG_REFERENCE_DEVICE_ENABLE +/** + * This macro emit a log message for the certification test. + * + * @param[in] ... Arguments for the format specification. + * + */ +#define LogCert(...) LogAlways(__VA_ARGS__) +#else +#define LogCert(...) +#endif + +#if (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_CRIT) && OPENTHREAD_CONFIG_LOG_PKT_DUMP +/** + * This macro generates a memory dump at log level critical. + * + * @param[in] aText A string that is printed before the bytes. + * @param[in] aData A pointer to the data buffer. + * @param[in] aDataLength Number of bytes in @p aData. + * + */ +#define DumpCrit(aText, aData, aDataLength) Logger::Dump(aText, aData, aDataLength) +#else +#define DumpCrit(aText, aData, aDataLength) +#endif + +#if (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_WARN) && OPENTHREAD_CONFIG_LOG_PKT_DUMP +/** + * This macro generates a memory dump at log level warning. + * + * @param[in] aText A string that is printed before the bytes. + * @param[in] aData A pointer to the data buffer. + * @param[in] aDataLength Number of bytes in @p aData. + * + */ +#define DumpWarn(aText, aData, aDataLength) Logger::Dump(aText, aData, aDataLength) +#else +#define DumpWarn(aText, aData, aDataLength) +#endif + +#if (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_NOTE) && OPENTHREAD_CONFIG_LOG_PKT_DUMP +/** + * This macro generates a memory dump at log level note. + * + * @param[in] aText A string that is printed before the bytes. + * @param[in] aData A pointer to the data buffer. + * @param[in] aDataLength Number of bytes in @p aData. + * + */ +#define DumpNote(aText, aData, aDataLength) Logger::Dump(aText, aData, aDataLength) +#else +#define DumpNote(aText, aData, aDataLength) +#endif + +#if (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO) && OPENTHREAD_CONFIG_LOG_PKT_DUMP +/** + * This macro generates a memory dump at log level info. + * + * @param[in] aText A string that is printed before the bytes. + * @param[in] aData A pointer to the data buffer. + * @param[in] aDataLength Number of bytes in @p aData. + * + */ +#define DumpInfo(aText, aData, aDataLength) Logger::Dump(aText, aData, aDataLength) +#else +#define DumpInfo(aText, aData, aDataLength) +#endif + +#if (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_DEBG) && OPENTHREAD_CONFIG_LOG_PKT_DUMP +/** + * This macro generates a memory dump at log level debug. + * + * @param[in] aText A string that is printed before the bytes. + * @param[in] aData A pointer to the data buffer. + * @param[in] aDataLength Number of bytes in @p aData. + * + */ +#define DumpDebg(aText, aData, aDataLength) Logger::Dump(aText, aData, aDataLength) +#else +#define DumpDebg(aText, aData, aDataLength) +#endif + +#if OPENTHREAD_CONFIG_LOG_PKT_DUMP +/** + * This macro generates a memory dump independent of the configured log level. + * + * @param[in] aText A string that is printed before the bytes. + * @param[in] aData A pointer to the data buffer. + * @param[in] aDataLength Number of bytes in @p aData. + * + */ +#define DumpAlways(aText, aData, aDataLength) Logger::DumpInModule("", kLogLevelNone, aText, aData, aDataLength) +#endif + +#if OPENTHREAD_CONFIG_REFERENCE_DEVICE_ENABLE && OPENTHREAD_CONFIG_LOG_PKT_DUMP +/** + * This macro generates a memory dump for certification test. + * + * @param[in] aText A string that is printed before the bytes. + * @param[in] aData A pointer to the data buffer. + * @param[in] aDataLength Number of bytes in @p aData. + * + */ +#define DumpCert(aText, aData, aDataLength) DumpAlways(aText, aData, aDataLength) +#else +#define DumpCert(aText, aData, aDataLength) +#endif + +//---------------------------------------------------------------------------------------------------------------------- + +class Logger +{ + // The `Logger` class implements the logging methods. + // + // The `Logger` methods are not intended to be directly used + // and instead the logging macros should be used. + +public: + template + static void Log(const char *aFormat, Args... aArgs) + { + LogAtLevel(kModuleName, aFormat, aArgs...); + } + + static void LogInModule(const char *aModuleName, LogLevel aLogLevel, const char *aFormat, ...); + + template static void LogAtLevel(const char *aModuleName, const char *aFormat, ...); + static void LogVarArgs(const char *aModuleName, LogLevel aLogLevel, const char *aFormat, va_list aArgs); + +#if OPENTHREAD_CONFIG_LOG_PKT_DUMP + static constexpr uint8_t kStringLineLength = 80; + static constexpr uint8_t kDumpBytesPerLine = 16; + + template + static void Dump(const char *aText, const void *aData, uint16_t aDataLength) + { + DumpAtLevel(kModuleName, aText, aData, aDataLength); + } + + static void DumpInModule(const char *aModuleName, + LogLevel aLogLevel, + const char *aText, + const void *aData, + uint16_t aDataLength); + + template + static void DumpAtLevel(const char *aModuleName, const char *aText, const void *aData, uint16_t aDataLength); + + static void DumpLine(const char *aModuleName, LogLevel aLogLevel, const uint8_t *aData, uint16_t aDataLength); +#endif +}; + +extern template void Logger::LogAtLevel(const char *aModuleName, const char *aFormat, ...); +extern template void Logger::LogAtLevel(const char *aModuleName, const char *aFormat, ...); +extern template void Logger::LogAtLevel(const char *aModuleName, const char *aFormat, ...); +extern template void Logger::LogAtLevel(const char *aModuleName, const char *aFormat, ...); +extern template void Logger::LogAtLevel(const char *aModuleName, const char *aFormat, ...); +extern template void Logger::LogAtLevel(const char *aModuleName, const char *aFormat, ...); + +#if OPENTHREAD_CONFIG_LOG_PKT_DUMP +extern template void Logger::DumpAtLevel(const char *aModuleName, + const char *aText, + const void *aData, + uint16_t aDataLength); +extern template void Logger::DumpAtLevel(const char *aModuleName, + const char *aText, + const void *aData, + uint16_t aDataLength); +extern template void Logger::DumpAtLevel(const char *aModuleName, + const char *aText, + const void *aData, + uint16_t aDataLength); +extern template void Logger::DumpAtLevel(const char *aModuleName, + const char *aText, + const void *aData, + uint16_t aDataLength); +extern template void Logger::DumpAtLevel(const char *aModuleName, + const char *aText, + const void *aData, + uint16_t aDataLength); +extern template void Logger::DumpAtLevel(const char *aModuleName, + const char *aText, + const void *aData, + uint16_t aDataLength); +#endif + +} // namespace ot + +#endif // LOG_HPP_ diff --git a/src/core/common/logging.cpp b/src/core/common/logging.cpp deleted file mode 100644 index af450944c..000000000 --- a/src/core/common/logging.cpp +++ /dev/null @@ -1,351 +0,0 @@ -/* - * Copyright (c) 2016, The OpenThread Authors. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the copyright holder nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -/** - * @file - * This file implements the logging related functions. - */ - -#include "logging.hpp" - -#include "common/code_utils.hpp" -#include "common/instance.hpp" -#include "common/string.hpp" - -/* - * Verify debug uart dependency. - * - * It is reasonable to only enable the debug uart and not enable logs to the DEBUG uart. - */ -#if (OPENTHREAD_CONFIG_LOG_OUTPUT == OPENTHREAD_CONFIG_LOG_OUTPUT_DEBUG_UART) && (!OPENTHREAD_CONFIG_ENABLE_DEBUG_UART) -#error "OPENTHREAD_CONFIG_ENABLE_DEBUG_UART_LOG requires OPENTHREAD_CONFIG_ENABLE_DEBUG_UART" -#endif - -#if OPENTHREAD_CONFIG_LOG_PREPEND_UPTIME && !OPENTHREAD_CONFIG_UPTIME_ENABLE -#error "OPENTHREAD_CONFIG_LOG_PREPEND_UPTIME requires OPENTHREAD_CONFIG_UPTIME_ENABLE" -#endif - -#if OPENTHREAD_CONFIG_LOG_PREPEND_UPTIME && OPENTHREAD_CONFIG_MULTIPLE_INSTANCE_ENABLE -#error "OPENTHREAD_CONFIG_LOG_PREPEND_UPTIME is not supported under OPENTHREAD_CONFIG_MULTIPLE_INSTANCE_ENABLE" -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -static void Log(otLogLevel aLogLevel, otLogRegion aLogRegion, const char *aFormat, va_list aArgs) -{ - ot::String logString; - -#if OPENTHREAD_CONFIG_LOG_PREPEND_UPTIME - ot::Uptime::UptimeToString(ot::Instance::Get().Get().GetUptime(), logString); - logString.Append(" "); -#endif - -#if OPENTHREAD_CONFIG_LOG_LEVEL_DYNAMIC_ENABLE - VerifyOrExit(otLoggingGetLevel() >= aLogLevel); -#endif - -#if OPENTHREAD_CONFIG_LOG_PREPEND_LEVEL - - { - static const char *const kLevelStrings[] = { - "NONE", "CRIT", "WARN", "NOTE", "INFO", "DEBG", - }; - - uint16_t index = ((aLogLevel >= 0) && (aLogLevel < static_cast(OT_ARRAY_LENGTH(kLevelStrings)))) - ? static_cast(aLogLevel) - : 0; - - logString.Append("[%s]", kLevelStrings[index]); - } -#endif - -#if OPENTHREAD_CONFIG_LOG_PREPEND_REGION - { - static const char *const kRegionStrings[] = { - "-------", "API----", "MLE----", "ARP----", "N-DATA-", "ICMP---", "IP6----", "TCP----", - "MAC----", "MEM----", "NCP----", "MESH-CP", "DIAG---", "PLAT---", "COAP---", "CLI----", - "CORE---", "UTIL---", "BBR----", "MLR----", "DUA----", "BR-----", "SRP----", "DNS----", - }; - - uint16_t index = (aLogRegion < OT_ARRAY_LENGTH(kRegionStrings)) ? static_cast(aLogRegion) : 0; - - logString.Append("-%s-: ", kRegionStrings[index]); - } -#elif OPENTHREAD_CONFIG_LOG_PREPEND_LEVEL - logString.Append(": "); -#endif - - logString.AppendVarArgs(aFormat, aArgs); - otPlatLog(aLogLevel, aLogRegion, "%s" OPENTHREAD_CONFIG_LOG_SUFFIX, logString.AsCString()); - -#if OPENTHREAD_CONFIG_LOG_LEVEL_DYNAMIC_ENABLE -exit: - return; -#endif -} - -#if OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_CRIT -void _otLogCrit(otLogRegion aRegion, const char *aFormat, ...) -{ - va_list args; - - va_start(args, aFormat); - Log(OT_LOG_LEVEL_CRIT, aRegion, aFormat, args); - va_end(args); -} -#endif - -#if OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_WARN -void _otLogWarn(otLogRegion aRegion, const char *aFormat, ...) -{ - va_list args; - - va_start(args, aFormat); - Log(OT_LOG_LEVEL_WARN, aRegion, aFormat, args); - va_end(args); -} -#endif - -#if OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_NOTE -void _otLogNote(otLogRegion aRegion, const char *aFormat, ...) -{ - va_list args; - - va_start(args, aFormat); - Log(OT_LOG_LEVEL_NOTE, aRegion, aFormat, args); - va_end(args); -} -#endif - -#if OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO -void _otLogInfo(otLogRegion aRegion, const char *aFormat, ...) -{ - va_list args; - - va_start(args, aFormat); - Log(OT_LOG_LEVEL_INFO, aRegion, aFormat, args); - va_end(args); -} -#endif - -#if OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_DEBG -void _otLogDebg(otLogRegion aRegion, const char *aFormat, ...) -{ - va_list args; - - va_start(args, aFormat); - Log(OT_LOG_LEVEL_DEBG, aRegion, aFormat, args); - va_end(args); -} -#endif - -#if OPENTHREAD_CONFIG_LOG_MAC -void otLogMac(otLogLevel aLogLevel, const char *aFormat, ...) -{ - va_list args; - - VerifyOrExit(otLoggingGetLevel() >= aLogLevel); - - va_start(args, aFormat); - Log(aLogLevel, OT_LOG_REGION_MAC, aFormat, args); - va_end(args); - -exit: - return; -} - -void otDumpMacFrame(otLogLevel aLogLevel, const char *aId, const void *aBuf, const size_t aLength) -{ - constexpr uint8_t kFixedStringPart = 10; // strlen(" seqno=000") - constexpr uint8_t kSeqnoIdx = 2; // index of the sequence number within aBuf - - size_t idLength = strlen(aId) + kFixedStringPart + 1; // allow for the '\0' character - char newId[25]; - - VerifyOrExit(idLength <= sizeof(newId)); - snprintf(newId, idLength, "%s seqno=%03u", aId, static_cast(aBuf)[kSeqnoIdx]); - otDump(aLogLevel, OT_LOG_REGION_MAC, newId, aBuf, aLength); -exit: - return; -} -#endif - -#if OPENTHREAD_CONFIG_REFERENCE_DEVICE_ENABLE -void otLogCertMeshCoP(const char *aFormat, ...) -{ - va_list args; - - va_start(args, aFormat); - Log(OT_LOG_LEVEL_NONE, OT_LOG_REGION_MESH_COP, aFormat, args); - va_end(args); -} -#endif - -#if OPENTHREAD_CONFIG_OTNS_ENABLE -void otLogOtns(const char *aFormat, ...) -{ - va_list args; - - va_start(args, aFormat); - Log(OT_LOG_LEVEL_NONE, OT_LOG_REGION_CORE, aFormat, args); - va_end(args); -} -#endif - -#if OPENTHREAD_CONFIG_LOG_PKT_DUMP - -static void otLogDump(otLogLevel aLogLevel, otLogRegion aRegion, const char *aFormat, ...) -{ - va_list args; - - VerifyOrExit(otLoggingGetLevel() >= aLogLevel); - - va_start(args, aFormat); - Log(aLogLevel, aRegion, aFormat, args); - va_end(args); - -exit: - return; -} - -static constexpr uint8_t kStringLineLength = 80; -static constexpr uint8_t kDumpBytesPerLine = 16; - -static void DumpLine(otLogLevel aLogLevel, otLogRegion aLogRegion, const uint8_t *aBytes, const size_t aLength) -{ - ot::String string; - - string.Append("|"); - - for (uint8_t i = 0; i < kDumpBytesPerLine; i++) - { - if (i < aLength) - { - string.Append(" %02X", aBytes[i]); - } - else - { - string.Append(" .."); - } - - if (!((i + 1) % 8)) - { - string.Append(" |"); - } - } - - string.Append(" "); - - for (uint8_t i = 0; i < kDumpBytesPerLine; i++) - { - char c = '.'; - - if (i < aLength) - { - char byteAsChar = static_cast(0x7f & aBytes[i]); - - if (isprint(byteAsChar)) - { - c = byteAsChar; - } - } - - string.Append("%c", c); - } - - otLogDump(aLogLevel, aLogRegion, "%s", string.AsCString()); -} - -void otDump(otLogLevel aLogLevel, otLogRegion aLogRegion, const char *aId, const void *aBuf, const size_t aLength) -{ - constexpr uint8_t kWidth = 72; - constexpr uint8_t kFixedStringPart = 10; // strlen("[ len=000]") - - size_t idLen = strlen(aId) + kFixedStringPart; - ot::String string; - - VerifyOrExit(otLoggingGetLevel() >= aLogLevel); - - for (size_t i = 0; i < (kWidth - idLen) / 2; i++) - { - string.Append("="); - } - - string.Append("[%s len=%03u]", aId, static_cast(aLength)); - - for (size_t i = 0; i < kWidth - idLen - (kWidth - idLen) / 2; i++) - { - string.Append("="); - } - - otLogDump(aLogLevel, aLogRegion, "%s", string.AsCString()); - - for (size_t i = 0; i < aLength; i += kDumpBytesPerLine) - { - DumpLine(aLogLevel, aLogRegion, static_cast(aBuf) + i, - OT_MIN((aLength - i), static_cast(kDumpBytesPerLine))); - } - - string.Clear(); - - for (size_t i = 0; i < kWidth; i++) - { - string.Append("-"); - } - - otLogDump(aLogLevel, aLogRegion, "%s", string.AsCString()); - -exit: - return; -} -#else // OPENTHREAD_CONFIG_LOG_PKT_DUMP -void otDump(otLogLevel, otLogRegion, const char *, const void *, const size_t) -{ -} -#endif // OPENTHREAD_CONFIG_LOG_PKT_DUMP - -#if OPENTHREAD_CONFIG_LOG_OUTPUT == OPENTHREAD_CONFIG_LOG_OUTPUT_NONE -/* this provides a stub, in case something uses the function */ -void otPlatLog(otLogLevel aLogLevel, otLogRegion aLogRegion, const char *aFormat, ...) -{ - OT_UNUSED_VARIABLE(aLogLevel); - OT_UNUSED_VARIABLE(aLogRegion); - OT_UNUSED_VARIABLE(aFormat); -} -#endif - -OT_TOOL_WEAK void otPlatLogLine(otLogLevel aLogLevel, otLogRegion aLogRegion, const char *aLogLine) -{ - otPlatLog(aLogLevel, aLogRegion, "%s", aLogLine); -} - -#ifdef __cplusplus -} -#endif diff --git a/src/core/common/logging.hpp b/src/core/common/logging.hpp index dc3167b28..56016bced 100644 --- a/src/core/common/logging.hpp +++ b/src/core/common/logging.hpp @@ -36,2554 +36,7 @@ #include "openthread-core-config.h" -#include -#include - #include #include -#include "common/arg_macros.hpp" - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * @def otLogCrit - * - * Logging at log level critical. - * - * @param[in] aRegion The log region. - * @param[in] ... Arguments for the format specification. - * - */ -#if OPENTHREAD_CONFIG_LOG_LEVEL < OT_LOG_LEVEL_CRIT -#define otLogCrit(aRegion, ...) -#else -#define otLogCrit(aRegion, ...) _otLogCrit(aRegion, __VA_ARGS__) -void _otLogCrit(otLogRegion aRegion, const char *aFormat, ...); -#endif - -/** - * @def otLogWarn - * - * Logging at log level warning. - * - * @param[in] aRegion The log region. - * @param[in] ... Arguments for the format specification. - * - */ -#if OPENTHREAD_CONFIG_LOG_LEVEL < OT_LOG_LEVEL_WARN -#define otLogWarn(aRegion, ...) -#else -#define otLogWarn(aRegion, ...) _otLogWarn(aRegion, __VA_ARGS__) -void _otLogWarn(otLogRegion aRegion, const char *aFormat, ...); -#endif - -/** - * @def otLogNote - * - * Logging at log level note - * - * @param[in] aRegion The log region. - * @param[in] ... Arguments for the format specification. - * - */ -#if OPENTHREAD_CONFIG_LOG_LEVEL < OT_LOG_LEVEL_NOTE -#define otLogNote(aRegion, ...) -#else -#define otLogNote(aRegion, ...) _otLogNote(aRegion, __VA_ARGS__) -void _otLogNote(otLogRegion aRegion, const char *aFormat, ...); -#endif - -/** - * @def otLogInfo - * - * Logging at log level info. - * - * @param[in] aRegion The log region. - * @param[in] ... Arguments for the format specification. - * - */ -#if OPENTHREAD_CONFIG_LOG_LEVEL < OT_LOG_LEVEL_INFO -#define otLogInfo(aRegion, ...) -#else -#define otLogInfo(aRegion, ...) _otLogInfo(aRegion, __VA_ARGS__) -void _otLogInfo(otLogRegion aRegion, const char *aFormat, ...); -#endif - -/** - * @def otLogDebg - * - * Logging at log level debug. - * - * @param[in] aRegion The log region. - * @param[in] ... Arguments for the format specification. - * - */ -#if OPENTHREAD_CONFIG_LOG_LEVEL < OT_LOG_LEVEL_DEBG -#define otLogDebg(aRegion, ...) -#else -#define otLogDebg(aRegion, ...) _otLogDebg(aRegion, __VA_ARGS__) -void _otLogDebg(otLogRegion aRegion, const char *aFormat, ...); -#endif - -/** - * @def otLogCritApi - * - * This function generates a log with level critical for the API region. - * - * @param[in] ... Arguments for the format specification. - * - */ - -/** - * @def otLogWarnApi - * - * This function generates a log with level warning for the API region. - * - * @param[in] ... Arguments for the format specification. - * - */ - -/** - * @def otLogNoteApi - * - * This function generates a log with level note for the API region. - * - * @param[in] ... Arguments for the format specification. - * - */ - -/** - * @def otLogInfoApi - * - * This function generates a log with level info for the API region. - * - * @param[in] ... Arguments for the format specification. - * - */ - -/** - * @def otLogDebgApi - * - * This function generates a log with level debug for the API region. - * - * @param[in] ... Arguments for the format specification. - * - */ -#if OPENTHREAD_CONFIG_LOG_API -#define otLogCritApi(...) otLogCrit(OT_LOG_REGION_API, __VA_ARGS__) -#define otLogWarnApi(...) otLogWarn(OT_LOG_REGION_API, __VA_ARGS__) -#define otLogNoteApi(...) otLogNote(OT_LOG_REGION_API, __VA_ARGS__) -#define otLogInfoApi(...) otLogInfo(OT_LOG_REGION_API, __VA_ARGS__) -#define otLogDebgApi(...) otLogDebg(OT_LOG_REGION_API, __VA_ARGS__) -#else -#define otLogCritApi(...) -#define otLogWarnApi(...) -#define otLogNoteApi(...) -#define otLogInfoApi(...) -#define otLogDebgApi(...) -#endif - -/** - * @def otLogCritMeshCoP - * - * This function generates a log with level critical for the MeshCoP region. - * - * @param[in] ... Arguments for the format specification. - * - * - */ - -/** - * @def otLogWarnMeshCoP - * - * This function generates a log with level warning for the MeshCoP region. - * - * @param[in] ... Arguments for the format specification. - * - */ - -/** - * @def otLogNoteMeshCoP - * - * This function generates a log with level note for the MeshCoP region. - * - * @param[in] ... Arguments for the format specification. - * - */ - -/** - * @def otLogInfoMeshCoP - * - * This function generates a log with level info for the MeshCoP region. - * - * @param[in] ... Arguments for the format specification. - * - */ - -/** - * @def otLogDebgMeshCoP - * - * This function generates a log with level debug for the MeshCoP region. - * - * @param[in] ... Arguments for the format specification. - * - */ -#if OPENTHREAD_CONFIG_LOG_MESHCOP -#define otLogCritMeshCoP(...) otLogCrit(OT_LOG_REGION_MESH_COP, __VA_ARGS__) -#define otLogWarnMeshCoP(...) otLogWarn(OT_LOG_REGION_MESH_COP, __VA_ARGS__) -#define otLogNoteMeshCoP(...) otLogNote(OT_LOG_REGION_MESH_COP, __VA_ARGS__) -#define otLogInfoMeshCoP(...) otLogInfo(OT_LOG_REGION_MESH_COP, __VA_ARGS__) -#define otLogDebgMeshCoP(...) otLogDebg(OT_LOG_REGION_MESH_COP, __VA_ARGS__) -#else -#define otLogCritMeshCoP(...) -#define otLogWarnMeshCoP(...) -#define otLogNoteMeshCoP(...) -#define otLogInfoMeshCoP(...) -#define otLogDebgMeshCoP(...) -#endif - -#define otLogCritMbedTls(...) otLogCritMeshCoP(__VA_ARGS__) -#define otLogWarnMbedTls(...) otLogWarnMeshCoP(__VA_ARGS__) -#define otLogNoteMbedTls(...) otLogNoteMeshCoP(__VA_ARGS__) -#define otLogInfoMbedTls(...) otLogInfoMeshCoP(__VA_ARGS__) -#define otLogDebgMbedTls(...) otLogDebgMeshCoP(__VA_ARGS__) - -/** - * @def otLogCritBr - * - * This function generates a log with level critical for the BR region. - * - * @param[in] ... Arguments for the format specification. - * - */ - -/** - * @def otLogWarnBr - * - * This function generates a log with level warning for the BR region. - * - * @param[in] ... Arguments for the format specification. - * - */ - -/** - * @def otLogNoteBr - * - * This function generates a log with level note for the BR region. - * - * @param[in] ... Arguments for the format specification. - * - */ - -/** - * @def otLogInfoBr - * - * This function generates a log with level info for the BR region. - * - * @param[in] ... Arguments for the format specification. - * - */ - -/** - * @def otLogDebgBr - * - * This function generates a log with level debug for the BR region. - * - * @param[in] ... Arguments for the format specification. - * - */ -#if OPENTHREAD_CONFIG_LOG_BR -#define otLogCritBr(...) otLogCrit(OT_LOG_REGION_BR, __VA_ARGS__) -#define otLogWarnBr(...) otLogWarn(OT_LOG_REGION_BR, __VA_ARGS__) -#define otLogNoteBr(...) otLogNote(OT_LOG_REGION_BR, __VA_ARGS__) -#define otLogInfoBr(...) otLogInfo(OT_LOG_REGION_BR, __VA_ARGS__) -#define otLogDebgBr(...) otLogDebg(OT_LOG_REGION_BR, __VA_ARGS__) -#else -#define otLogCritBr(...) -#define otLogWarnBr(...) -#define otLogNoteBr(...) -#define otLogInfoBr(...) -#define otLogDebgBr(...) -#endif - -/** - * @def otLogCritMle - * - * This function generates a log with level critical for the MLE region. - * - * @param[in] ... Arguments for the format specification. - * - */ - -/** - * @def otLogWarnMle - * - * This function generates a log with level warning for the MLE region. - * - * @param[in] ... Arguments for the format specification. - * - */ - -/** - * @def otLogNoteMle - * - * This function generates a log with level note for the MLE region. - * - * @param[in] ... Arguments for the format specification. - * - */ - -/** - * @def otLogInfoMle - * - * This function generates a log with level info for the MLE region. - * - * @param[in] ... Arguments for the format specification. - * - */ - -/** - * @def otLogDebgMle - * - * This function generates a log with level debug for the MLE region. - * - * @param[in] ... Arguments for the format specification. - * - * - */ -#if OPENTHREAD_CONFIG_LOG_MLE -#define otLogCritMle(...) otLogCrit(OT_LOG_REGION_MLE, __VA_ARGS__) -#define otLogWarnMle(...) otLogWarn(OT_LOG_REGION_MLE, __VA_ARGS__) -#define otLogNoteMle(...) otLogNote(OT_LOG_REGION_MLE, __VA_ARGS__) -#define otLogInfoMle(...) otLogInfo(OT_LOG_REGION_MLE, __VA_ARGS__) -#define otLogDebgMle(...) otLogDebg(OT_LOG_REGION_MLE, __VA_ARGS__) -#else -#define otLogCritMle(...) -#define otLogWarnMle(...) -#define otLogNoteMle(...) -#define otLogInfoMle(...) -#define otLogDebgMle(...) -#endif - -/** - * @def otLogCritArp - * - * This function generates a log with level critical for the EID-to-RLOC mapping region. - * - * @param[in] ... Arguments for the format specification. - * - */ - -/** - * @def otLogWarnArp - * - * This function generates a log with level warning for the EID-to-RLOC mapping region. - * - * @param[in] ... Arguments for the format specification. - * - */ - -/** - * @def otLogNoteArp - * - * This function generates a log with level note for the EID-to-RLOC mapping region. - * - * @param[in] ... Arguments for the format specification. - * - */ - -/** - * @def otLogInfoArp - * - * This function generates a log with level info for the EID-to-RLOC mapping region. - * - * @param[in] ... Arguments for the format specification. - * - */ - -/** - * @def otLogDebgArp - * - * This function generates a log with level debug for the EID-to-RLOC mapping region. - * - * @param[in] ... Arguments for the format specification. - * - */ -#if OPENTHREAD_CONFIG_LOG_ARP -#define otLogCritArp(...) otLogCrit(OT_LOG_REGION_ARP, __VA_ARGS__) -#define otLogWarnArp(...) otLogWarn(OT_LOG_REGION_ARP, __VA_ARGS__) -#define otLogNoteArp(...) otLogNote(OT_LOG_REGION_ARP, __VA_ARGS__) -#define otLogInfoArp(...) otLogInfo(OT_LOG_REGION_ARP, __VA_ARGS__) -#define otLogDebgArp(...) otLogDebg(OT_LOG_REGION_ARP, __VA_ARGS__) -#else -#define otLogCritArp(...) -#define otLogWarnArp(...) -#define otLogNoteArp(...) -#define otLogInfoArp(...) -#define otLogDebgArp(...) -#endif - -/** - * @def otLogCritBbr - * - * This function generates a log with level critical for the Backbone Router (BBR) region. - * - * @param[in] ... Arguments for the format specification. - * - */ - -/** - * @def otLogWarnBbr - * - * This function generates a log with level warning for the Backbone Router (BBR) region. - * - * @param[in] ... Arguments for the format specification. - * - */ - -/** - * @def otLogNoteBbr - * - * This function generates a log with level note for the Backbone Router (BBR) region. - * - * @param[in] ... Arguments for the format specification. - * - */ - -/** - * @def otLogInfoBbr - * - * This function generates a log with level info for the Backbone Router (BBR) region. - * - * @param[in] ... Arguments for the format specification. - * - */ - -/** - * @def otLogDebgBbr - * - * This function generates a log with level debug for the Backbone Router (BBR) region. - * - * @param[in] ... Arguments for the format specification. - * - */ -#if OPENTHREAD_CONFIG_LOG_BBR -#define otLogCritBbr(...) otLogCrit(OT_LOG_REGION_BBR, __VA_ARGS__) -#define otLogWarnBbr(...) otLogWarn(OT_LOG_REGION_BBR, __VA_ARGS__) -#define otLogNoteBbr(...) otLogNote(OT_LOG_REGION_BBR, __VA_ARGS__) -#define otLogInfoBbr(...) otLogInfo(OT_LOG_REGION_BBR, __VA_ARGS__) -#define otLogDebgBbr(...) otLogDebg(OT_LOG_REGION_BBR, __VA_ARGS__) -#else -#define otLogCritBbr(...) -#define otLogWarnBbr(...) -#define otLogNoteBbr(...) -#define otLogInfoBbr(...) -#define otLogDebgBbr(...) -#endif - -/** - * @def otLogCritMlr - * - * This function generates a log with level critical for the Multicast Listener Registration (MLR) region. - * - * @param[in] ... Arguments for the format specification. - * - */ - -/** - * @def otLogWarnMlr - * - * This function generates a log with level warning for the Multicast Listener Registration (MLR) region. - * - * @param[in] ... Arguments for the format specification. - * - */ - -/** - * @def otLogNoteMlr - * - * This function generates a log with level note for the Multicast Listener Registration (MLR) region. - * - * @param[in] ... Arguments for the format specification. - * - */ - -/** - * @def otLogInfoMlr - * - * This function generates a log with level info for the Multicast Listener Registration (MLR) region. - * - * @param[in] ... Arguments for the format specification. - * - */ - -/** - * @def otLogDebgMlr - * - * This function generates a log with level debug for the Multicast Listener Registration (MLR) region. - * - * @param[in] ... Arguments for the format specification. - * - */ -#if OPENTHREAD_CONFIG_LOG_MLR -#define otLogCritMlr(...) otLogCrit(OT_LOG_REGION_MLR, __VA_ARGS__) -#define otLogWarnMlr(...) otLogWarn(OT_LOG_REGION_MLR, __VA_ARGS__) -#define otLogNoteMlr(...) otLogNote(OT_LOG_REGION_MLR, __VA_ARGS__) -#define otLogInfoMlr(...) otLogInfo(OT_LOG_REGION_MLR, __VA_ARGS__) -#define otLogDebgMlr(...) otLogDebg(OT_LOG_REGION_MLR, __VA_ARGS__) -#else -#define otLogCritMlr(...) -#define otLogWarnMlr(...) -#define otLogNoteMlr(...) -#define otLogInfoMlr(...) -#define otLogDebgMlr(...) -#endif - -/** - * @def otLogCritNetData - * - * This function generates a log with level critical for the Network Data region. - * - * @param[in] ... Arguments for the format specification. - * - */ - -/** - * @def otLogWarnNetData - * - * This function generates a log with level warning for the Network Data region. - * - * @param[in] ... Arguments for the format specification. - * - */ - -/** - * @def otLogNoteNetData - * - * This function generates a log with level note for the Network Data region. - * - * @param[in] ... Arguments for the format specification. - * - */ - -/** - * @def otLogInfoNetData - * - * This function generates a log with level info for the Network Data region. - * - * @param[in] ... Arguments for the format specification. - * - */ - -/** - * @def otLogDebgNetData - * - * This function generates a log with level debug for the Network Data region. - * - * @param[in] ... Arguments for the format specification. - * - */ -#if OPENTHREAD_CONFIG_LOG_NETDATA -#define otLogCritNetData(...) otLogCrit(OT_LOG_REGION_NET_DATA, __VA_ARGS__) -#define otLogWarnNetData(...) otLogWarn(OT_LOG_REGION_NET_DATA, __VA_ARGS__) -#define otLogNoteNetData(...) otLogNote(OT_LOG_REGION_NET_DATA, __VA_ARGS__) -#define otLogInfoNetData(...) otLogInfo(OT_LOG_REGION_NET_DATA, __VA_ARGS__) -#define otLogDebgNetData(...) otLogDebg(OT_LOG_REGION_NET_DATA, __VA_ARGS__) -#else -#define otLogCritNetData(...) -#define otLogWarnNetData(...) -#define otLogNoteNetData(...) -#define otLogInfoNetData(...) -#define otLogDebgNetData(...) -#endif - -/** - * @def otLogCritIcmp - * - * This function generates a log with level critical for the ICMPv6 region. - * - * @param[in] ... Arguments for the format specification. - * - */ - -/** - * @def otLogWarnIcmp - * - * This function generates a log with level warning for the ICMPv6 region. - * - * @param[in] ... Arguments for the format specification. - * - */ - -/** - * @def otLogNoteIcmp - * - * This function generates a log with level note for the ICMPv6 region. - * - * @param[in] ... Arguments for the format specification. - * - */ - -/** - * @def otLogInfoIcmp - * - * This function generates a log with level info for the ICMPv6 region. - * - * @param[in] ... Arguments for the format specification. - * - */ - -/** - * @def otLogDebgIcmp - * - * This function generates a log with level debug for the ICMPv6 region. - * - * @param[in] ... Arguments for the format specification. - * - */ -#if OPENTHREAD_CONFIG_LOG_ICMP -#define otLogCritIcmp(...) otLogCrit(OT_LOG_REGION_ICMP, __VA_ARGS__) -#define otLogWarnIcmp(...) otLogWarn(OT_LOG_REGION_ICMP, __VA_ARGS__) -#define otLogNoteIcmp(...) otLogNote(OT_LOG_REGION_ICMP, __VA_ARGS__) -#define otLogInfoIcmp(...) otLogInfo(OT_LOG_REGION_ICMP, __VA_ARGS__) -#define otLogDebgIcmp(...) otLogDebg(OT_LOG_REGION_ICMP, __VA_ARGS__) -#else -#define otLogCritIcmp(...) -#define otLogWarnIcmp(...) -#define otLogNoteIcmp(...) -#define otLogInfoIcmp(...) -#define otLogDebgIcmp(...) -#endif - -/** - * @def otLogCritIp6 - * - * This function generates a log with level critical for the IPv6 region. - * - * @param[in] ... Arguments for the format specification. - * - */ - -/** - * @def otLogWarnIp6 - * - * This function generates a log with level warning for the IPv6 region. - * - * @param[in] ... Arguments for the format specification. - * - */ - -/** - * @def otLogNoteIp6 - * - * This function generates a log with level note for the IPv6 region. - * - * @param[in] ... Arguments for the format specification. - * - */ - -/** - * @def otLogInfoIp6 - * - * This function generates a log with level info for the IPv6 region. - * - * @param[in] ... Arguments for the format specification. - * - */ - -/** - * @def otLogDebgIp6 - * - * This function generates a log with level debug for the IPv6 region. - * - * @param[in] ... Arguments for the format specification. - * - */ -#if OPENTHREAD_CONFIG_LOG_IP6 -#define otLogCritIp6(...) otLogCrit(OT_LOG_REGION_IP6, __VA_ARGS__) -#define otLogWarnIp6(...) otLogWarn(OT_LOG_REGION_IP6, __VA_ARGS__) -#define otLogNoteIp6(...) otLogNote(OT_LOG_REGION_IP6, __VA_ARGS__) -#define otLogInfoIp6(...) otLogInfo(OT_LOG_REGION_IP6, __VA_ARGS__) -#define otLogDebgIp6(...) otLogDebg(OT_LOG_REGION_IP6, __VA_ARGS__) -#else -#define otLogCritIp6(...) -#define otLogWarnIp6(...) -#define otLogNoteIp6(...) -#define otLogInfoIp6(...) -#define otLogDebgIp6(...) -#endif - -/** - * @def otLogCritTcp - * - * This function generates a log with level critical for the TCP region. - * - * @param[in] ... Arguments for the format specification. - * - */ - -/** - * @def otLogWarnTcp - * - * This function generates a log with level warning for the TCP region. - * - * @param[in] ... Arguments for the format specification. - * - */ - -/** - * @def otLogNoteTcp - * - * This function generates a log with level note for the TCP region. - * - * @param[in] ... Arguments for the format specification. - * - */ - -/** - * @def otLogInfoTcp - * - * This function generates a log with level info for the TCP region. - * - * @param[in] ... Arguments for the format specification. - * - */ - -/** - * @def otLogDebgTcp - * - * This function generates a log with level debug for the TCP region. - * - * @param[in] ... Arguments for the format specification. - * - */ -#if OPENTHREAD_CONFIG_LOG_TCP -#define otLogCritTcp(...) otLogCrit(OT_LOG_REGION_TCP, __VA_ARGS__) -#define otLogWarnTcp(...) otLogWarn(OT_LOG_REGION_TCP, __VA_ARGS__) -#define otLogNoteTcp(...) otLogNote(OT_LOG_REGION_TCP, __VA_ARGS__) -#define otLogInfoTcp(...) otLogInfo(OT_LOG_REGION_TCP, __VA_ARGS__) -#define otLogDebgTcp(...) otLogDebg(OT_LOG_REGION_TCP, __VA_ARGS__) -#else -#define otLogCritTcp(...) -#define otLogWarnTcp(...) -#define otLogNoteTcp(...) -#define otLogInfoTcp(...) -#define otLogDebgTcp(...) -#endif - -/** - * @def otLogCritMac - * - * This function generates a log with level critical for the MAC region. - * - * @param[in] ... Arguments for the format specification. - * - */ - -/** - * @def otLogWarnMac - * - * This function generates a log with level warning for the MAC region. - * - * @param[in] ... Arguments for the format specification. - * - */ - -/** - * @def otLogNoteMac - * - * This function generates a log with level note for the MAC region. - * - * @param[in] ... Arguments for the format specification. - * - */ - -/** - * @def otLogInfoMac - * - * This function generates a log with level info for the MAC region. - * - * @param[in] ... Arguments for the format specification. - * - */ - -/** - * @def otLogDebgMac - * - * This function generates a log with level debug for the MAC region. - * - * @param[in] ... Arguments for the format specification. - * - */ - -/** - * @def otLogMac - * - * This function generates a log with a given log level for the MAC region. - * - * @param[in] aLogLevel A log level. - * @param[in] aFormat A pointer to the format string. - * @param[in] ... Arguments for the format specification. - * - */ -#if OPENTHREAD_CONFIG_LOG_MAC -#define otLogCritMac(...) otLogCrit(OT_LOG_REGION_MAC, __VA_ARGS__) -#define otLogWarnMac(...) otLogWarn(OT_LOG_REGION_MAC, __VA_ARGS__) -#define otLogNoteMac(...) otLogNote(OT_LOG_REGION_MAC, __VA_ARGS__) -#define otLogInfoMac(...) otLogInfo(OT_LOG_REGION_MAC, __VA_ARGS__) -#define otLogDebgMac(...) otLogDebg(OT_LOG_REGION_MAC, __VA_ARGS__) -void otLogMac(otLogLevel aLogLevel, const char *aFormat, ...); -#else -#define otLogCritMac(...) -#define otLogWarnMac(...) -#define otLogNoteMac(...) -#define otLogInfoMac(...) -#define otLogDebgMac(...) -#define otLogMac(aLogLevel, ...) -#endif - -/** - * @def otLogCritCore - * - * This function generates a log with level critical for the Core region. - * - * @param[in] ... Arguments for the format specification. - * - */ - -/** - * @def otLogWarnCore - * - * This function generates a log with level warning for the Core region. - * - * @param[in] ... Arguments for the format specification. - * - */ - -/** - * @def otLogNoteCore - * - * This function generates a log with level note for the Core region. - * - * @param[in] ... Arguments for the format specification. - * - */ - -/** - * @def otLogInfoCore - * - * This function generates a log with level info for the Core region. - * - * @param[in] ... Arguments for the format specification. - * - */ - -/** - * @def otLogDebgCore - * - * This function generates a log with level debug for the Core region. - * - * @param[in] ... Arguments for the format specification. - * - */ -#if OPENTHREAD_CONFIG_LOG_CORE -#define otLogCritCore(...) otLogCrit(OT_LOG_REGION_CORE, __VA_ARGS__) -#define otLogWarnCore(...) otLogWarn(OT_LOG_REGION_CORE, __VA_ARGS__) -#define otLogNoteCore(...) otLogNote(OT_LOG_REGION_CORE, __VA_ARGS__) -#define otLogInfoCore(...) otLogInfo(OT_LOG_REGION_CORE, __VA_ARGS__) -#define otLogDebgCore(...) otLogDebg(OT_LOG_REGION_CORE, __VA_ARGS__) -#else -#define otLogCritCore(...) -#define otLogWarnCore(...) -#define otLogInfoCore(...) -#define otLogDebgCore(...) -#endif - -/** - * @def otLogCritMem - * - * This function generates a log with level critical for the memory region. - * - * @param[in] ... Arguments for the format specification. - * - */ - -/** - * @def otLogWarnMem - * - * This function generates a log with level warning for the memory region. - * - * @param[in] ... Arguments for the format specification. - * - */ - -/** - * @def otLogNoteMem - * - * This function generates a log with level note for the memory region. - * - * @param[in] ... Arguments for the format specification. - * - */ - -/** - * @def otLogInfoMem - * - * This function generates a log with level info for the memory region. - * - * @param[in] ... Arguments for the format specification. - * - */ - -/** - * @def otLogDebgMem - * - * This function generates a log with level debug for the memory region. - * - * @param[in] ... Arguments for the format specification. - * - */ -#if OPENTHREAD_CONFIG_LOG_MEM -#define otLogCritMem(...) otLogCrit(OT_LOG_REGION_MEM, __VA_ARGS__) -#define otLogWarnMem(...) otLogWarn(OT_LOG_REGION_MEM, __VA_ARGS__) -#define otLogNoteMem(...) otLogNote(OT_LOG_REGION_MEM, __VA_ARGS__) -#define otLogInfoMem(...) otLogInfo(OT_LOG_REGION_MEM, __VA_ARGS__) -#define otLogDebgMem(...) otLogDebg(OT_LOG_REGION_MEM, __VA_ARGS__) -#else -#define otLogCritMem(...) -#define otLogWarnMem(...) -#define otLogNoteMem(...) -#define otLogInfoMem(...) -#define otLogDebgMem(...) -#endif - -/** - * @def otLogCritUtil - * - * This function generates a log with level critical for the Util region. - * - * @param[in] ... Arguments for the format specification. - * - */ - -/** - * @def otLogWarnUtil - * - * This function generates a log with level warning for the Util region. - * - * @param[in] ... Arguments for the format specification. - * - */ - -/** - * @def otLogNoteUtil - * - * This function generates a log with level note for the Util region. - * - * @param[in] ... Arguments for the format specification. - * - */ - -/** - * @def otLogInfoUtil - * - * This function generates a log with level info for the Util region. - * - * @param[in] ... Arguments for the format specification. - * - */ - -/** - * @def otLogDebgUtil - * - * This function generates a log with level debug for the Util region. - * - * @param[in] ... Arguments for the format specification. - * - */ -#if OPENTHREAD_CONFIG_LOG_UTIL -#define otLogCritUtil(...) otLogCrit(OT_LOG_REGION_UTIL, __VA_ARGS__) -#define otLogWarnUtil(...) otLogWarn(OT_LOG_REGION_UTIL, __VA_ARGS__) -#define otLogNoteUtil(...) otLogNote(OT_LOG_REGION_UTIL, __VA_ARGS__) -#define otLogInfoUtil(...) otLogInfo(OT_LOG_REGION_UTIL, __VA_ARGS__) -#define otLogDebgUtil(...) otLogDebg(OT_LOG_REGION_UTIL, __VA_ARGS__) -#else -#define otLogCritUtil(...) -#define otLogWarnUtil(...) -#define otLogNoteUtil(...) -#define otLogInfoUtil(...) -#define otLogDebgUtil(...) -#endif - -/** - * @def otLogCritNetDiag - * - * This function generates a log with level critical for the NETDIAG region. - * - * @param[in] ... Arguments for the format specification. - * - */ - -/** - * @def otLogWarnNetDiag - * - * This function generates a log with level warning for the NETDIAG region. - * - * @param[in] ... Arguments for the format specification. - * - */ - -/** - * @def otLogNoteNetDiag - * - * This function generates a log with level note for the NETDIAG region. - * - * @param[in] ... Arguments for the format specification. - * - */ - -/** - * @def otLogInfoNetDiag - * - * This function generates a log with level info for the NETDIAG region. - * - * @param[in] ... Arguments for the format specification. - * - */ - -/** - * @def otLogDebgNetDiag - * - * This function generates a log with level debug for the NETDIAG region. - * - * @param[in] ... Arguments for the format specification. - * - */ -#if OPENTHREAD_CONFIG_LOG_NETDIAG -#define otLogCritNetDiag(...) otLogCrit(OT_LOG_REGION_NET_DIAG, __VA_ARGS__) -#define otLogWarnNetDiag(...) otLogWarn(OT_LOG_REGION_NET_DIAG, __VA_ARGS__) -#define otLogNoteNetDiag(...) otLogNote(OT_LOG_REGION_NET_DIAG, __VA_ARGS__) -#define otLogInfoNetDiag(...) otLogInfo(OT_LOG_REGION_NET_DIAG, __VA_ARGS__) -#define otLogDebgNetDiag(...) otLogDebg(OT_LOG_REGION_NET_DIAG, __VA_ARGS__) -#else -#define otLogCritNetDiag(...) -#define otLogWarnNetDiag(...) -#define otLogNoteNetDiag(...) -#define otLogInfoNetDiag(...) -#define otLogDebgNetDiag(...) -#endif - -/** - * @def otLogCert - * - * This function generates a log with level none for the certification test. - * - * @param[in] ... Arguments for the format specification. - * - * - */ -#if !OPENTHREAD_CONFIG_REFERENCE_DEVICE_ENABLE -#define otLogCertMeshCoP(...) -#else -void otLogCertMeshCoP(const char *aFormat, ...); -#endif - -/** - * @def otLogCritCli - * - * This function generates a log with level critical for the CLI region. - * - * @param[in] ... Arguments for the format specification. - * - */ - -/** - * @def otLogWarnCli - * - * This function generates a log with level warning for the CLI region. - * - * @param[in] ... Arguments for the format specification. - * - */ - -/** - * @def otLogNoteCli - * - * This function generates a log with level note for the CLI region. - * - * @param[in] ... Arguments for the format specification. - * - */ - -/** - * @def otLogInfoCli - * - * This function generates a log with level info for the CLI region. - * - * @param[in] ... Arguments for the format specification. - * - */ - -/** - * @def otLogDebgCli - * - * This function generates a log with level debug for the CLI region. - * - * @param[in] ... Arguments for the format specification. - * - */ -#if OPENTHREAD_CONFIG_LOG_CLI - -#define otLogCritCli(...) otLogCrit(OT_LOG_REGION_CLI, __VA_ARGS__) -#define otLogWarnCli(...) otLogWarn(OT_LOG_REGION_CLI, __VA_ARGS__) -#define otLogNoteCli(...) otLogNote(OT_LOG_REGION_CLI, __VA_ARGS__) -#define otLogInfoCli(...) otLogInfo(OT_LOG_REGION_CLI, __VA_ARGS__) -#define otLogDebgCli(...) otLogDebg(OT_LOG_REGION_CLI, __VA_ARGS__) -#else -#define otLogCritCli(...) -#define otLogWarnCli(...) -#define otLogNoteCli(...) -#define otLogInfoCli(...) -#define otLogDebgCli(...) -#endif - -/** - * @def otLogCritCoap - * - * This function generates a log with level critical for the CoAP region. - * - * @param[in] ... Arguments for the format specification. - * - */ - -/** - * @def otLogWarnCoap - * - * This function generates a log with level warning for the CoAP region. - * - * @param[in] ... Arguments for the format specification. - * - */ - -/** - * @def otLogNoteCoap - * - * This function generates a log with level note for the CoAP region. - * - * @param[in] ... Arguments for the format specification. - * - */ - -/** - * @def otLogInfoCoap - * - * This function generates a log with level info for the CoAP region. - * - * @param[in] ... Arguments for the format specification. - * - */ - -/** - * @def otLogDebgCoap - * - * This function generates a log with level debug for the CoAP region. - * - * @param[in] ... Arguments for the format specification. - * - */ -#if OPENTHREAD_CONFIG_LOG_COAP -#define otLogCritCoap(...) otLogCrit(OT_LOG_REGION_COAP, __VA_ARGS__) -#define otLogWarnCoap(...) otLogWarn(OT_LOG_REGION_COAP, __VA_ARGS__) -#define otLogNoteCoap(...) otLogNote(OT_LOG_REGION_COAP, __VA_ARGS__) -#define otLogInfoCoap(...) otLogInfo(OT_LOG_REGION_COAP, __VA_ARGS__) -#define otLogDebgCoap(...) otLogDebg(OT_LOG_REGION_COAP, __VA_ARGS__) -#else -#define otLogCritCoap(...) -#define otLogWarnCoap(...) -#define otLogNoteCoap(...) -#define otLogInfoCoap(...) -#define otLogDebgCoap(...) -#endif - -/** - * @def otLogCritDua - * - * This function generates a log with level critical for the Domain Unicast Address region. - * - * @param[in] ... Arguments for the format specification. - * - */ - -/** - * @def otLogWarnDua - * - * This function generates a log with level warning for the Domain Unicast Address region. - * - * @param[in] ... Arguments for the format specification. - * - */ - -/** - * @def otLogNoteDua - * - * This function generates a log with level note for the Domain Unicast Address region. - * - * @param[in] ... Arguments for the format specification. - * - */ - -/** - * @def otLogInfoDua - * - * This function generates a log with level info for the Domain Unicast Address region. - * - * @param[in] ... Arguments for the format specification. - * - */ - -/** - * @def otLogDebgDua - * - * This function generates a log with level debug for the Domain Unicast Address region. - * - * @param[in] ... Arguments for the format specification. - * - */ -#if OPENTHREAD_CONFIG_LOG_DUA -#define otLogCritDua(...) otLogCrit(OT_LOG_REGION_DUA, __VA_ARGS__) -#define otLogWarnDua(...) otLogWarn(OT_LOG_REGION_DUA, __VA_ARGS__) -#define otLogNoteDua(...) otLogNote(OT_LOG_REGION_DUA, __VA_ARGS__) -#define otLogInfoDua(...) otLogInfo(OT_LOG_REGION_DUA, __VA_ARGS__) -#define otLogDebgDua(...) otLogDebg(OT_LOG_REGION_DUA, __VA_ARGS__) -#else -#define otLogCritDua(...) -#define otLogWarnDua(...) -#define otLogNoteDua(...) -#define otLogInfoDua(...) -#define otLogDebgDua(...) -#endif - -/** - * @def otLogCritSrp - * - * This function generates a log with level critical for the Service Registration Protocol (SRP) region. - * - * @param[in] ... Arguments for the format specification. - * - */ - -/** - * @def otLogWarnSrp - * - * This function generates a log with level warning for the Service Registration Protocol (SRP) region. - * - * @param[in] ... Arguments for the format specification. - * - */ - -/** - * @def otLogNoteSrp - * - * This function generates a log with level note for the Service Registration Protocol (SRP) region. - * - * @param[in] ... Arguments for the format specification. - * - */ - -/** - * @def otLogInfoSrp - * - * This function generates a log with level info for the Service Registration Protocol (SRP) region. - * - * @param[in] ... Arguments for the format specification. - * - */ - -/** - * @def otLogDebgSrp - * - * This function generates a log with level debug for the Service Registration Protocol (SRP) region. - * - * @param[in] ... Arguments for the format specification. - * - */ -#if OPENTHREAD_CONFIG_LOG_SRP -#define otLogCritSrp(...) otLogCrit(OT_LOG_REGION_SRP, __VA_ARGS__) -#define otLogWarnSrp(...) otLogWarn(OT_LOG_REGION_SRP, __VA_ARGS__) -#define otLogNoteSrp(...) otLogNote(OT_LOG_REGION_SRP, __VA_ARGS__) -#define otLogInfoSrp(...) otLogInfo(OT_LOG_REGION_SRP, __VA_ARGS__) -#define otLogDebgSrp(...) otLogDebg(OT_LOG_REGION_SRP, __VA_ARGS__) -#else -#define otLogCritSrp(...) -#define otLogWarnSrp(...) -#define otLogNoteSrp(...) -#define otLogInfoSrp(...) -#define otLogDebgSrp(...) -#endif - -/** - * @def otLogCritDns - * - * This function generates a log with level critical for the DNS region. - * - * @param[in] ... Arguments for the format specification. - * - */ - -/** - * @def otLogWarnDns - * - * This function generates a log with level warning for the DNS region. - * - * @param[in] ... Arguments for the format specification. - * - */ - -/** - * @def otLogNoteDns - * - * This function generates a log with level note for the DNS region. - * - * @param[in] ... Arguments for the format specification. - * - */ - -/** - * @def otLogInfoDns - * - * This function generates a log with level info for the DNS region. - * - * @param[in] ... Arguments for the format specification. - * - */ - -/** - * @def otLogDebgDns - * - * This function generates a log with level debug for the DNS region. - * - * @param[in] ... Arguments for the format specification. - * - */ -#if OPENTHREAD_CONFIG_LOG_DNS -#define otLogCritDns(...) otLogCrit(OT_LOG_REGION_DNS, __VA_ARGS__) -#define otLogWarnDns(...) otLogWarn(OT_LOG_REGION_DNS, __VA_ARGS__) -#define otLogNoteDns(...) otLogNote(OT_LOG_REGION_DNS, __VA_ARGS__) -#define otLogInfoDns(...) otLogInfo(OT_LOG_REGION_DNS, __VA_ARGS__) -#define otLogDebgDns(...) otLogDebg(OT_LOG_REGION_DNS, __VA_ARGS__) -#else -#define otLogCritDns(...) -#define otLogWarnDns(...) -#define otLogNoteDns(...) -#define otLogInfoDns(...) -#define otLogDebgDns(...) -#endif - -/** - * @def otLogCritPlat - * - * This function generates a log with level critical for the Platform region. - * - * @param[in] ... Arguments for the format specification. - * - */ - -/** - * @def otLogWarnPlat - * - * This function generates a log with level warning for the Platform region. - * - * @param[in] ... Arguments for the format specification. - * - */ - -/** - * @def otLogNotePlat - * - * This function generates a log with level note for the Platform region. - * - * @param[in] ... Arguments for the format specification. - * - */ - -/** - * @def otLogInfoPlat - * - * This function generates a log with level info for the Platform region. - * - * @param[in] ... Arguments for the format specification. - * - */ - -/** - * @def otLogDebgPlat - * - * This function generates a log with level debug for the Platform region. - * - * @param[in] ... Arguments for the format specification. - * - */ -#if OPENTHREAD_CONFIG_LOG_PLATFORM -#define otLogCritPlat(...) otLogCrit(OT_LOG_REGION_PLATFORM, __VA_ARGS__) -#define otLogWarnPlat(...) otLogWarn(OT_LOG_REGION_PLATFORM, __VA_ARGS__) -#define otLogNotePlat(...) otLogNote(OT_LOG_REGION_PLATFORM, __VA_ARGS__) -#define otLogInfoPlat(...) otLogInfo(OT_LOG_REGION_PLATFORM, __VA_ARGS__) -#define otLogDebgPlat(...) otLogDebg(OT_LOG_REGION_PLATFORM, __VA_ARGS__) -#else -#define otLogCritPlat(...) -#define otLogWarnPlat(...) -#define otLogNotePlat(...) -#define otLogInfoPlat(...) -#define otLogDebgPlat(...) -#endif - -/** - * @def otLogOtns - * - * This function generates a log with level none for the Core region, - * and is specifically for OTNS visualization use. - * - * @param[in] ... Arguments for the format specification. - * - */ -#if OPENTHREAD_CONFIG_OTNS_ENABLE -void otLogOtns(const char *aFormat, ...); -#endif - -/** - * @def otDumpCrit - * - * This function generates a memory dump with log level critical. - * - * @param[in] aRegion The log region. - * @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes. - * @param[in] aBuf A pointer to the buffer. - * @param[in] aLength Number of bytes to print. - * - */ -#if OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_CRIT -#define otDumpCrit(aRegion, aId, aBuf, aLength) otDump(OT_LOG_LEVEL_CRIT, aRegion, aId, aBuf, aLength) -#else -#define otDumpCrit(aRegion, aId, aBuf, aLength) -#endif - -/** - * @def otDumpWarn - * - * This function generates a memory dump with log level warning. - * - * @param[in] aRegion The log region. - * @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes. - * @param[in] aBuf A pointer to the buffer. - * @param[in] aLength Number of bytes to print. - * - */ -#if OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_WARN -#define otDumpWarn(aRegion, aId, aBuf, aLength) otDump(OT_LOG_LEVEL_WARN, aRegion, aId, aBuf, aLength) -#else -#define otDumpWarn(aRegion, aId, aBuf, aLength) -#endif - -/** - * @def otDumpNote - * - * This function generates a memory dump with log level note. - * - * @param[in] aRegion The log region. - * @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes. - * @param[in] aBuf A pointer to the buffer. - * @param[in] aLength Number of bytes to print. - * - */ -#if OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_NOTE -#define otDumpNote(aRegion, aId, aBuf, aLength) otDump(OT_LOG_LEVEL_NOTE, aRegion, aId, aBuf, aLength) -#else -#define otDumpNote(aRegion, aId, aBuf, aLength) -#endif - -/** - * @def otDumpInfo - * - * This function generates a memory dump with log level info. - * - * @param[in] aRegion The log region. - * @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes. - * @param[in] aBuf A pointer to the buffer. - * @param[in] aLength Number of bytes to print. - * - */ -#if OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO -#define otDumpInfo(aRegion, aId, aBuf, aLength) otDump(OT_LOG_LEVEL_INFO, aRegion, aId, aBuf, aLength) -#else -#define otDumpInfo(aRegion, aId, aBuf, aLength) -#endif - -/** - * @def otDumpDebg - * - * This function generates a memory dump with log level debug. - * - * @param[in] aRegion The log region. - * @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes. - * @param[in] aBuf A pointer to the buffer. - * @param[in] aLength Number of bytes to print. - * - */ -#if OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_DEBG -#define otDumpDebg(aRegion, aId, aBuf, aLength) otDump(OT_LOG_LEVEL_DEBG, aRegion, aId, aBuf, aLength) -#else -#define otDumpDebg(aRegion, aId, aBuf, aLength) -#endif - -/** - * @def otDumpCritNetData - * - * This function generates a memory dump with log level debug and region Network Data. - * - * @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes. - * @param[in] aBuf A pointer to the buffer. - * @param[in] aLength Number of bytes to print. - * - */ - -/** - * @def otDumpWarnNetData - * - * This function generates a memory dump with log level warning and region Network Data. - * - * @param[in] aBuf A pointer to the buffer. - * @param[in] aLength Number of bytes to print. - * - */ - -/** - * @def otDumpNoteNetData - * - * @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes. - * @param[in] aBuf A pointer to the buffer. - * @param[in] aLength Number of bytes to print. - * - */ - -/** - * @def otDumpInfoNetData - * - * @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes. - * @param[in] aBuf A pointer to the buffer. - * @param[in] aLength Number of bytes to print. - * - */ - -/** - * @def otDumpDebgNetData - * - * This function generates a memory dump with log level debug and region Network Data. - * - * @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes. - * @param[in] aBuf A pointer to the buffer. - * @param[in] aLength Number of bytes to print. - * - */ -#if OPENTHREAD_CONFIG_LOG_NETDATA -#define otDumpCritNetData(aId, aBuf, aLength) otDumpCrit(OT_LOG_REGION_NET_DATA, aId, aBuf, aLength) -#define otDumpWarnNetData(aId, aBuf, aLength) otDumpWarn(OT_LOG_REGION_NET_DATA, aId, aBuf, aLength) -#define otDumpNoteNetData(aId, aBuf, aLength) otDumpNote(OT_LOG_REGION_NET_DATA, aId, aBuf, aLength) -#define otDumpInfoNetData(aId, aBuf, aLength) otDumpInfo(OT_LOG_REGION_NET_DATA, aId, aBuf, aLength) -#define otDumpDebgNetData(aId, aBuf, aLength) otDumpDebg(OT_LOG_REGION_NET_DATA, aId, aBuf, aLength) -#else -#define otDumpCritNetData(aId, aBuf, aLength) -#define otDumpWarnNetData(aId, aBuf, aLength) -#define otDumpNoteNetData(aId, aBuf, aLength) -#define otDumpInfoNetData(aId, aBuf, aLength) -#define otDumpDebgNetData(aId, aBuf, aLength) -#endif - -/** - * @def otDumpCritMle - * - * This function generates a memory dump with log level debug and region MLE. - * - * @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes. - * @param[in] aBuf A pointer to the buffer. - * @param[in] aLength Number of bytes to print. - * - */ - -/** - * @def otDumpWarnMle - * - * This function generates a memory dump with log level warning and region MLE. - * - * @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes. - * @param[in] aBuf A pointer to the buffer. - * @param[in] aLength Number of bytes to print. - * - */ - -/** - * @def otDumpNoteMle - * - * This function generates a memory dump with log level note and region MLE. - * - * @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes. - * @param[in] aBuf A pointer to the buffer. - * @param[in] aLength Number of bytes to print. - * - */ - -/** - * @def otDumpInfoMle - * - * This function generates a memory dump with log level info and region MLE. - * - * @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes. - * @param[in] aBuf A pointer to the buffer. - * @param[in] aLength Number of bytes to print. - * - */ - -/** - * @def otDumpDebgMle - * - * This function generates a memory dump with log level debug and region MLE. - * - * @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes. - * @param[in] aBuf A pointer to the buffer. - * @param[in] aLength Number of bytes to print. - * - */ -#if OPENTHREAD_CONFIG_LOG_MLE -#define otDumpCritMle(aId, aBuf, aLength) otDumpCrit(OT_LOG_REGION_MLE, aId, aBuf, aLength) -#define otDumpWarnMle(aId, aBuf, aLength) otDumpWarn(OT_LOG_REGION_MLE, aId, aBuf, aLength) -#define otDumpNoteMle(aId, aBuf, aLength) otDumpNote(OT_LOG_REGION_MLE, aId, aBuf, aLength) -#define otDumpInfoMle(aId, aBuf, aLength) otDumpInfo(OT_LOG_REGION_MLE, aId, aBuf, aLength) -#define otDumpDebgMle(aId, aBuf, aLength) otDumpDebg(OT_LOG_REGION_MLE, aId, aBuf, aLength) -#else -#define otDumpCritMle(aId, aBuf, aLength) -#define otDumpWarnMle(aId, aBuf, aLength) -#define otDumpNoteMle(aId, aBuf, aLength) -#define otDumpInfoMle(aId, aBuf, aLength) -#define otDumpDebgMle(aId, aBuf, aLength) -#endif - -/** - * @def otDumpCritArp - * - * This function generates a memory dump with log level debug and region EID-to-RLOC mapping. - * - * @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes. - * @param[in] aBuf A pointer to the buffer. - * @param[in] aLength Number of bytes to print. - * - */ - -/** - * @def otDumpWarnArp - * - * This function generates a memory dump with log level warning and region EID-to-RLOC mapping. - * - * @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes. - * @param[in] aBuf A pointer to the buffer. - * @param[in] aLength Number of bytes to print. - * - */ - -/** - * @def otDumpNoteArp - * - * This function generates a memory dump with log level note and region EID-to-RLOC mapping. - * - * @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes. - * @param[in] aBuf A pointer to the buffer. - * @param[in] aLength Number of bytes to print. - * - */ - -/** - * @def otDumpInfoArp - * - * This function generates a memory dump with log level info and region EID-to-RLOC mapping. - * - * @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes. - * @param[in] aBuf A pointer to the buffer. - * @param[in] aLength Number of bytes to print. - * - */ - -/** - * @def otDumpDebgArp - * - * This function generates a memory dump with log level debug and region EID-to-RLOC mapping. - * - * @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes. - * @param[in] aBuf A pointer to the buffer. - * @param[in] aLength Number of bytes to print. - * - */ -#if OPENTHREAD_CONFIG_LOG_ARP -#define otDumpCritArp(aId, aBuf, aLength) otDumpCrit(OT_LOG_REGION_ARP, aId, aBuf, aLength) -#define otDumpWarnArp(aId, aBuf, aLength) otDumpWarn(OT_LOG_REGION_ARP, aId, aBuf, aLength) -#define otDumpNoteArp(aId, aBuf, aLength) otDumpNote(OT_LOG_REGION_ARP, aId, aBuf, aLength) -#define otDumpInfoArp(aId, aBuf, aLength) otDumpInfo(OT_LOG_REGION_ARP, aId, aBuf, aLength) -#define otDumpDebgArp(aId, aBuf, aLength) otDumpDebg(OT_LOG_REGION_ARP, aId, aBuf, aLength) -#else -#define otDumpCritArp(aId, aBuf, aLength) -#define otDumpWarnArp(aId, aBuf, aLength) -#define otDumpNoteArp(aId, aBuf, aLength) -#define otDumpInfoArp(aId, aBuf, aLength) -#define otDumpDebgArp(aId, aBuf, aLength) -#endif - -/** - * @def otDumpCritBbr - * - * This function generates a memory dump with log level critical and region Backbone Router (BBR). - * - * @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes. - * @param[in] aBuf A pointer to the buffer. - * @param[in] aLength Number of bytes to print. - * - */ - -/** - * @def otDumpWarnBbr - * - * This function generates a memory dump with log level warning and region Backbone Router (BBR). - * - * @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes. - * @param[in] aBuf A pointer to the buffer. - * @param[in] aLength Number of bytes to print. - * - */ - -/** - * @def otDumpNoteBbr - * - * This function generates a memory dump with log level note and region Backbone Router (BBR). - * - * @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes. - * @param[in] aBuf A pointer to the buffer. - * @param[in] aLength Number of bytes to print. - * - */ - -/** - * @def otDumpInfoBbr - * - * This function generates a memory dump with log level info and region Backbone Router (BBR). - * - * @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes. - * @param[in] aBuf A pointer to the buffer. - * @param[in] aLength Number of bytes to print. - * - */ - -/** - * @def otDumpDebgBbr - * - * This function generates a memory dump with log level debug and region Backbone Router (BBR). - * - * @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes. - * @param[in] aBuf A pointer to the buffer. - * @param[in] aLength Number of bytes to print. - * - */ -#if OPENTHREAD_CONFIG_LOG_BBR -#define otDumpCritBbr(aId, aBuf, aLength) otDumpCrit(OT_LOG_REGION_BBR, aId, aBuf, aLength) -#define otDumpWarnBbr(aId, aBuf, aLength) otDumpWarn(OT_LOG_REGION_BBR, aId, aBuf, aLength) -#define otDumpNoteBbr(aId, aBuf, aLength) otDumpNote(OT_LOG_REGION_BBR, aId, aBuf, aLength) -#define otDumpInfoBbr(aId, aBuf, aLength) otDumpInfo(OT_LOG_REGION_BBR, aId, aBuf, aLength) -#define otDumpDebgBbr(aId, aBuf, aLength) otDumpDebg(OT_LOG_REGION_BBR, aId, aBuf, aLength) -#else -#define otDumpCritBbr(aId, aBuf, aLength) -#define otDumpWarnBbr(aId, aBuf, aLength) -#define otDumpNoteBbr(aId, aBuf, aLength) -#define otDumpInfoBbr(aId, aBuf, aLength) -#define otDumpDebgBbr(aId, aBuf, aLength) -#endif - -/** - * @def otDumpCritMlr - * - * This function generates a memory dump with log level critical and region Multicast Listener Registration (MLR). - * - * @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes. - * @param[in] aBuf A pointer to the buffer. - * @param[in] aLength Number of bytes to print. - * - */ - -/** - * @def otDumpWarnMlr - * - * This function generates a memory dump with log level warning and region Multicast Listener Registration (MLR). - * - * @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes. - * @param[in] aBuf A pointer to the buffer. - * @param[in] aLength Number of bytes to print. - * - */ - -/** - * @def otDumpNoteMlr - * - * This function generates a memory dump with log level note and region Multicast Listener Registration (MLR). - * - * @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes. - * @param[in] aBuf A pointer to the buffer. - * @param[in] aLength Number of bytes to print. - * - */ - -/** - * @def otDumpInfoMlr - * - * This function generates a memory dump with log level info and region Multicast Listener Registration (MLR). - * - * @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes. - * @param[in] aBuf A pointer to the buffer. - * @param[in] aLength Number of bytes to print. - * - */ - -/** - * @def otDumpDebgMlr - * - * This function generates a memory dump with log level debug and region Multicast Listener Registration (MLR). - * - * @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes. - * @param[in] aBuf A pointer to the buffer. - * @param[in] aLength Number of bytes to print. - * - */ -#if OPENTHREAD_CONFIG_LOG_MLR -#define otDumpCritMlr(aId, aBuf, aLength) otDumpCrit(OT_LOG_REGION_MLR, aId, aBuf, aLength) -#define otDumpWarnMlr(aId, aBuf, aLength) otDumpWarn(OT_LOG_REGION_MLR, aId, aBuf, aLength) -#define otDumpNoteMlr(aId, aBuf, aLength) otDumpNote(OT_LOG_REGION_MLR, aId, aBuf, aLength) -#define otDumpInfoMlr(aId, aBuf, aLength) otDumpInfo(OT_LOG_REGION_MLR, aId, aBuf, aLength) -#define otDumpDebgMlr(aId, aBuf, aLength) otDumpDebg(OT_LOG_REGION_MLR, aId, aBuf, aLength) -#else -#define otDumpCritMlr(aId, aBuf, aLength) -#define otDumpWarnMlr(aId, aBuf, aLength) -#define otDumpNoteMlr(aId, aBuf, aLength) -#define otDumpInfoMlr(aId, aBuf, aLength) -#define otDumpDebgMlr(aId, aBuf, aLength) -#endif - -/** - * @def otDumpCritIcmp - * - * This function generates a memory dump with log level debug and region ICMPv6. - * - * @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes. - * @param[in] aBuf A pointer to the buffer. - * @param[in] aLength Number of bytes to print. - * - */ - -/** - * @def otDumpWarnIcmp - * - * This function generates a memory dump with log level warning and region ICMPv6. - * - * @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes. - * @param[in] aBuf A pointer to the buffer. - * @param[in] aLength Number of bytes to print. - * - */ - -/** - * @def otDumpNoteIcmp - * - * This function generates a memory dump with log level note and region ICMPv6. - * - * @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes. - * @param[in] aBuf A pointer to the buffer. - * @param[in] aLength Number of bytes to print. - * - */ - -/** - * @def otDumpInfoIcmp - * - * This function generates a memory dump with log level info and region ICMPv6. - * - * @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes. - * @param[in] aBuf A pointer to the buffer. - * @param[in] aLength Number of bytes to print. - * - */ - -/** - * @def otDumpDebgIcmp - * - * This function generates a memory dump with log level debug and region ICMPv6. - * - * @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes. - * @param[in] aBuf A pointer to the buffer. - * @param[in] aLength Number of bytes to print. - * - */ -#if OPENTHREAD_CONFIG_LOG_ICMP -#define otDumpCritIcmp(aId, aBuf, aLength) otDumpCrit(OT_LOG_REGION_ICMP, aId, aBuf, aLength) -#define otDumpWarnIcmp(aId, aBuf, aLength) otDumpWarn(OT_LOG_REGION_ICMP, aId, aBuf, aLength) -#define otDumpNoteIcmp(aId, aBuf, aLength) otDumpNote(OT_LOG_REGION_ICMP, aId, aBuf, aLength) -#define otDumpInfoIcmp(aId, aBuf, aLength) otDumpInfo(OT_LOG_REGION_ICMP, aId, aBuf, aLength) -#define otDumpDebgIcmp(aId, aBuf, aLength) otDumpDebg(OT_LOG_REGION_ICMP, aId, aBuf, aLength) -#else -#define otDumpCritIcmp(aId, aBuf, aLength) -#define otDumpWarnIcmp(aId, aBuf, aLength) -#define otDumpNoteIcmp(aId, aBuf, aLength) -#define otDumpInfoIcmp(aId, aBuf, aLength) -#define otDumpDebgIcmp(aId, aBuf, aLength) -#endif - -/** - * @def otDumpCritIp6 - * - * This function generates a memory dump with log level debug and region IPv6. - * - * @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes. - * @param[in] aBuf A pointer to the buffer. - * @param[in] aLength Number of bytes to print. - * - */ - -/** - * @def otDumpWarnIp6 - * - * This function generates a memory dump with log level warning and region IPv6. - * - * @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes. - * @param[in] aBuf A pointer to the buffer. - * @param[in] aLength Number of bytes to print. - * - */ - -/** - * @def otDumpNoteIp6 - * - * This function generates a memory dump with log level note and region IPv6. - * - * @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes. - * @param[in] aBuf A pointer to the buffer. - * @param[in] aLength Number of bytes to print. - * - */ - -/** - * @def otDumpInfoIp6 - * - * This function generates a memory dump with log level info and region IPv6. - * - * @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes. - * @param[in] aBuf A pointer to the buffer. - * @param[in] aLength Number of bytes to print. - * - */ - -/** - * @def otDumpDebgIp6 - * - * This function generates a memory dump with log level debug and region IPv6. - * - * @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes. - * @param[in] aBuf A pointer to the buffer. - * @param[in] aLength Number of bytes to print. - * - */ -#if OPENTHREAD_CONFIG_LOG_IP6 -#define otDumpCritIp6(aId, aBuf, aLength) otDumpCrit(OT_LOG_REGION_IP6, aId, aBuf, aLength) -#define otDumpWarnIp6(aId, aBuf, aLength) otDumpWarn(OT_LOG_REGION_IP6, aId, aBuf, aLength) -#define otDumpNoteIp6(aId, aBuf, aLength) otDumpNote(OT_LOG_REGION_IP6, aId, aBuf, aLength) -#define otDumpInfoIp6(aId, aBuf, aLength) otDumpInfo(OT_LOG_REGION_IP6, aId, aBuf, aLength) -#define otDumpDebgIp6(aId, aBuf, aLength) otDumpDebg(OT_LOG_REGION_IP6, aId, aBuf, aLength) -#else -#define otDumpCritIp6(aId, aBuf, aLength) -#define otDumpWarnIp6(aId, aBuf, aLength) -#define otDumpNoteIp6(aId, aBuf, aLength) -#define otDumpInfoIp6(aId, aBuf, aLength) -#define otDumpDebgIp6(aId, aBuf, aLength) -#endif - -/** - * @def otDumpCritTcp - * - * This function generates a memory dump with log level debug and region TCP. - * - * @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes. - * @param[in] aBuf A pointer to the buffer. - * @param[in] aLength Number of bytes to print. - * - */ - -/** - * @def otDumpWartTcp - * - * This function generates a memory dump with log level warning and region TCP. - * - * @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes. - * @param[in] aBuf A pointer to the buffer. - * @param[in] aLength Number of bytes to print. - * - */ - -/** - * @def otDumpNottTcp - * - * This function generates a memory dump with log level note and region TCP. - * - * @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes. - * @param[in] aBuf A pointer to the buffer. - * @param[in] aLength Number of bytes to print. - * - */ - -/** - * @def otDumpInftTcp - * - * This function generates a memory dump with log level info and region TCP. - * - * @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes. - * @param[in] aBuf A pointer to the buffer. - * @param[in] aLength Number of bytes to print. - * - */ - -/** - * @def otDumpDebtTcp - * - * This function generates a memory dump with log level debug and region TCP. - * - * @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes. - * @param[in] aBuf A pointer to the buffer. - * @param[in] aLength Number of bytes to print. - * - */ -#if OPENTHREAD_CONFIG_LOG_TCP -#define otDumpCritTcp(aId, aBuf, aLength) otDumpCrit(OT_LOG_REGION_TCP, aId, aBuf, aLength) -#define otDumpWarnTcp(aId, aBuf, aLength) otDumpWarn(OT_LOG_REGION_TCP, aId, aBuf, aLength) -#define otDumpNoteTcp(aId, aBuf, aLength) otDumpNote(OT_LOG_REGION_TCP, aId, aBuf, aLength) -#define otDumpInfoTcp(aId, aBuf, aLength) otDumpInfo(OT_LOG_REGION_TCP, aId, aBuf, aLength) -#define otDumpDebgTcp(aId, aBuf, aLength) otDumpDebg(OT_LOG_REGION_TCP, aId, aBuf, aLength) -#else -#define otDumpCritTcp(aId, aBuf, aLength) -#define otDumpWarnTcp(aId, aBuf, aLength) -#define otDumpNoteTcp(aId, aBuf, aLength) -#define otDumpInfoTcp(aId, aBuf, aLength) -#define otDumpDebgTcp(aId, aBuf, aLength) -#endif - -/** - * @def otDumpCritMac - * - * This function generates a memory dump with log level debug and region MAC. - * - * @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes. - * @param[in] aBuf A pointer to the buffer. - * @param[in] aLength Number of bytes to print. - * - */ - -/** - * @def otDumpWarnMac - * - * This function generates a memory dump with log level warning and region MAC. - * - * @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes. - * @param[in] aBuf A pointer to the buffer. - * @param[in] aLength Number of bytes to print. - * - */ - -/** - * @def otDumpNoteMac - * - * This function generates a memory dump with log level note and region MAC. - * - * @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes. - * @param[in] aBuf A pointer to the buffer. - * @param[in] aLength Number of bytes to print. - * - */ - -/** - * @def otDumpInfoMac - * - * This function generates a memory dump with log level info and region MAC. - * - * @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes. - * @param[in] aBuf A pointer to the buffer. - * @param[in] aLength Number of bytes to print. - * - */ - -/** - * @def otDumpDebgMac - * - * This function generates a memory dump with log level debug and region MAC. - * - * @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes. - * @param[in] aBuf A pointer to the buffer. - * @param[in] aLength Number of bytes to print. - * - */ -#if OPENTHREAD_CONFIG_LOG_MAC -void otDumpMacFrame(otLogLevel aLogLevel, const char *aId, const void *aBuf, size_t aLength); -#define otDumpCritMac(aId, aBuf, aLength) otDumpMacFrame(OT_LOG_LEVEL_CRIT, aId, aBuf, aLength) -#define otDumpWarnMac(aId, aBuf, aLength) otDumpMacFrame(OT_LOG_LEVEL_WARN, aId, aBuf, aLength) -#define otDumpNoteMac(aId, aBuf, aLength) otDumpMacFrame(OT_LOG_LEVEL_NOTE, aId, aBuf, aLength) -#define otDumpInfoMac(aId, aBuf, aLength) otDumpMacFrame(OT_LOG_LEVEL_INFO, aId, aBuf, aLength) -#define otDumpDebgMac(aId, aBuf, aLength) otDumpMacFrame(OT_LOG_LEVEL_DEBG, aId, aBuf, aLength) -#else -#define otDumpCritMac(aId, aBuf, aLength) -#define otDumpWarnMac(aId, aBuf, aLength) -#define otDumpNoteMac(aId, aBuf, aLength) -#define otDumpInfoMac(aId, aBuf, aLength) -#define otDumpDebgMac(aId, aBuf, aLength) -#endif - -/** - * @def otDumpCritCore - * - * This function generates a memory dump with log level debug and region Core. - * - * @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes. - * @param[in] aBuf A pointer to the buffer. - * @param[in] aLength Number of bytes to print. - * - */ - -/** - * @def otDumpWarnCore - * - * This function generates a memory dump with log level warning and region Core. - * - * @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes. - * @param[in] aBuf A pointer to the buffer. - * @param[in] aLength Number of bytes to print. - * - */ - -/** - * @def otDumpNoteCore - * - * This function generates a memory dump with log level note and region Core. - * - * @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes. - * @param[in] aBuf A pointer to the buffer. - * @param[in] aLength Number of bytes to print. - * - */ - -/** - * @def otDumpInfoCore - * - * This function generates a memory dump with log level info and region Core. - * - * @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes. - * @param[in] aBuf A pointer to the buffer. - * @param[in] aLength Number of bytes to print. - * - */ - -/** - * @def otDumpDebgCore - * - * This function generates a memory dump with log level debug and region Core. - * - * @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes. - * @param[in] aBuf A pointer to the buffer. - * @param[in] aLength Number of bytes to print. - * - */ -#if OPENTHREAD_CONFIG_LOG_CORE -#define otDumpCritCore(aId, aBuf, aLength) otDumpCrit(OT_LOG_REGION_CORE, aId, aBuf, aLength) -#define otDumpWarnCore(aId, aBuf, aLength) otDumpWarn(OT_LOG_REGION_CORE, aId, aBuf, aLength) -#define otDumpNoteCore(aId, aBuf, aLength) otDumpNote(OT_LOG_REGION_CORE, aId, aBuf, aLength) -#define otDumpInfoCore(aId, aBuf, aLength) otDumpInfo(OT_LOG_REGION_CORE, aId, aBuf, aLength) -#define otDumpDebgCore(aId, aBuf, aLength) otDumpDebg(OT_LOG_REGION_CORE, aId, aBuf, aLength) -#else -#define otDumpCritCore(aId, aBuf, aLength) -#define otDumpWarnCore(aId, aBuf, aLength) -#define otDumpNoteCore(aId, aBuf, aLength) -#define otDumpInfoCore(aId, aBuf, aLength) -#define otDumpDebgCore(aId, aBuf, aLength) -#endif - -/** - * @def otDumpCritDua - * - * This function generates a memory dump with log level critical and region Domain Unicast Address. - * - * @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes. - * @param[in] aBuf A pointer to the buffer. - * @param[in] aLength Number of bytes to print. - * - */ - -/** - * @def otDumpWarnDua - * - * This function generates a memory dump with log level warning and region Domain Unicast Address. - * - * @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes. - * @param[in] aBuf A pointer to the buffer. - * @param[in] aLength Number of bytes to print. - * - */ - -/** - * @def otDumpNoteDua - * - * This function generates a memory dump with log level note and region Domain Unicast Address. - * - * @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes. - * @param[in] aBuf A pointer to the buffer. - * @param[in] aLength Number of bytes to print. - * - */ - -/** - * @def otDumpInfoDua - * - * This function generates a memory dump with log level info and region Domain Unicast Address. - * - * @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes. - * @param[in] aBuf A pointer to the buffer. - * @param[in] aLength Number of bytes to print. - * - */ - -/** - * @def otDumpDebgDua - * - * This function generates a memory dump with log level debug and region Domain Unicast Address. - * - * @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes. - * @param[in] aBuf A pointer to the buffer. - * @param[in] aLength Number of bytes to print. - * - */ -#if OPENTHREAD_CONFIG_LOG_DUA -#define otDumpCritDua(aId, aBuf, aLength) otDumpCrit(OT_LOG_REGION_DUA, aId, aBuf, aLength) -#define otDumpWarnDua(aId, aBuf, aLength) otDumpWarn(OT_LOG_REGION_DUA, aId, aBuf, aLength) -#define otDumpNoteDua(aId, aBuf, aLength) otDumpNote(OT_LOG_REGION_DUA, aId, aBuf, aLength) -#define otDumpInfoDua(aId, aBuf, aLength) otDumpInfo(OT_LOG_REGION_DUA, aId, aBuf, aLength) -#define otDumpDebgDua(aId, aBuf, aLength) otDumpDebg(OT_LOG_REGION_DUA, aId, aBuf, aLength) -#else -#define otDumpCritDua(aId, aBuf, aLength) -#define otDumpWarnDua(aId, aBuf, aLength) -#define otDumpNoteDua(aId, aBuf, aLength) -#define otDumpInfoDua(aId, aBuf, aLength) -#define otDumpDebgDua(aId, aBuf, aLength) -#endif - -/** - * @def otDumpCritSrp - * - * This function generates a memory dump with log level critical and region Service Registration Protocol (SRP). - * - * @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes. - * @param[in] aBuf A pointer to the buffer. - * @param[in] aLength Number of bytes to print. - * - */ - -/** - * @def otDumpWarnSrp - * - * This function generates a memory dump with log level warning and region Service Registration Protocol (SRP). - * - * @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes. - * @param[in] aBuf A pointer to the buffer. - * @param[in] aLength Number of bytes to print. - * - */ - -/** - * @def otDumpNoteSrp - * - * This function generates a memory dump with log level note and region Service Registration Protocol (SRP). - * - * @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes. - * @param[in] aBuf A pointer to the buffer. - * @param[in] aLength Number of bytes to print. - * - */ - -/** - * @def otDumpInfoSrp - * - * This function generates a memory dump with log level info and region Service Registration Protocol (SRP). - * - * @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes. - * @param[in] aBuf A pointer to the buffer. - * @param[in] aLength Number of bytes to print. - * - */ - -/** - * @def otDumpDebgSrp - * - * This function generates a memory dump with log level debug and region Service Registration Protocol (SRP). - * - * @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes. - * @param[in] aBuf A pointer to the buffer. - * @param[in] aLength Number of bytes to print. - * - */ -#if OPENTHREAD_CONFIG_LOG_SRP -#define otDumpCritSrp(aId, aBuf, aLength) otDumpCrit(OT_LOG_REGION_SRP, aId, aBuf, aLength) -#define otDumpWarnSrp(aId, aBuf, aLength) otDumpWarn(OT_LOG_REGION_SRP, aId, aBuf, aLength) -#define otDumpNoteSrp(aId, aBuf, aLength) otDumpNote(OT_LOG_REGION_SRP, aId, aBuf, aLength) -#define otDumpInfoSrp(aId, aBuf, aLength) otDumpInfo(OT_LOG_REGION_SRP, aId, aBuf, aLength) -#define otDumpDebgSrp(aId, aBuf, aLength) otDumpDebg(OT_LOG_REGION_SRP, aId, aBuf, aLength) -#else -#define otDumpCritSrp(aId, aBuf, aLength) -#define otDumpWarnSrp(aId, aBuf, aLength) -#define otDumpNoteSrp(aId, aBuf, aLength) -#define otDumpInfoSrp(aId, aBuf, aLength) -#define otDumpDebgSrp(aId, aBuf, aLength) -#endif - -/** - * @def otDumpCritBr - * - * This function generates a memory dump with log level critical and region Border Routing. - * - * @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes. - * @param[in] aBuf A pointer to the buffer. - * @param[in] aLength Number of bytes to print. - * - */ - -/** - * @def otDumpWarnBr - * - * This function generates a memory dump with log level warning and region Border Routing. - * - * @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes. - * @param[in] aBuf A pointer to the buffer. - * @param[in] aLength Number of bytes to print. - * - */ - -/** - * @def otDumpNoteBr - * - * This function generates a memory dump with log level note and region Border Routing. - * - * @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes. - * @param[in] aBuf A pointer to the buffer. - * @param[in] aLength Number of bytes to print. - * - */ - -/** - * @def otDumpInfoBr - * - * This function generates a memory dump with log level info and region Border Routing. - * - * @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes. - * @param[in] aBuf A pointer to the buffer. - * @param[in] aLength Number of bytes to print. - * - */ - -/** - * @def otDumpDebgBr - * - * This function generates a memory dump with log level debug and region Border Routing. - * - * @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes. - * @param[in] aBuf A pointer to the buffer. - * @param[in] aLength Number of bytes to print. - * - */ -#if OPENTHREAD_CONFIG_LOG_BR -#define otDumpCritBr(aId, aBuf, aLength) otDumpCrit(OT_LOG_REGION_BR, aId, aBuf, aLength) -#define otDumpWarnBr(aId, aBuf, aLength) otDumpWarn(OT_LOG_REGION_BR, aId, aBuf, aLength) -#define otDumpNoteBr(aId, aBuf, aLength) otDumpNote(OT_LOG_REGION_BR, aId, aBuf, aLength) -#define otDumpInfoBr(aId, aBuf, aLength) otDumpInfo(OT_LOG_REGION_BR, aId, aBuf, aLength) -#define otDumpDebgBr(aId, aBuf, aLength) otDumpDebg(OT_LOG_REGION_BR, aId, aBuf, aLength) -#else -#define otDumpCritBr(aId, aBuf, aLength) -#define otDumpWarnBr(aId, aBuf, aLength) -#define otDumpNoteBr(aId, aBuf, aLength) -#define otDumpInfoBr(aId, aBuf, aLength) -#define otDumpDebgBr(aId, aBuf, aLength) -#endif - -/** - * @def otDumpCritDns - * - * This function generates a memory dump with log level critical and region DNS. - * - * @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes. - * @param[in] aBuf A pointer to the buffer. - * @param[in] aLength Number of bytes to print. - * - */ - -/** - * @def otDumpWarnDns - * - * This function generates a memory dump with log level warning and region DNS. - * - * @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes. - * @param[in] aBuf A pointer to the buffer. - * @param[in] aLength Number of bytes to print. - * - */ - -/** - * @def otDumpNoteDns - * - * This function generates a memory dump with log level note and region DNS. - * - * @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes. - * @param[in] aBuf A pointer to the buffer. - * @param[in] aLength Number of bytes to print. - * - */ - -/** - * @def otDumpInfoDns - * - * This function generates a memory dump with log level info and region DNS. - * - * @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes. - * @param[in] aBuf A pointer to the buffer. - * @param[in] aLength Number of bytes to print. - * - */ - -/** - * @def otDumpDebgDns - * - * This function generates a memory dump with log level debug and region DNS. - * - * @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes. - * @param[in] aBuf A pointer to the buffer. - * @param[in] aLength Number of bytes to print. - * - */ -#if OPENTHREAD_CONFIG_LOG_SRP -#define otDumpCritDns(aId, aBuf, aLength) otDumpCrit(OT_LOG_REGION_SRP, aId, aBuf, aLength) -#define otDumpWarnDns(aId, aBuf, aLength) otDumpWarn(OT_LOG_REGION_SRP, aId, aBuf, aLength) -#define otDumpNoteDns(aId, aBuf, aLength) otDumpNote(OT_LOG_REGION_SRP, aId, aBuf, aLength) -#define otDumpInfoDns(aId, aBuf, aLength) otDumpInfo(OT_LOG_REGION_SRP, aId, aBuf, aLength) -#define otDumpDebgDns(aId, aBuf, aLength) otDumpDebg(OT_LOG_REGION_SRP, aId, aBuf, aLength) -#else -#define otDumpCritDns(aId, aBuf, aLength) -#define otDumpWarnDns(aId, aBuf, aLength) -#define otDumpNoteDns(aId, aBuf, aLength) -#define otDumpInfoDns(aId, aBuf, aLength) -#define otDumpDebgDns(aId, aBuf, aLength) -#endif - -/** - * @def otDumpCritMem - * - * This function generates a memory dump with log level debug and region memory. - * - * @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes. - * @param[in] aBuf A pointer to the buffer. - * @param[in] aLength Number of bytes to print. - * - */ - -/** - * @def otDumpWarnMem - * - * This function generates a memory dump with log level warning and region memory. - * - * @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes. - * @param[in] aBuf A pointer to the buffer. - * @param[in] aLength Number of bytes to print. - * - */ - -/** - * @def otDumpNoteMem - * - * This function generates a memory dump with log level note and region memory. - * - * @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes. - * @param[in] aBuf A pointer to the buffer. - * @param[in] aLength Number of bytes to print. - * - */ - -/** - * @def otDumpInfoMem - * - * This function generates a memory dump with log level info and region memory. - * - * @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes. - * @param[in] aBuf A pointer to the buffer. - * @param[in] aLength Number of bytes to print. - * - */ - -/** - * @def otDumpDebgMem - * - * This function generates a memory dump with log level debug and region memory. - * - * @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes. - * @param[in] aBuf A pointer to the buffer. - * @param[in] aLength Number of bytes to print. - * - */ -#if OPENTHREAD_CONFIG_LOG_MEM -#define otDumpCritMem(aId, aBuf, aLength) otDumpCrit(OT_LOG_REGION_MEM, aId, aBuf, aLength) -#define otDumpWarnMem(aId, aBuf, aLength) otDumpWarn(OT_LOG_REGION_MEM, aId, aBuf, aLength) -#define otDumpNoteMem(aId, aBuf, aLength) otDumpNote(OT_LOG_REGION_MEM, aId, aBuf, aLength) -#define otDumpInfoMem(aId, aBuf, aLength) otDumpInfo(OT_LOG_REGION_MEM, aId, aBuf, aLength) -#define otDumpDebgMem(aId, aBuf, aLength) otDumpDebg(OT_LOG_REGION_MEM, aId, aBuf, aLength) -#else -#define otDumpCritMem(aId, aBuf, aLength) -#define otDumpWarnMem(aId, aBuf, aLength) -#define otDumpNoteMem(aId, aBuf, aLength) -#define otDumpInfoMem(aId, aBuf, aLength) -#define otDumpDebgMem(aId, aBuf, aLength) -#endif - -/** - * @def otDumpCertMeshCoP - * - * This function generates a memory dump with log level none for the certification test. - * - * @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes. - * @param[in] aBuf A pointer to the buffer. - * @param[in] aLength Number of bytes to print. - * - */ -#if OPENTHREAD_CONFIG_REFERENCE_DEVICE_ENABLE -#define otDumpCertMeshCoP(aId, aBuf, aLength) otDump(OT_LOG_LEVEL_NONE, OT_LOG_REGION_MESH_COP, aId, aBuf, aLength) -#else -#define otDumpCertMeshCoP(aId, aBuf, aLength) -#endif - -/** - * This function dumps bytes to the log in a human-readable fashion. - * - * @param[in] aLogLevel The log level. - * @param[in] aLogRegion The log region. - * @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes. - * @param[in] aBuf A pointer to the buffer. - * @param[in] aLength Number of bytes to print. - * - */ -void otDump(otLogLevel aLogLevel, otLogRegion aLogRegion, const char *aId, const void *aBuf, size_t aLength); - -#ifdef __cplusplus -} -#endif - #endif // LOGGING_HPP_ diff --git a/src/core/common/message.cpp b/src/core/common/message.cpp index 3ddc9f18f..4c48204b5 100644 --- a/src/core/common/message.cpp +++ b/src/core/common/message.cpp @@ -39,7 +39,7 @@ #include "common/heap.hpp" #include "common/instance.hpp" #include "common/locator_getters.hpp" -#include "common/logging.hpp" +#include "common/log.hpp" #include "net/checksum.hpp" #include "net/ip6.hpp" @@ -55,6 +55,8 @@ namespace ot { +RegisterLogModule("Message"); + //--------------------------------------------------------------------------------------------------------------------- // MessagePool @@ -128,7 +130,7 @@ Buffer *MessagePool::NewBuffer(Message::Priority aPriority) exit: if (buffer == nullptr) { - otLogInfoMem("No available message buffer"); + LogInfo("No available message buffer"); } return buffer; diff --git a/src/core/common/notifier.cpp b/src/core/common/notifier.cpp index 99663274c..06c29ea1a 100644 --- a/src/core/common/notifier.cpp +++ b/src/core/common/notifier.cpp @@ -38,10 +38,12 @@ #include "common/code_utils.hpp" #include "common/debug.hpp" #include "common/locator_getters.hpp" -#include "common/logging.hpp" +#include "common/log.hpp" namespace ot { +RegisterLogModule("Notifier"); + Notifier::Notifier(Instance &aInstance) : InstanceLocator(aInstance) , mTask(aInstance, Notifier::EmitEvents) @@ -214,7 +216,7 @@ exit: // LCOV_EXCL_START -#if (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO) && (OPENTHREAD_CONFIG_LOG_CORE == 1) +#if OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO void Notifier::LogEvents(Events aEvents) const { @@ -231,8 +233,8 @@ void Notifier::LogEvents(Events aEvents) const { if (string.GetLength() >= kFlagsStringLineLimit) { - otLogInfoCore("Notifier: StateChanged (0x%08x) %s%s ...", aEvents.GetAsFlags(), didLog ? "... " : "[", - string.AsCString()); + LogInfo("StateChanged (0x%08x) %s%s ...", aEvents.GetAsFlags(), didLog ? "... " : "[", + string.AsCString()); string.Clear(); didLog = true; addSpace = false; @@ -246,8 +248,7 @@ void Notifier::LogEvents(Events aEvents) const } exit: - otLogInfoCore("Notifier: StateChanged (0x%08x) %s%s]", aEvents.GetAsFlags(), didLog ? "... " : "[", - string.AsCString()); + LogInfo("StateChanged (0x%08x) %s%s]", aEvents.GetAsFlags(), didLog ? "... " : "[", string.AsCString()); } const char *Notifier::EventToString(Event aEvent) const @@ -302,7 +303,7 @@ const char *Notifier::EventToString(Event aEvent) const return retval; } -#else // #if (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO) && (OPENTHREAD_CONFIG_LOG_CORE == 1) +#else // #if OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO void Notifier::LogEvents(Events) const { @@ -313,7 +314,7 @@ const char *Notifier::EventToString(Event) const return ""; } -#endif // #if (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO) && (OPENTHREAD_CONFIG_LOG_CORE == 1) +#endif // #if OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO // LCOV_EXCL_STOP diff --git a/src/core/common/random_manager.cpp b/src/core/common/random_manager.cpp index 3ff7ffee3..e059bdeeb 100644 --- a/src/core/common/random_manager.cpp +++ b/src/core/common/random_manager.cpp @@ -37,7 +37,6 @@ #include "common/code_utils.hpp" #include "common/debug.hpp" -#include "common/logging.hpp" #include "common/random.hpp" #include "crypto/mbedtls.hpp" diff --git a/src/core/common/settings.cpp b/src/core/common/settings.cpp index ed5fad6ee..ea27dbae7 100644 --- a/src/core/common/settings.cpp +++ b/src/core/common/settings.cpp @@ -37,78 +37,78 @@ #include "common/code_utils.hpp" #include "common/instance.hpp" #include "common/locator_getters.hpp" -#include "common/logging.hpp" +#include "common/log.hpp" #include "meshcop/dataset.hpp" #include "thread/mle.hpp" namespace ot { +RegisterLogModule("Settings"); + //--------------------------------------------------------------------------------------------------------------------- // SettingsBase // LCOV_EXCL_START -#if OPENTHREAD_CONFIG_LOG_UTIL && (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO) +#if OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO void SettingsBase::NetworkInfo::Log(Action aAction) const { - otLogInfoCore( - "[settings] %s NetworkInfo {rloc:0x%04x, extaddr:%s, role:%s, mode:0x%02x, version:%hu, keyseq:0x%x, ...", - ActionToString(aAction), GetRloc16(), GetExtAddress().ToString().AsCString(), - Mle::Mle::RoleToString(static_cast(GetRole())), GetDeviceMode(), GetVersion(), - GetKeySequence()); + LogInfo("%s NetworkInfo {rloc:0x%04x, extaddr:%s, role:%s, mode:0x%02x, version:%hu, keyseq:0x%x, ...", + ActionToString(aAction), GetRloc16(), GetExtAddress().ToString().AsCString(), + Mle::Mle::RoleToString(static_cast(GetRole())), GetDeviceMode(), GetVersion(), + GetKeySequence()); - otLogInfoCore("[settings] ... pid:0x%x, mlecntr:0x%x, maccntr:0x%x, mliid:%s}", GetPreviousPartitionId(), - GetMleFrameCounter(), GetMacFrameCounter(), GetMeshLocalIid().ToString().AsCString()); + LogInfo("... pid:0x%x, mlecntr:0x%x, maccntr:0x%x, mliid:%s}", GetPreviousPartitionId(), GetMleFrameCounter(), + GetMacFrameCounter(), GetMeshLocalIid().ToString().AsCString()); } void SettingsBase::ParentInfo::Log(Action aAction) const { - otLogInfoCore("[settings] %s ParentInfo {extaddr:%s, version:%hu}", ActionToString(aAction), - GetExtAddress().ToString().AsCString(), GetVersion()); + LogInfo("%s ParentInfo {extaddr:%s, version:%hu}", ActionToString(aAction), GetExtAddress().ToString().AsCString(), + GetVersion()); } #if OPENTHREAD_FTD void SettingsBase::ChildInfo::Log(Action aAction) const { - otLogInfoCore("[settings] %s ChildInfo {rloc:0x%04x, extaddr:%s, timeout:%u, mode:0x%02x, version:%hu}", - ActionToString(aAction), GetRloc16(), GetExtAddress().ToString().AsCString(), GetTimeout(), GetMode(), - GetVersion()); + LogInfo("%s ChildInfo {rloc:0x%04x, extaddr:%s, timeout:%u, mode:0x%02x, version:%hu}", ActionToString(aAction), + GetRloc16(), GetExtAddress().ToString().AsCString(), GetTimeout(), GetMode(), GetVersion()); } #endif #if OPENTHREAD_CONFIG_DUA_ENABLE void SettingsBase::DadInfo::Log(Action aAction) const { - otLogInfoCore("[settings] %s DadInfo {DadCounter:%2d}", ActionToString(aAction), GetDadCounter()); + LogInfo("%s DadInfo {DadCounter:%2d}", ActionToString(aAction), GetDadCounter()); } #endif #if OPENTHREAD_CONFIG_BORDER_ROUTING_ENABLE void SettingsBase::LogPrefix(Action aAction, Key aKey, const Ip6::Prefix &aPrefix) { - otLogInfoCore("[settings] %s %s %s", ActionToString(aAction), KeyToString(aKey), aPrefix.ToString().AsCString()); + LogInfo("%s %s %s", ActionToString(aAction), KeyToString(aKey), aPrefix.ToString().AsCString()); } #endif #if OPENTHREAD_CONFIG_SRP_CLIENT_ENABLE && OPENTHREAD_CONFIG_SRP_CLIENT_SAVE_SELECTED_SERVER_ENABLE void SettingsBase::SrpClientInfo::Log(Action aAction) const { - otLogInfoCore("[settings] %s SrpClientInfo {Server:[%s]:%u}", ActionToString(aAction), - GetServerAddress().ToString().AsCString(), GetServerPort()); + LogInfo("%s SrpClientInfo {Server:[%s]:%u}", ActionToString(aAction), GetServerAddress().ToString().AsCString(), + GetServerPort()); } #endif #if OPENTHREAD_CONFIG_SRP_SERVER_ENABLE && OPENTHREAD_CONFIG_SRP_SERVER_PORT_SWITCH_ENABLE void SettingsBase::SrpServerInfo::Log(Action aAction) const { - otLogInfoCore("[settings] %s SrpServerInfo {port:%u}", ActionToString(aAction), GetPort()); + LogInfo("%s SrpServerInfo {port:%u}", ActionToString(aAction), GetPort()); } #endif -#endif // OPENTHREAD_CONFIG_LOG_UTIL && (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO) +#endif // OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO -#if OPENTHREAD_CONFIG_LOG_UTIL && (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO) +#if OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO const char *SettingsBase::ActionToString(Action aAction) { static const char *const kActionStrings[] = { @@ -135,9 +135,9 @@ const char *SettingsBase::ActionToString(Action aAction) return kActionStrings[aAction]; } -#endif // OPENTHREAD_CONFIG_LOG_UTIL && (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO) +#endif // OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO -#if OPENTHREAD_CONFIG_LOG_UTIL && (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_WARN) +#if OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_WARN const char *SettingsBase::KeyToString(Key aKey) { static const char *const kKeyStrings[] = { @@ -179,7 +179,7 @@ const char *SettingsBase::KeyToString(Key aKey) return kKeyStrings[aKey]; } -#endif // OPENTHREAD_CONFIG_LOG_UTIL && (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_WARN) +#endif // OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_WARN // LCOV_EXCL_STOP @@ -207,7 +207,7 @@ void Settings::Deinit(void) void Settings::Wipe(void) { Get().Wipe(); - otLogInfoCore("[settings] Wiped all info"); + LogInfo("Wiped all info"); } Error Settings::SaveOperationalDataset(bool aIsActive, const MeshCoP::Dataset &aDataset) @@ -356,8 +356,6 @@ void Settings::Log(Action aAction, Error aError, Key aKey, const void *aValue) OT_UNUSED_VARIABLE(aError); OT_UNUSED_VARIABLE(aValue); -#if OPENTHREAD_CONFIG_LOG_UTIL - if (aError != kErrorNone) { // Log error if log level is at "warn" or higher. @@ -396,7 +394,7 @@ void Settings::Log(Action aAction, Error aError, Key aKey, const void *aValue) ExitNow(); } - otLogWarnCore("[settings] Error %s %s %s", ErrorToString(aError), actionText, KeyToString(aKey)); + LogWarn("Error %s %s %s", ErrorToString(aError), actionText, KeyToString(aKey)); #endif // #if (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_WARN) @@ -463,13 +461,11 @@ void Settings::Log(Action aAction, Error aError, Key aKey, const void *aValue) if (aValue == nullptr) { - otLogInfoCore("[settings] %s %s", ActionToString(aAction), KeyToString(aKey)); + LogInfo("%s %s", ActionToString(aAction), KeyToString(aKey)); } #endif // (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO) exit: - -#endif // OPENTHREAD_CONFIG_LOG_UTIL return; } diff --git a/src/core/common/settings.hpp b/src/core/common/settings.hpp index c394bb02b..116573a90 100644 --- a/src/core/common/settings.hpp +++ b/src/core/common/settings.hpp @@ -744,10 +744,10 @@ protected: static void LogPrefix(Action aAction, Key aKey, const Ip6::Prefix &aPrefix); #endif -#if OPENTHREAD_CONFIG_LOG_UTIL && (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_WARN) +#if OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_WARN static const char *KeyToString(Key aKey); #endif -#if OPENTHREAD_CONFIG_LOG_UTIL && (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO) +#if OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO static const char *ActionToString(Action aAction); #endif }; diff --git a/src/core/common/timer.cpp b/src/core/common/timer.cpp index 803f054b5..66de06d99 100644 --- a/src/core/common/timer.cpp +++ b/src/core/common/timer.cpp @@ -38,7 +38,6 @@ #include "common/debug.hpp" #include "common/instance.hpp" #include "common/locator_getters.hpp" -#include "common/logging.hpp" namespace ot { diff --git a/src/core/config/logging.h b/src/core/config/logging.h index d531e4a8a..aacec6984 100644 --- a/src/core/config/logging.h +++ b/src/core/config/logging.h @@ -103,140 +103,20 @@ #define OPENTHREAD_CONFIG_LOG_LEVEL_INIT OPENTHREAD_CONFIG_LOG_LEVEL #endif -/** - * @def OPENTHREAD_CONFIG_LOG_API - * - * Define to enable OpenThread API logging. - * - */ -#ifndef OPENTHREAD_CONFIG_LOG_API -#define OPENTHREAD_CONFIG_LOG_API 1 -#endif - -/** - * @def OPENTHREAD_CONFIG_LOG_MLE - * - * Define to enable MLE logging. - * - */ -#ifndef OPENTHREAD_CONFIG_LOG_MLE -#define OPENTHREAD_CONFIG_LOG_MLE 1 -#endif - -/** - * @def OPENTHREAD_CONFIG_LOG_MESHCOP - * - * Define to enable MeshCoP logging. - * - */ -#ifndef OPENTHREAD_CONFIG_LOG_MESHCOP -#define OPENTHREAD_CONFIG_LOG_MESHCOP 1 -#endif - -/** - * @def OPENTHREAD_CONFIG_LOG_ARP - * - * Define to enable EID-to-RLOC map logging. - * - */ -#ifndef OPENTHREAD_CONFIG_LOG_ARP -#define OPENTHREAD_CONFIG_LOG_ARP 1 -#endif - -/** - * @def OPENTHREAD_CONFIG_LOG_NETDATA - * - * Define to enable Network Data logging. - * - */ -#ifndef OPENTHREAD_CONFIG_LOG_NETDATA -#define OPENTHREAD_CONFIG_LOG_NETDATA 1 -#endif - -/** - * @def OPENTHREAD_CONFIG_LOG_ICMP - * - * Define to enable ICMPv6 logging. - * - */ -#ifndef OPENTHREAD_CONFIG_LOG_ICMP -#define OPENTHREAD_CONFIG_LOG_ICMP 1 -#endif - -/** - * @def OPENTHREAD_CONFIG_LOG_IP6 - * - * Define to enable IPv6 logging. - * - */ -#ifndef OPENTHREAD_CONFIG_LOG_IP6 -#define OPENTHREAD_CONFIG_LOG_IP6 1 -#endif - -/** - * @def OPENTHREAD_CONFIG_LOG_TCP - * - * Define to enable IPv6 logging. - * - */ -#ifndef OPENTHREAD_CONFIG_LOG_TCP -#define OPENTHREAD_CONFIG_LOG_TCP 1 -#endif - -/** - * @def OPENTHREAD_CONFIG_LOG_MAC - * - * Define to enable IEEE 802.15.4 MAC logging. - * - */ -#ifndef OPENTHREAD_CONFIG_LOG_MAC -#define OPENTHREAD_CONFIG_LOG_MAC 1 -#endif - -/** - * @def OPENTHREAD_CONFIG_LOG_MEM - * - * Define to enable memory logging. - * - */ -#ifndef OPENTHREAD_CONFIG_LOG_MEM -#define OPENTHREAD_CONFIG_LOG_MEM 1 -#endif - /** * @def OPENTHREAD_CONFIG_LOG_PKT_DUMP * - * Define to enable log content of packets. + * Define to enable dump logs (of packets). * */ #ifndef OPENTHREAD_CONFIG_LOG_PKT_DUMP #define OPENTHREAD_CONFIG_LOG_PKT_DUMP 1 #endif -/** - * @def OPENTHREAD_CONFIG_LOG_NETDIAG - * - * Define to enable network diagnostic logging. - * - */ -#ifndef OPENTHREAD_CONFIG_LOG_NETDIAG -#define OPENTHREAD_CONFIG_LOG_NETDIAG 1 -#endif - -/** - * @def OPENTHREAD_CONFIG_LOG_PLATFORM - * - * Define to enable platform region logging. - * - */ -#ifndef OPENTHREAD_CONFIG_LOG_PLATFORM -#define OPENTHREAD_CONFIG_LOG_PLATFORM 1 -#endif - /** * @def OPENTHREAD_CONFIG_LOG_CLI * - * Define to enable CLI logging. + * Define to enable CLI logging and `otLogCli()` OT function. * */ #ifndef OPENTHREAD_CONFIG_LOG_CLI @@ -244,99 +124,13 @@ #endif /** - * @def OPENTHREAD_CONFIG_LOG_COAP + * @def OPENTHREAD_CONFIG_LOG_PLATFORM * - * Define to enable COAP logging. + * Define to enable platform logging and `otLog{Level}Plat()` OT functions. * */ -#ifndef OPENTHREAD_CONFIG_LOG_COAP -#define OPENTHREAD_CONFIG_LOG_COAP 1 -#endif - -/** - * @def OPENTHREAD_CONFIG_LOG_CORE - * - * Define to enable OpenThread Core logging. - * - */ -#ifndef OPENTHREAD_CONFIG_LOG_CORE -#define OPENTHREAD_CONFIG_LOG_CORE 1 -#endif - -/** - * @def OPENTHREAD_CONFIG_LOG_UTIL - * - * Define to enable OpenThread Utility module logging. - * - */ -#ifndef OPENTHREAD_CONFIG_LOG_UTIL -#define OPENTHREAD_CONFIG_LOG_UTIL 1 -#endif - -/** - * @def OPENTHREAD_CONFIG_LOG_BBR - * - * Note: available since Thread 1.2. - * - * Define to enable Backbone Router (BBR) region logging. - * - */ -#ifndef OPENTHREAD_CONFIG_LOG_BBR -#define OPENTHREAD_CONFIG_LOG_BBR 1 -#endif - -/** - * @def OPENTHREAD_CONFIG_LOG_MLR - * - * Note: available since Thread 1.2. - * - * Define to enable Multicast Listener Registration (MLR) region logging. - * - */ -#ifndef OPENTHREAD_CONFIG_LOG_MLR -#define OPENTHREAD_CONFIG_LOG_MLR 1 -#endif - -/** - * @def OPENTHREAD_CONFIG_LOG_DUA - * - * Note: available since Thread 1.2. - * - * Define to enable Domain Unicast Address (DUA) region logging. - * - */ -#ifndef OPENTHREAD_CONFIG_LOG_DUA -#define OPENTHREAD_CONFIG_LOG_DUA 1 -#endif - -/** - * @def OPENTHREAD_CONFIG_LOG_BR - * - * Define to Border Router (BR) region logging. - * - */ -#ifndef OPENTHREAD_CONFIG_LOG_BR -#define OPENTHREAD_CONFIG_LOG_BR 1 -#endif - -/** - * @def OPENTHREAD_CONFIG_LOG_SRP - * - * Define to enable Service Registration Protocol (SRP) region logging. - * - */ -#ifndef OPENTHREAD_CONFIG_LOG_SRP -#define OPENTHREAD_CONFIG_LOG_SRP 1 -#endif - -/** - * @def OPENTHREAD_CONFIG_LOG_DNS - * - * Define to enable DNS region logging. - * - */ -#ifndef OPENTHREAD_CONFIG_LOG_DNS -#define OPENTHREAD_CONFIG_LOG_DNS 1 +#ifndef OPENTHREAD_CONFIG_LOG_PLATFORM +#define OPENTHREAD_CONFIG_LOG_PLATFORM 1 #endif /** @@ -359,16 +153,6 @@ #define OPENTHREAD_CONFIG_LOG_PREPEND_LEVEL 1 #endif -/** - * @def OPENTHREAD_CONFIG_LOG_PREPEND_REGION - * - * Define to prepend the log region to all log messages. - * - */ -#ifndef OPENTHREAD_CONFIG_LOG_PREPEND_REGION -#define OPENTHREAD_CONFIG_LOG_PREPEND_REGION 1 -#endif - /** * @def OPENTHREAD_CONFIG_LOG_SUFFIX * diff --git a/src/core/config/openthread-core-config-check.h b/src/core/config/openthread-core-config-check.h index b90e041f1..dc4032ab3 100644 --- a/src/core/config/openthread-core-config-check.h +++ b/src/core/config/openthread-core-config-check.h @@ -530,4 +530,88 @@ #error "OPENTHREAD_CONFIG_UNSECURE_TRAFFIC_MANAGED_BY_STACK_ENABLE was removed and no longer supported" #endif +#ifdef OPENTHREAD_CONFIG_LOG_API +#error "OPENTHREAD_CONFIG_LOG_API was removed and no longer supported" +#endif + +#ifdef OPENTHREAD_CONFIG_LOG_MLE +#error "OPENTHREAD_CONFIG_LOG_MLE was removed and no longer supported" +#endif + +#ifdef OPENTHREAD_CONFIG_LOG_MESHCOP +#error "OPENTHREAD_CONFIG_LOG_MESHCOP was removed and no longer supported" +#endif + +#ifdef OPENTHREAD_CONFIG_LOG_ARP +#error "OPENTHREAD_CONFIG_LOG_ARP was removed and no longer supported" +#endif + +#ifdef OPENTHREAD_CONFIG_LOG_NETDATA +#error "OPENTHREAD_CONFIG_LOG_NETDATA was removed and no longer supported" +#endif + +#ifdef OPENTHREAD_CONFIG_LOG_ICMP +#error "OPENTHREAD_CONFIG_LOG_ICMP was removed and no longer supported" +#endif + +#ifdef OPENTHREAD_CONFIG_LOG_IP6 +#error "OPENTHREAD_CONFIG_LOG_IP6 was removed and no longer supported" +#endif + +#ifdef OPENTHREAD_CONFIG_LOG_TCP +#error "OPENTHREAD_CONFIG_LOG_TCP was removed and no longer supported" +#endif + +#ifdef OPENTHREAD_CONFIG_LOG_MAC +#error "OPENTHREAD_CONFIG_LOG_MAC was removed and no longer supported" +#endif + +#ifdef OPENTHREAD_CONFIG_LOG_MEM +#error "OPENTHREAD_CONFIG_LOG_MEM was removed and no longer supported" +#endif + +#ifdef OPENTHREAD_CONFIG_LOG_NETDIAG +#error "OPENTHREAD_CONFIG_LOG_NETDIAG was removed and no longer supported" +#endif + +#ifdef OPENTHREAD_CONFIG_LOG_COAP +#error "OPENTHREAD_CONFIG_LOG_COAP was removed and no longer supported" +#endif + +#ifdef OPENTHREAD_CONFIG_LOG_CORE +#error "OPENTHREAD_CONFIG_LOG_CORE was removed and no longer supported" +#endif + +#ifdef OPENTHREAD_CONFIG_LOG_UTIL +#error "OPENTHREAD_CONFIG_LOG_UTIL was removed and no longer supported" +#endif + +#ifdef OPENTHREAD_CONFIG_LOG_BBR +#error "OPENTHREAD_CONFIG_LOG_BBR was removed and no longer supported" +#endif + +#ifdef OPENTHREAD_CONFIG_LOG_MLR +#error "OPENTHREAD_CONFIG_LOG_MLR was removed and no longer supported" +#endif + +#ifdef OPENTHREAD_CONFIG_LOG_DUA +#error "OPENTHREAD_CONFIG_LOG_DUA was removed and no longer supported" +#endif + +#ifdef OPENTHREAD_CONFIG_LOG_BR +#error "OPENTHREAD_CONFIG_LOG_BR was removed and no longer supported" +#endif + +#ifdef OPENTHREAD_CONFIG_LOG_SRP +#error "OPENTHREAD_CONFIG_LOG_SRP was removed and no longer supported" +#endif + +#ifdef OPENTHREAD_CONFIG_LOG_DNS +#error "OPENTHREAD_CONFIG_LOG_DNS was removed and no longer supported" +#endif + +#ifdef OPENTHREAD_CONFIG_LOG_PREPEND_REGION +#error "OPENTHREAD_CONFIG_LOG_PREPEND_REGION was removed and not longer supported" +#endif + #endif // OPENTHREAD_CORE_CONFIG_CHECK_H_ diff --git a/src/core/mac/data_poll_handler.cpp b/src/core/mac/data_poll_handler.cpp index 8703ab094..c1d78e327 100644 --- a/src/core/mac/data_poll_handler.cpp +++ b/src/core/mac/data_poll_handler.cpp @@ -38,10 +38,12 @@ #include "common/code_utils.hpp" #include "common/instance.hpp" #include "common/locator_getters.hpp" -#include "common/logging.hpp" +#include "common/log.hpp" namespace ot { +RegisterLogModule("DataPollHandlr"); + DataPollHandler::Callbacks::Callbacks(Instance &aInstance) : InstanceLocator(aInstance) { @@ -144,8 +146,8 @@ void DataPollHandler::HandleDataPoll(Mac::RxFrame &aFrame) indirectMsgCount = child->GetIndirectMessageCount(); - otLogInfoMac("Rx data poll, src:0x%04x, qed_msgs:%d, rss:%d, ack-fp:%d", child->GetRloc16(), indirectMsgCount, - aFrame.GetRssi(), aFrame.IsAckedWithFramePending()); + LogInfo("Rx data poll, src:0x%04x, qed_msgs:%d, rss:%d, ack-fp:%d", child->GetRloc16(), indirectMsgCount, + aFrame.GetRssi(), aFrame.IsAckedWithFramePending()); if (!aFrame.IsAckedWithFramePending()) { @@ -245,8 +247,8 @@ void DataPollHandler::HandleSentFrame(const Mac::TxFrame &aFrame, Error aError, OT_ASSERT(!aFrame.GetSecurityEnabled() || aFrame.IsHeaderUpdated()); aChild.IncrementIndirectTxAttempts(); - otLogInfoMac("Indirect tx to child %04x failed, attempt %d/%d", aChild.GetRloc16(), - aChild.GetIndirectTxAttempts(), kMaxPollTriggeredTxAttempts); + LogInfo("Indirect tx to child %04x failed, attempt %d/%d", aChild.GetRloc16(), aChild.GetIndirectTxAttempts(), + kMaxPollTriggeredTxAttempts); OT_FALL_THROUGH; diff --git a/src/core/mac/data_poll_sender.cpp b/src/core/mac/data_poll_sender.cpp index 1756b1a7a..6af166d12 100644 --- a/src/core/mac/data_poll_sender.cpp +++ b/src/core/mac/data_poll_sender.cpp @@ -36,7 +36,7 @@ #include "common/code_utils.hpp" #include "common/instance.hpp" #include "common/locator_getters.hpp" -#include "common/logging.hpp" +#include "common/log.hpp" #include "common/message.hpp" #include "net/ip6.hpp" #include "net/netif.hpp" @@ -46,6 +46,8 @@ namespace ot { +RegisterLogModule("DataPollSender"); + DataPollSender::DataPollSender(Instance &aInstance) : InstanceLocator(aInstance) , mTimerStartTime(0) @@ -112,22 +114,22 @@ exit: switch (error) { case kErrorNone: - otLogDebgMac("Sending data poll"); + LogDebg("Sending data poll"); ScheduleNextPoll(kUsePreviousPollPeriod); break; case kErrorInvalidState: - otLogWarnMac("Data poll tx requested while data polling was not enabled!"); + LogWarn("Data poll tx requested while data polling was not enabled!"); StopPolling(); break; case kErrorAlready: - otLogDebgMac("Data poll tx requested when a previous data request still in send queue."); + LogDebg("Data poll tx requested when a previous data request still in send queue."); ScheduleNextPoll(kUsePreviousPollPeriod); break; default: - otLogWarnMac("Unexpected error %s requesting data poll", ErrorToString(error)); + LogWarn("Unexpected error %s requesting data poll", ErrorToString(error)); ScheduleNextPoll(kRecalculatePollPeriod); break; } @@ -260,12 +262,12 @@ void DataPollSender::HandlePollSent(Mac::TxFrame &aFrame, Error aError) mPollTxFailureCounter++; #if OPENTHREAD_CONFIG_MAC_CSL_RECEIVER_ENABLE - otLogInfoMac("Failed to send data poll, error:%s, retx:%d/%d", ErrorToString(aError), mPollTxFailureCounter, - (aFrame.GetHeaderIe(Mac::CslIe::kHeaderIeId) != nullptr) ? kMaxCslPollRetxAttempts - : kMaxPollRetxAttempts); + LogInfo("Failed to send data poll, error:%s, retx:%d/%d", ErrorToString(aError), mPollTxFailureCounter, + (aFrame.GetHeaderIe(Mac::CslIe::kHeaderIeId) != nullptr) ? kMaxCslPollRetxAttempts + : kMaxPollRetxAttempts); #else - otLogInfoMac("Failed to send data poll, error:%s, retx:%d/%d", ErrorToString(aError), mPollTxFailureCounter, - kMaxPollRetxAttempts); + LogInfo("Failed to send data poll, error:%s, retx:%d/%d", ErrorToString(aError), mPollTxFailureCounter, + kMaxPollRetxAttempts); #endif #if OPENTHREAD_CONFIG_MAC_CSL_RECEIVER_ENABLE @@ -310,7 +312,7 @@ void DataPollSender::HandlePollTimeout(void) mPollTimeoutCounter++; - otLogInfoMac("Data poll timeout, retry:%d/%d", mPollTimeoutCounter, kQuickPollsAfterTimeout); + LogInfo("Data poll timeout, retry:%d/%d", mPollTimeoutCounter, kQuickPollsAfterTimeout); if (mPollTimeoutCounter < kQuickPollsAfterTimeout) { diff --git a/src/core/mac/link_raw.cpp b/src/core/mac/link_raw.cpp index 155708f0d..8bdb45ea9 100644 --- a/src/core/mac/link_raw.cpp +++ b/src/core/mac/link_raw.cpp @@ -42,13 +42,15 @@ #include "common/debug.hpp" #include "common/instance.hpp" #include "common/locator_getters.hpp" -#include "common/logging.hpp" +#include "common/log.hpp" #include "common/random.hpp" #include "mac/mac_frame.hpp" namespace ot { namespace Mac { +RegisterLogModule("LinkRaw"); + LinkRaw::LinkRaw(Instance &aInstance) : InstanceLocator(aInstance) , mReceiveChannel(OPENTHREAD_CONFIG_DEFAULT_CHANNEL) @@ -84,7 +86,7 @@ Error LinkRaw::SetReceiveDone(otLinkRawReceiveDone aCallback) Error error = kErrorNone; bool enable = aCallback != nullptr; - otLogDebgMac("LinkRaw::Enabled(%s)", (enable ? "true" : "false")); + LogDebg("Enabled(%s)", (enable ? "true" : "false")); #if OPENTHREAD_MTD || OPENTHREAD_FTD VerifyOrExit(!Get().IsUp(), error = kErrorInvalidState); @@ -179,8 +181,7 @@ exit: void LinkRaw::InvokeReceiveDone(RxFrame *aFrame, Error aError) { - otLogDebgMac("LinkRaw::ReceiveDone(%d bytes), error:%s", (aFrame != nullptr) ? aFrame->mLength : 0, - ErrorToString(aError)); + LogDebg("ReceiveDone(%d bytes), error:%s", (aFrame != nullptr) ? aFrame->mLength : 0, ErrorToString(aError)); if (mReceiveDoneCallback && (aError == kErrorNone)) { @@ -203,7 +204,7 @@ exit: void LinkRaw::InvokeTransmitDone(TxFrame &aFrame, RxFrame *aAckFrame, Error aError) { - otLogDebgMac("LinkRaw::TransmitDone(%d bytes), error:%s", aFrame.mLength, ErrorToString(aError)); + LogDebg("TransmitDone(%d bytes), error:%s", aFrame.mLength, ErrorToString(aError)); if (mTransmitDoneCallback) { @@ -270,7 +271,7 @@ exit: // LCOV_EXCL_START -#if (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO) && (OPENTHREAD_CONFIG_LOG_MAC == 1) +#if OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO void LinkRaw::RecordFrameTransmitStatus(const TxFrame &aFrame, const RxFrame *aAckFrame, @@ -283,8 +284,8 @@ void LinkRaw::RecordFrameTransmitStatus(const TxFrame &aFrame, if (aError != kErrorNone) { - otLogInfoMac("Frame tx failed, error:%s, retries:%d/%d, %s", ErrorToString(aError), aRetryCount, - aFrame.GetMaxFrameRetries(), aFrame.ToInfoString().AsCString()); + LogInfo("Frame tx failed, error:%s, retries:%d/%d, %s", ErrorToString(aError), aRetryCount, + aFrame.GetMaxFrameRetries(), aFrame.ToInfoString().AsCString()); } } diff --git a/src/core/mac/link_raw.hpp b/src/core/mac/link_raw.hpp index 7b8eb4c82..b1c848d2c 100644 --- a/src/core/mac/link_raw.hpp +++ b/src/core/mac/link_raw.hpp @@ -294,7 +294,7 @@ public: * when there was an error in transmission (i.e., `aError` is not NONE). * */ -#if (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO) && (OPENTHREAD_CONFIG_LOG_MAC == 1) +#if OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO void RecordFrameTransmitStatus(const TxFrame &aFrame, const RxFrame *aAckFrame, Error aError, diff --git a/src/core/mac/mac.cpp b/src/core/mac/mac.cpp index b0f03f179..869f206d2 100644 --- a/src/core/mac/mac.cpp +++ b/src/core/mac/mac.cpp @@ -42,7 +42,7 @@ #include "common/encoding.hpp" #include "common/instance.hpp" #include "common/locator_getters.hpp" -#include "common/logging.hpp" +#include "common/log.hpp" #include "common/random.hpp" #include "common/string.hpp" #include "crypto/aes_ccm.hpp" @@ -58,6 +58,8 @@ namespace ot { namespace Mac { +RegisterLogModule("Mac"); + const otExtAddress Mac::sMode2ExtAddress = { {0x35, 0x06, 0xfe, 0xb8, 0x23, 0xd4, 0x87, 0x12}, }; @@ -594,7 +596,7 @@ void Mac::UpdateIdleMode(void) mTimer.Start(kSleepDelay); mShouldDelaySleep = false; mDelayingSleep = true; - otLogDebgMac("Idle mode: Sleep delayed"); + LogDebg("Idle mode: Sleep delayed"); } if (mDelayingSleep) @@ -620,12 +622,12 @@ void Mac::UpdateIdleMode(void) } #endif mLinks.Sleep(); - otLogDebgMac("Idle mode: Radio sleeping"); + LogDebg("Idle mode: Radio sleeping"); } else { mLinks.Receive(mRadioChannel); - otLogDebgMac("Idle mode: Radio receiving on channel %d", mRadioChannel); + LogDebg("Idle mode: Radio receiving on channel %d", mRadioChannel); } exit: @@ -643,12 +645,12 @@ void Mac::StartOperation(Operation aOperation) { SetPending(aOperation); - otLogDebgMac("Request to start operation \"%s\"", OperationToString(aOperation)); + LogDebg("Request to start operation \"%s\"", OperationToString(aOperation)); #if OPENTHREAD_CONFIG_MAC_STAY_AWAKE_BETWEEN_FRAGMENTS if (mDelayingSleep) { - otLogDebgMac("Canceling sleep delay"); + LogDebg("Canceling sleep delay"); mTimer.Stop(); mDelayingSleep = false; mShouldDelaySleep = false; @@ -732,7 +734,7 @@ void Mac::PerformNextOperation(void) if (mOperation != kOperationIdle) { ClearPending(mOperation); - otLogDebgMac("Starting operation \"%s\"", OperationToString(mOperation)); + LogDebg("Starting operation \"%s\"", OperationToString(mOperation)); mTimer.Stop(); // Stop the timer before any non-idle operation, have the operation itself be responsible to // start the timer (if it wants to). } @@ -775,7 +777,7 @@ exit: void Mac::FinishOperation(void) { - otLogDebgMac("Finishing operation \"%s\"", OperationToString(mOperation)); + LogDebg("Finishing operation \"%s\"", OperationToString(mOperation)); mOperation = kOperationIdle; } @@ -789,7 +791,7 @@ TxFrame *Mac::PrepareBeaconRequest(void) frame.SetDstAddr(kShortAddrBroadcast); IgnoreError(frame.SetCommandId(Frame::kMacCmdBeaconRequest)); - otLogInfoMac("Sending Beacon Request"); + LogInfo("Sending Beacon Request"); return &frame; } @@ -1140,7 +1142,7 @@ void Mac::BeginTransmit(void) if (!mRxOnWhenIdle && !mPromiscuous) { mShouldDelaySleep = frame->GetFramePending(); - otLogDebgMac("Delay sleep for pending tx"); + LogDebg("Delay sleep for pending tx"); } #endif @@ -1233,7 +1235,7 @@ void Mac::RecordFrameTransmitStatus(const TxFrame &aFrame, if (aError != kErrorNone) { LogFrameTxFailure(aFrame, aError, aRetryCount, aWillRetx); - otDumpDebgMac("TX ERR", aFrame.GetHeader(), 16); + DumpDebg("TX ERR", aFrame.GetHeader(), 16); if (aWillRetx) { @@ -1386,8 +1388,8 @@ void Mac::HandleTransmitDone(TxFrame &aFrame, RxFrame *aAckFrame, Error aError) if (requriedRadios.Contains(radio) && (aError != kErrorNone)) { - otLogDebgMac("Frame tx failed on required radio link %s with error %s", RadioTypeToString(radio), - ErrorToString(aError)); + LogDebg("Frame tx failed on required radio link %s with error %s", RadioTypeToString(radio), + ErrorToString(aError)); mTxError = aError; } @@ -1430,7 +1432,7 @@ void Mac::HandleTransmitDone(TxFrame &aFrame, RxFrame *aAckFrame, Error aError) StartOperation(kOperationWaitingForData); } - otLogInfoMac("Sent data poll, fp:%s", ToYesNo(framePending)); + LogInfo("Sent data poll, fp:%s", ToYesNo(framePending)); } mCounters.mTxDataPoll++; @@ -1453,7 +1455,7 @@ void Mac::HandleTransmitDone(TxFrame &aFrame, RxFrame *aAckFrame, Error aError) } #endif - otDumpDebgMac("TX", aFrame.GetHeader(), aFrame.GetLength()); + DumpDebg("TX", aFrame.GetHeader(), aFrame.GetLength()); FinishOperation(); Get().HandleSentFrame(aFrame, aError); #if OPENTHREAD_CONFIG_THREAD_VERSION >= OT_THREAD_VERSION_1_2 @@ -1467,7 +1469,7 @@ void Mac::HandleTransmitDone(TxFrame &aFrame, RxFrame *aAckFrame, Error aError) case kOperationTransmitDataCsl: mCounters.mTxData++; - otDumpDebgMac("TX", aFrame.GetHeader(), aFrame.GetLength()); + DumpDebg("TX", aFrame.GetHeader(), aFrame.GetLength()); FinishOperation(); Get().HandleSentFrame(aFrame, aError); PerformNextOperation(); @@ -1488,7 +1490,7 @@ void Mac::HandleTransmitDone(TxFrame &aFrame, RxFrame *aAckFrame, Error aError) } #endif - otDumpDebgMac("TX", aFrame.GetHeader(), aFrame.GetLength()); + DumpDebg("TX", aFrame.GetHeader(), aFrame.GetLength()); FinishOperation(); Get().HandleSentFrame(aFrame, aError); PerformNextOperation(); @@ -1519,7 +1521,7 @@ void Mac::HandleTimer(void) break; case kOperationWaitingForData: - otLogDebgMac("Data poll timeout"); + LogDebg("Data poll timeout"); FinishOperation(); Get().HandlePollTimeout(); PerformNextOperation(); @@ -1531,7 +1533,7 @@ void Mac::HandleTimer(void) #if OPENTHREAD_CONFIG_MAC_STAY_AWAKE_BETWEEN_FRAGMENTS if (mDelayingSleep) { - otLogDebgMac("Sleep delay timeout expired"); + LogDebg("Sleep delay timeout expired"); mDelayingSleep = false; UpdateIdleMode(); } @@ -1568,7 +1570,7 @@ Error Mac::ProcessReceiveSecurity(RxFrame &aFrame, const Address &aSrcAddr, Neig VerifyOrExit(securityLevel == Frame::kSecEncMic32); IgnoreError(aFrame.GetFrameCounter(frameCounter)); - otLogDebgMac("Rx security - frame counter %u", frameCounter); + LogDebg("Rx security - frame counter %u", frameCounter); IgnoreError(aFrame.GetKeyIdMode(keyIdMode)); @@ -1714,7 +1716,7 @@ Error Mac::ProcessEnhAckSecurity(TxFrame &aTxFrame, RxFrame &aAckFrame) VerifyOrExit(txKeyId == ackKeyId); IgnoreError(aAckFrame.GetFrameCounter(frameCounter)); - otLogDebgMac("Rx security - Ack frame counter %u", frameCounter); + LogDebg("Rx security - Ack frame counter %u", frameCounter); IgnoreError(aAckFrame.GetSrcAddr(srcAddr)); @@ -1775,7 +1777,7 @@ Error Mac::ProcessEnhAckSecurity(TxFrame &aTxFrame, RxFrame &aAckFrame) exit: if (error != kErrorNone) { - otLogInfoMac("Frame tx attempt failed, error: Enh-ACK security check fail"); + LogInfo("Frame tx attempt failed, error: Enh-ACK security check fail"); } return error; @@ -1842,7 +1844,7 @@ void Mac::HandleReceivedFrame(RxFrame *aFrame, Error aError) break; case Address::kTypeShort: - otLogDebgMac("Received frame from short address 0x%04x", srcaddr.GetShort()); + LogDebg("Received frame from short address 0x%04x", srcaddr.GetShort()); VerifyOrExit(neighbor != nullptr, error = kErrorUnknownNeighbor); @@ -2005,7 +2007,7 @@ void Mac::HandleReceivedFrame(RxFrame *aFrame, Error aError) if (!mRxOnWhenIdle && !mPromiscuous && aFrame->GetFramePending()) { mShouldDelaySleep = true; - otLogDebgMac("Delay sleep for pending rx"); + LogDebg("Delay sleep for pending rx"); } #endif FinishOperation(); @@ -2043,7 +2045,7 @@ void Mac::HandleReceivedFrame(RxFrame *aFrame, Error aError) ExitNow(); } - otDumpDebgMac("RX", aFrame->GetHeader(), aFrame->GetLength()); + DumpDebg("RX", aFrame->GetHeader(), aFrame->GetLength()); Get().HandleReceivedFrame(*aFrame); UpdateIdleMode(); @@ -2106,7 +2108,7 @@ bool Mac::HandleMacCommand(RxFrame &aFrame) { case Frame::kMacCmdBeaconRequest: mCounters.mRxBeaconRequest++; - otLogInfoMac("Received Beacon Request"); + LogInfo("Received Beacon Request"); if (ShouldSendBeacon()) { @@ -2188,7 +2190,7 @@ void Mac::ResetRetrySuccessHistogram() // LCOV_EXCL_START -#if (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO) && (OPENTHREAD_CONFIG_LOG_MAC == 1) +#if OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO const char *Mac::OperationToString(Operation aOperation) { @@ -2227,28 +2229,28 @@ const char *Mac::OperationToString(Operation aOperation) void Mac::LogFrameRxFailure(const RxFrame *aFrame, Error aError) const { - otLogLevel logLevel; + LogLevel logLevel; switch (aError) { case kErrorAbort: case kErrorNoFrameReceived: case kErrorDestinationAddressFiltered: - logLevel = OT_LOG_LEVEL_DEBG; + logLevel = kLogLevelDebg; break; default: - logLevel = OT_LOG_LEVEL_INFO; + logLevel = kLogLevelInfo; break; } if (aFrame == nullptr) { - otLogMac(logLevel, "Frame rx failed, error:%s", ErrorToString(aError)); + LogAt(logLevel, "Frame rx failed, error:%s", ErrorToString(aError)); } else { - otLogMac(logLevel, "Frame rx failed, error:%s, %s", ErrorToString(aError), aFrame->ToInfoString().AsCString()); + LogAt(logLevel, "Frame rx failed, error:%s, %s", ErrorToString(aError), aFrame->ToInfoString().AsCString()); } } @@ -2265,21 +2267,21 @@ void Mac::LogFrameTxFailure(const TxFrame &aFrame, Error aError, uint8_t aRetryC uint8_t maxAttempts = aFrame.GetMaxFrameRetries() + 1; uint8_t curAttempt = aWillRetx ? (aRetryCount + 1) : maxAttempts; - otLogInfoMac("Frame tx attempt %d/%d failed, error:%s, %s", curAttempt, maxAttempts, ErrorToString(aError), - aFrame.ToInfoString().AsCString()); + LogInfo("Frame tx attempt %d/%d failed, error:%s, %s", curAttempt, maxAttempts, ErrorToString(aError), + aFrame.ToInfoString().AsCString()); } else { - otLogInfoMac("Frame tx failed, error:%s, %s", ErrorToString(aError), aFrame.ToInfoString().AsCString()); + LogInfo("Frame tx failed, error:%s, %s", ErrorToString(aError), aFrame.ToInfoString().AsCString()); } } void Mac::LogBeacon(const char *aActionText, const BeaconPayload &aBeaconPayload) const { - otLogInfoMac("%s Beacon, %s", aActionText, aBeaconPayload.ToInfoString().AsCString()); + LogInfo("%s Beacon, %s", aActionText, aBeaconPayload.ToInfoString().AsCString()); } -#else // #if (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO) && (OPENTHREAD_CONFIG_LOG_MAC == 1) +#else // #if OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO void Mac::LogFrameRxFailure(const RxFrame *, Error) const { @@ -2293,7 +2295,7 @@ void Mac::LogFrameTxFailure(const TxFrame &, Error, uint8_t, bool) const { } -#endif // #if (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO) && (OPENTHREAD_CONFIG_LOG_MAC == 1) +#endif // #if OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO // LCOV_EXCL_STOP @@ -2381,9 +2383,9 @@ void Mac::ProcessCsl(const RxFrame &aFrame, const Address &aSrcAddr) child->SetCslSynchronized(true); child->SetCslLastHeard(TimerMilli::GetNow()); child->SetLastRxTimestamp(aFrame.GetTimestamp()); - otLogDebgMac("Timestamp=%u Sequence=%u CslPeriod=%hu CslPhase=%hu TransmitPhase=%hu", - static_cast(aFrame.GetTimestamp()), aFrame.GetSequence(), csl->GetPeriod(), csl->GetPhase(), - child->GetCslPhase()); + LogDebg("Timestamp=%u Sequence=%u CslPeriod=%hu CslPhase=%hu TransmitPhase=%hu", + static_cast(aFrame.GetTimestamp()), aFrame.GetSequence(), csl->GetPeriod(), csl->GetPhase(), + child->GetCslPhase()); Get().Update(); diff --git a/src/core/mac/mac_frame.cpp b/src/core/mac/mac_frame.cpp index 39334c8aa..5b83c5568 100644 --- a/src/core/mac/mac_frame.cpp +++ b/src/core/mac/mac_frame.cpp @@ -1379,7 +1379,7 @@ exit: // LCOV_EXCL_START -#if (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_NOTE) && (OPENTHREAD_CONFIG_LOG_MAC == 1) +#if OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_NOTE Frame::InfoString Frame::ToInfoString(void) const { @@ -1459,7 +1459,7 @@ BeaconPayload::InfoString BeaconPayload::ToInfoString(void) const return string; } -#endif // #if (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_NOTE) && (OPENTHREAD_CONFIG_LOG_MAC == 1) +#endif // #if OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_NOTE // LCOV_EXCL_STOP diff --git a/src/core/mac/sub_mac.cpp b/src/core/mac/sub_mac.cpp index 0b8fbe71d..73e9ae53a 100644 --- a/src/core/mac/sub_mac.cpp +++ b/src/core/mac/sub_mac.cpp @@ -41,7 +41,7 @@ #include "common/debug.hpp" #include "common/instance.hpp" #include "common/locator_getters.hpp" -#include "common/logging.hpp" +#include "common/log.hpp" #include "common/random.hpp" #include "common/time.hpp" #include "mac/mac_frame.hpp" @@ -49,6 +49,8 @@ namespace ot { namespace Mac { +RegisterLogModule("SubMac"); + SubMac::SubMac(Instance &aInstance) : InstanceLocator(aInstance) , mRadioCaps(Get().GetCaps()) @@ -147,14 +149,14 @@ otRadioCaps SubMac::GetCaps(void) const void SubMac::SetPanId(PanId aPanId) { Get().SetPanId(aPanId); - otLogDebgMac("RadioPanId: 0x%04x", aPanId); + LogDebg("RadioPanId: 0x%04x", aPanId); } void SubMac::SetShortAddress(ShortAddress aShortAddress) { mShortAddress = aShortAddress; Get().SetShortAddress(mShortAddress); - otLogDebgMac("RadioShortAddress: 0x%04x", mShortAddress); + LogDebg("RadioShortAddress: 0x%04x", mShortAddress); } void SubMac::SetExtAddress(const ExtAddress &aExtAddress) @@ -167,7 +169,7 @@ void SubMac::SetExtAddress(const ExtAddress &aExtAddress) address.Set(aExtAddress.m8, ExtAddress::kReverseByteOrder); Get().SetExtendedAddress(address); - otLogDebgMac("RadioExtAddress: %s", mExtAddress.ToString().AsCString()); + LogDebg("RadioExtAddress: %s", mExtAddress.ToString().AsCString()); } void SubMac::SetPcapCallback(otLinkPcapCallback aPcapCallback, void *aCallbackContext) @@ -211,7 +213,7 @@ Error SubMac::Sleep(void) if (error != kErrorNone) { - otLogWarnMac("RadioSleep() failed, error: %s", ErrorToString(error)); + LogWarn("RadioSleep() failed, error: %s", ErrorToString(error)); ExitNow(); } @@ -238,7 +240,7 @@ Error SubMac::Receive(uint8_t aChannel) if (error != kErrorNone) { - otLogWarnMac("RadioReceive() failed, error: %s", ErrorToString(error)); + LogWarn("RadioReceive() failed, error: %s", ErrorToString(error)); ExitNow(); } @@ -283,7 +285,7 @@ Error SubMac::CslSample(uint8_t aPanChannel) exit: if (error != kErrorNone) { - otLogWarnMac("CslSample() failed, error: %s", ErrorToString(error)); + LogWarn("CslSample() failed, error: %s", ErrorToString(error)); } return error; } @@ -312,10 +314,10 @@ void SubMac::HandleReceiveDone(RxFrame *aFrame, Error aError) #if OPENTHREAD_CONFIG_MAC_CSL_DEBUG_ENABLE // Split the log into two lines for RTT to output - otLogDebgMac("Received frame in state (SubMac %s, CSL %s), timestamp %u", StateToString(mState), - CslStateToString(mCslState), static_cast(aFrame->mInfo.mRxInfo.mTimestamp)); - otLogDebgMac("Target sample start time %u, time drift %d", mCslSampleTime.GetValue(), - static_cast(aFrame->mInfo.mRxInfo.mTimestamp) - mCslSampleTime.GetValue()); + LogDebg("Received frame in state (SubMac %s, CSL %s), timestamp %u", StateToString(mState), + CslStateToString(mCslState), static_cast(aFrame->mInfo.mRxInfo.mTimestamp)); + LogDebg("Target sample start time %u, time drift %d", mCslSampleTime.GetValue(), + static_cast(aFrame->mInfo.mRxInfo.mTimestamp) - mCslSampleTime.GetValue()); #endif } #endif // OPENTHREAD_CONFIG_MAC_CSL_RECEIVER_ENABLE @@ -762,7 +764,7 @@ void SubMac::HandleTimer(void) break; case kStateTransmit: - otLogDebgMac("Ack timer timed out"); + LogDebg("Ack timer timed out"); IgnoreError(Get().Receive(mTransmitFrame.GetChannel())); HandleTransmitDone(mTransmitFrame, nullptr, kErrorNoAck); break; @@ -888,7 +890,7 @@ void SubMac::SetState(State aState) { if (mState != aState) { - otLogDebgMac("RadioState: %s -> %s", StateToString(mState), StateToString(aState)); + LogDebg("RadioState: %s -> %s", StateToString(mState), StateToString(aState)); mState = aState; } } @@ -1047,7 +1049,7 @@ void SubMac::SetCslPeriod(uint16_t aPeriod) } } - otLogDebgMac("CSL Period: %u", mCslPeriod); + LogDebg("CSL Period: %u", mCslPeriod); exit: return; @@ -1085,7 +1087,7 @@ void SubMac::HandleCslTimer(void) #if !OPENTHREAD_CONFIG_MAC_CSL_DEBUG_ENABLE IgnoreError(Get().Sleep()); // Don't actually sleep for debugging #endif - otLogDebgMac("CSL sleep %u", mCslTimer.GetNow().GetValue()); + LogDebg("CSL sleep %u", mCslTimer.GetNow().GetValue()); } break; @@ -1114,7 +1116,7 @@ void SubMac::HandleCslTimer(void) else { IgnoreError(Get().Receive(mCslChannel)); - otLogDebgMac("CSL sample %u, duration %u", mCslTimer.GetNow().GetValue(), timeAhead + timeAfter); + LogDebg("CSL sample %u, duration %u", mCslTimer.GetNow().GetValue(), timeAhead + timeAfter); } } break; diff --git a/src/core/meshcop/announce_begin_client.cpp b/src/core/meshcop/announce_begin_client.cpp index a312c38cd..29b7cdbe8 100644 --- a/src/core/meshcop/announce_begin_client.cpp +++ b/src/core/meshcop/announce_begin_client.cpp @@ -40,7 +40,7 @@ #include "common/debug.hpp" #include "common/instance.hpp" #include "common/locator_getters.hpp" -#include "common/logging.hpp" +#include "common/log.hpp" #include "meshcop/meshcop.hpp" #include "meshcop/meshcop_tlvs.hpp" #include "thread/thread_netif.hpp" @@ -48,6 +48,8 @@ namespace ot { +RegisterLogModule("MeshCoP"); + AnnounceBeginClient::AnnounceBeginClient(Instance &aInstance) : InstanceLocator(aInstance) { @@ -85,7 +87,7 @@ Error AnnounceBeginClient::SendRequest(uint32_t aChannelMask, SuccessOrExit(error = Get().SendMessage(*message, messageInfo)); - otLogInfoMeshCoP("sent announce begin query"); + LogInfo("sent announce begin query"); exit: FreeMessageOnError(message, error); diff --git a/src/core/meshcop/border_agent.cpp b/src/core/meshcop/border_agent.cpp index c4a637ba5..c216015f7 100644 --- a/src/core/meshcop/border_agent.cpp +++ b/src/core/meshcop/border_agent.cpp @@ -40,7 +40,7 @@ #include "common/heap.hpp" #include "common/instance.hpp" #include "common/locator_getters.hpp" -#include "common/logging.hpp" +#include "common/log.hpp" #include "meshcop/meshcop.hpp" #include "meshcop/meshcop_tlvs.hpp" #include "thread/thread_netif.hpp" @@ -50,6 +50,8 @@ namespace ot { namespace MeshCoP { +RegisterLogModule("BorderAgent"); + namespace { constexpr uint16_t kBorderAgentUdpPort = OPENTHREAD_CONFIG_BORDER_AGENT_UDP_PORT; ///< UDP port of border agent service. } @@ -191,8 +193,8 @@ void BorderAgent::HandleCoapResponse(ForwardContext &aForwardContext, const Coap Get().AddUnicastAddress(mCommissionerAloc); IgnoreError(Get().AddReceiver(mUdpReceiver)); - otLogInfoMeshCoP("commissioner accepted: session ID=%d, ALOC=%s", sessionId, - mCommissionerAloc.GetAddress().ToString().AsCString()); + LogInfo("commissioner accepted: session ID=%d, ALOC=%s", sessionId, + mCommissionerAloc.GetAddress().ToString().AsCString()); } } @@ -211,7 +213,7 @@ exit: { FreeMessage(message); - otLogWarnMeshCoP("Commissioner request[%hu] failed: %s", aForwardContext.GetMessageId(), ErrorToString(error)); + LogWarn("Commissioner request[%hu] failed: %s", aForwardContext.GetMessageId(), ErrorToString(error)); SendErrorMessage(aForwardContext, error); } @@ -343,7 +345,7 @@ void BorderAgent::HandleProxyTransmit(const Coap::Message &aMessage) SuccessOrExit(error = Get().SendDatagram(*message, messageInfo, Ip6::kProtoUdp)); mUdpProxyPort = tlv.GetSourcePort(); - otLogInfoMeshCoP("Proxy transmit sent to %s", messageInfo.GetPeerAddr().ToString().AsCString()); + LogInfo("Proxy transmit sent to %s", messageInfo.GetPeerAddr().ToString().AsCString()); exit: FreeMessageOnError(message, error); @@ -386,7 +388,7 @@ bool BorderAgent::HandleUdpReceive(const Message &aMessage, const Ip6::MessageIn SuccessOrExit(error = Get().SendMessage(*message, Get().GetMessageInfo())); - otLogInfoMeshCoP("Sent to commissioner on %s", UriPath::kProxyRx); + LogInfo("Sent to commissioner on %s", UriPath::kProxyRx); exit: FreeMessageOnError(message, error); @@ -412,7 +414,7 @@ void BorderAgent::HandleRelayReceive(const Coap::Message &aMessage) } SuccessOrExit(error = ForwardToCommissioner(*message, aMessage)); - otLogInfoMeshCoP("Sent to commissioner on %s", UriPath::kRelayRx); + LogInfo("Sent to commissioner on %s", UriPath::kRelayRx); exit: FreeMessageOnError(message, error); @@ -430,7 +432,7 @@ Error BorderAgent::ForwardToCommissioner(Coap::Message &aForwardMessage, const M SuccessOrExit(error = Get().SendMessage(aForwardMessage, Get().GetMessageInfo())); - otLogInfoMeshCoP("Sent to commissioner"); + LogInfo("Sent to commissioner"); exit: LogError("send to commissioner", error); @@ -478,7 +480,7 @@ void BorderAgent::HandleRelayTransmit(const Coap::Message &aMessage) SuccessOrExit(error = Get().SendMessage(*message, messageInfo)); - otLogInfoMeshCoP("Sent to joiner router request on %s", UriPath::kRelayTx); + LogInfo("Sent to joiner router request on %s", UriPath::kRelayTx); exit: FreeMessageOnError(message, error); @@ -531,7 +533,7 @@ Error BorderAgent::ForwardToLeader(const Coap::Message & aMessage, // HandleCoapResponse is responsible to free this forward context. forwardContext = nullptr; - otLogInfoMeshCoP("Forwarded request to leader on %s", aPath); + LogInfo("Forwarded request to leader on %s", aPath); exit: LogError("forward to leader", error); @@ -559,13 +561,13 @@ void BorderAgent::HandleConnected(bool aConnected) { if (aConnected) { - otLogInfoMeshCoP("Commissioner connected"); + LogInfo("Commissioner connected"); mState = kStateActive; mTimer.Start(kKeepAliveTimeout); } else { - otLogInfoMeshCoP("Commissioner disconnected"); + LogInfo("Commissioner disconnected"); IgnoreError(Get().RemoveReceiver(mUdpReceiver)); Get().RemoveUnicastAddress(mCommissionerAloc); mState = kStateStarted; @@ -609,12 +611,12 @@ void BorderAgent::Start(void) mState = kStateStarted; mUdpProxyPort = 0; - otLogInfoMeshCoP("Border Agent start listening on port %d", kBorderAgentUdpPort); + LogInfo("Border Agent start listening on port %d", kBorderAgentUdpPort); exit: if (error != kErrorNone) { - otLogWarnMeshCoP("failed to start Border Agent on port %d: %s", kBorderAgentUdpPort, ErrorToString(error)); + LogWarn("failed to start Border Agent on port %d: %s", kBorderAgentUdpPort, ErrorToString(error)); } } @@ -628,7 +630,7 @@ void BorderAgent::HandleTimeout(void) if (Get().IsConnected()) { Get().Disconnect(); - otLogWarnMeshCoP("Reset commissioner session"); + LogWarn("Reset commissioner session"); } } @@ -658,7 +660,7 @@ void BorderAgent::Stop(void) mState = kStateStopped; mUdpProxyPort = 0; - otLogInfoMeshCoP("Border Agent stopped"); + LogInfo("Border Agent stopped"); exit: return; diff --git a/src/core/meshcop/commissioner.cpp b/src/core/meshcop/commissioner.cpp index 7789cba8e..cb065993e 100644 --- a/src/core/meshcop/commissioner.cpp +++ b/src/core/meshcop/commissioner.cpp @@ -43,7 +43,7 @@ #include "common/encoding.hpp" #include "common/instance.hpp" #include "common/locator_getters.hpp" -#include "common/logging.hpp" +#include "common/log.hpp" #include "common/string.hpp" #include "meshcop/joiner.hpp" #include "meshcop/joiner_router.hpp" @@ -56,6 +56,8 @@ namespace ot { namespace MeshCoP { +RegisterLogModule("Commissioner"); + Commissioner::Commissioner(Instance &aInstance) : InstanceLocator(aInstance) , mActiveJoiner(nullptr) @@ -96,7 +98,7 @@ void Commissioner::SetState(State aState) SuccessOrExit(Get().Update(mState, aState, kEventCommissionerStateChanged)); - otLogInfoMeshCoP("CommissionerState: %s -> %s", StateToString(oldState), StateToString(aState)); + LogInfo("State: %s -> %s", StateToString(oldState), StateToString(aState)); if (mStateCallback) { @@ -641,7 +643,7 @@ void Commissioner::HandleJoinerExpirationTimer(void) if (joiner.mExpirationTime <= now) { - otLogDebgMeshCoP("removing joiner due to timeout or successfully joined"); + LogDebg("removing joiner due to timeout or successfully joined"); RemoveJoinerEntry(joiner); } } @@ -711,7 +713,7 @@ Error Commissioner::SendMgmtCommissionerGetRequest(const uint8_t *aTlvs, uint8_t SuccessOrExit(error = Get().SendMessage(*message, messageInfo, Commissioner::HandleMgmtCommissionerGetResponse, this)); - otLogInfoMeshCoP("sent MGMT_COMMISSIONER_GET.req to leader"); + LogInfo("sent MGMT_COMMISSIONER_GET.req to leader"); exit: FreeMessageOnError(message, error); @@ -734,7 +736,7 @@ void Commissioner::HandleMgmtCommissionerGetResponse(Coap::Message * aMe OT_UNUSED_VARIABLE(aMessageInfo); VerifyOrExit(aResult == kErrorNone && aMessage->GetCode() == Coap::kCodeChanged); - otLogInfoMeshCoP("received MGMT_COMMISSIONER_GET response"); + LogInfo("received MGMT_COMMISSIONER_GET response"); exit: return; @@ -784,7 +786,7 @@ Error Commissioner::SendMgmtCommissionerSetRequest(const Dataset &aDataset, cons SuccessOrExit(error = Get().SendMessage(*message, messageInfo, Commissioner::HandleMgmtCommissionerSetResponse, this)); - otLogInfoMeshCoP("sent MGMT_COMMISSIONER_SET.req to leader"); + LogInfo("sent MGMT_COMMISSIONER_SET.req to leader"); exit: FreeMessageOnError(message, error); @@ -807,7 +809,7 @@ void Commissioner::HandleMgmtCommissionerSetResponse(Coap::Message * aMe OT_UNUSED_VARIABLE(aMessageInfo); VerifyOrExit(aResult == kErrorNone && aMessage->GetCode() == Coap::kCodeChanged); - otLogInfoMeshCoP("received MGMT_COMMISSIONER_SET response"); + LogInfo("received MGMT_COMMISSIONER_SET response"); exit: return; @@ -838,7 +840,7 @@ Error Commissioner::SendPetition(void) SuccessOrExit( error = Get().SendMessage(*message, messageInfo, Commissioner::HandleLeaderPetitionResponse, this)); - otLogInfoMeshCoP("sent petition"); + LogInfo("sent petition"); exit: FreeMessageOnError(message, error); @@ -867,7 +869,7 @@ void Commissioner::HandleLeaderPetitionResponse(Coap::Message * aMessage VerifyOrExit(aResult == kErrorNone && aMessage->GetCode() == Coap::kCodeChanged, retransmit = (mState == kStatePetition)); - otLogInfoMeshCoP("received Leader Petition response"); + LogInfo("received Leader Petition response"); SuccessOrExit(Tlv::Find(*aMessage, state)); VerifyOrExit(state == StateTlv::kAccept, IgnoreError(Stop(kDoNotSendKeepAlive))); @@ -933,7 +935,7 @@ void Commissioner::SendKeepAlive(uint16_t aSessionId) SuccessOrExit(error = Get().SendMessage(*message, messageInfo, Commissioner::HandleLeaderKeepAliveResponse, this)); - otLogInfoMeshCoP("sent keep alive"); + LogInfo("sent keep alive"); exit: FreeMessageOnError(message, error); @@ -961,7 +963,7 @@ void Commissioner::HandleLeaderKeepAliveResponse(Coap::Message * aMessag VerifyOrExit(aResult == kErrorNone && aMessage->GetCode() == Coap::kCodeChanged, IgnoreError(Stop(kDoNotSendKeepAlive))); - otLogInfoMeshCoP("received Leader keep-alive response"); + LogInfo("received Leader keep-alive response"); SuccessOrExit(Tlv::Find(*aMessage, state)); VerifyOrExit(state == StateTlv::kAccept, IgnoreError(Stop(kDoNotSendKeepAlive))); @@ -1025,7 +1027,7 @@ void Commissioner::HandleRelayReceive(Coap::Message &aMessage, const Ip6::Messag mJoinerPort = joinerPort; mJoinerRloc = joinerRloc; - otLogInfoMeshCoP("Received Relay Receive (%s, 0x%04x)", mJoinerIid.ToString().AsCString(), mJoinerRloc); + LogInfo("Received Relay Receive (%s, 0x%04x)", mJoinerIid.ToString().AsCString(), mJoinerRloc); aMessage.SetOffset(offset); SuccessOrExit(error = aMessage.SetLength(offset + length)); @@ -1049,11 +1051,11 @@ void Commissioner::HandleDatasetChanged(Coap::Message &aMessage, const Ip6::Mess { VerifyOrExit(aMessage.IsConfirmablePostRequest()); - otLogInfoMeshCoP("received dataset changed"); + LogInfo("received dataset changed"); SuccessOrExit(Get().SendEmptyAck(aMessage, aMessageInfo)); - otLogInfoMeshCoP("sent dataset changed acknowledgment"); + LogInfo("sent dataset changed acknowledgment"); exit: return; @@ -1071,7 +1073,7 @@ void Commissioner::HandleJoinerFinalize(Coap::Message &aMessage, const Ip6::Mess StateTlv::State state = StateTlv::kAccept; ProvisioningUrlTlv provisioningUrl; - otLogInfoMeshCoP("received joiner finalize"); + LogInfo("received joiner finalize"); if (Tlv::FindTlv(aMessage, provisioningUrl) == kErrorNone) { @@ -1090,8 +1092,7 @@ void Commissioner::HandleJoinerFinalize(Coap::Message &aMessage, const Ip6::Mess uint8_t buf[OPENTHREAD_CONFIG_MESSAGE_BUFFER_SIZE]; aMessage.ReadBytes(aMessage.GetOffset(), buf, aMessage.GetLength() - aMessage.GetOffset()); - otDumpCertMeshCoP("[THCI] direction=recv | type=JOIN_FIN.req |", buf, - aMessage.GetLength() - aMessage.GetOffset()); + DumpCert("[THCI] direction=recv | type=JOIN_FIN.req |", buf, aMessage.GetLength() - aMessage.GetOffset()); } #endif @@ -1122,7 +1123,7 @@ void Commissioner::SendJoinFinalizeResponse(const Coap::Message &aRequest, State VerifyOrExit(message->GetLength() <= sizeof(buf)); message->ReadBytes(message->GetOffset(), buf, message->GetLength() - message->GetOffset()); - otDumpCertMeshCoP("[THCI] direction=send | type=JOIN_FIN.rsp |", buf, message->GetLength() - message->GetOffset()); + DumpCert("[THCI] direction=send | type=JOIN_FIN.rsp |", buf, message->GetLength() - message->GetOffset()); #endif SuccessOrExit(error = Get().SendMessage(*message, joinerMessageInfo)); @@ -1135,7 +1136,7 @@ void Commissioner::SendJoinFinalizeResponse(const Coap::Message &aRequest, State RemoveJoiner(*mActiveJoiner, kRemoveJoinerDelay); } - otLogInfoMeshCoP("sent joiner finalize response"); + LogInfo("sent joiner finalize response"); exit: FreeMessageOnError(message, error); @@ -1209,7 +1210,7 @@ exit: // LCOV_EXCL_START -#if (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO) && (OPENTHREAD_CONFIG_LOG_MESHCOP == 1) +#if OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO const char *Commissioner::StateToString(State aState) { @@ -1234,17 +1235,17 @@ void Commissioner::LogJoinerEntry(const char *aAction, const Joiner &aJoiner) co break; case Joiner::kTypeAny: - otLogInfoMeshCoP("%s Joiner (any, %s)", aAction, aJoiner.mPskd.GetAsCString()); + LogInfo("%s Joiner (any, %s)", aAction, aJoiner.mPskd.GetAsCString()); break; case Joiner::kTypeEui64: - otLogInfoMeshCoP("%s Joiner (eui64:%s, %s)", aAction, aJoiner.mSharedId.mEui64.ToString().AsCString(), - aJoiner.mPskd.GetAsCString()); + LogInfo("%s Joiner (eui64:%s, %s)", aAction, aJoiner.mSharedId.mEui64.ToString().AsCString(), + aJoiner.mPskd.GetAsCString()); break; case Joiner::kTypeDiscerner: - otLogInfoMeshCoP("%s Joiner (disc:%s, %s)", aAction, aJoiner.mSharedId.mDiscerner.ToString().AsCString(), - aJoiner.mPskd.GetAsCString()); + LogInfo("%s Joiner (disc:%s, %s)", aAction, aJoiner.mSharedId.mDiscerner.ToString().AsCString(), + aJoiner.mPskd.GetAsCString()); break; } } @@ -1255,7 +1256,7 @@ void Commissioner::LogJoinerEntry(const char *, const Joiner &) const { } -#endif // (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO) && (OPENTHREAD_CONFIG_LOG_MESHCOP == 1) +#endif // OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO // LCOV_EXCL_STOP diff --git a/src/core/meshcop/dataset.cpp b/src/core/meshcop/dataset.cpp index cbff80149..ff3b9f54e 100644 --- a/src/core/meshcop/dataset.cpp +++ b/src/core/meshcop/dataset.cpp @@ -40,7 +40,7 @@ #include "common/encoding.hpp" #include "common/instance.hpp" #include "common/locator_getters.hpp" -#include "common/logging.hpp" +#include "common/log.hpp" #include "mac/mac_types.hpp" #include "meshcop/meshcop_tlvs.hpp" #include "thread/mle_tlvs.hpp" @@ -48,6 +48,8 @@ namespace ot { namespace MeshCoP { +RegisterLogModule("Dataset"); + Error Dataset::Info::GenerateRandom(Instance &aInstance) { Error error; @@ -539,8 +541,7 @@ Error Dataset::ApplyConfiguration(Instance &aInstance, bool *aIsNetworkKeyUpdate if (error != kErrorNone) { - otLogWarnMeshCoP("DatasetManager::ApplyConfiguration() Failed to set channel to %d (%s)", channel, - ErrorToString(error)); + LogWarn("ApplyConfiguration() Failed to set channel to %d (%s)", channel, ErrorToString(error)); ExitNow(); } diff --git a/src/core/meshcop/dataset_local.cpp b/src/core/meshcop/dataset_local.cpp index 78e6f610d..0b8b39e29 100644 --- a/src/core/meshcop/dataset_local.cpp +++ b/src/core/meshcop/dataset_local.cpp @@ -39,7 +39,7 @@ #include "common/code_utils.hpp" #include "common/instance.hpp" #include "common/locator_getters.hpp" -#include "common/logging.hpp" +#include "common/log.hpp" #include "common/settings.hpp" #include "crypto/storage.hpp" #include "meshcop/dataset.hpp" @@ -49,6 +49,8 @@ namespace ot { namespace MeshCoP { +RegisterLogModule("DatasetLocal"); + DatasetLocal::DatasetLocal(Instance &aInstance, Dataset::Type aType) : InstanceLocator(aInstance) , mUpdateTime(0) @@ -189,7 +191,7 @@ Error DatasetLocal::Save(const Dataset &aDataset) // do not propagate error back IgnoreError(Get().DeleteOperationalDataset(IsActive())); mSaved = false; - otLogInfoMeshCoP("%s dataset deleted", Dataset::TypeToString(mType)); + LogInfo("%s dataset deleted", Dataset::TypeToString(mType)); } else { @@ -205,7 +207,7 @@ Error DatasetLocal::Save(const Dataset &aDataset) #endif mSaved = true; - otLogInfoMeshCoP("%s dataset set", Dataset::TypeToString(mType)); + LogInfo("%s dataset set", Dataset::TypeToString(mType)); } mTimestampPresent = (aDataset.GetTimestamp(mType, mTimestamp) == kErrorNone); diff --git a/src/core/meshcop/dataset_manager.cpp b/src/core/meshcop/dataset_manager.cpp index 4bb845c8b..c6419565a 100644 --- a/src/core/meshcop/dataset_manager.cpp +++ b/src/core/meshcop/dataset_manager.cpp @@ -39,7 +39,7 @@ #include "common/as_core_type.hpp" #include "common/instance.hpp" #include "common/locator_getters.hpp" -#include "common/logging.hpp" +#include "common/log.hpp" #include "common/notifier.hpp" #include "meshcop/meshcop.hpp" #include "meshcop/meshcop_tlvs.hpp" @@ -51,6 +51,8 @@ namespace ot { namespace MeshCoP { +RegisterLogModule("DatasetManager"); + DatasetManager::DatasetManager(Instance &aInstance, Dataset::Type aType, Timer::Handler aTimerHandler) : InstanceLocator(aInstance) , mLocal(aInstance, aType) @@ -291,7 +293,7 @@ void DatasetManager::SendSet(void) SuccessOrExit( error = Get().SendMessage(*message, messageInfo, &DatasetManager::HandleMgmtSetResponse, this)); - otLogInfoMeshCoP("Sent %s set to leader", Dataset::TypeToString(GetType())); + LogInfo("Sent %s set to leader", Dataset::TypeToString(GetType())); exit: @@ -345,7 +347,7 @@ void DatasetManager::HandleMgmtSetResponse(Coap::Message *aMessage, const Ip6::M } exit: - otLogInfoMeshCoP("MGMT_SET finished: %s", ErrorToString(error)); + LogInfo("MGMT_SET finished: %s", ErrorToString(error)); mMgmtPending = false; @@ -454,8 +456,8 @@ void DatasetManager::SendGetResponse(const Coap::Message & aRequest, SuccessOrExit(error = Get().SendMessage(*message, aMessageInfo)); - otLogInfoMeshCoP("sent %s dataset get response to %s", (GetType() == Dataset::kActive ? "active" : "pending"), - aMessageInfo.GetPeerAddr().ToString().AsCString()); + LogInfo("sent %s dataset get response to %s", (GetType() == Dataset::kActive ? "active" : "pending"), + aMessageInfo.GetPeerAddr().ToString().AsCString()); exit: FreeMessageOnError(message, error); @@ -533,7 +535,7 @@ Error DatasetManager::SendSetRequest(const Dataset::Info & aDatasetInfo, mMgmtSetCallbackContext = aContext; mMgmtPending = true; - otLogInfoMeshCoP("sent dataset set request to leader"); + LogInfo("sent dataset set request to leader"); exit: FreeMessageOnError(message, error); @@ -654,7 +656,7 @@ Error DatasetManager::SendGetRequest(const Dataset::Components &aDatasetComponen messageInfo.SetPeerPort(Tmf::kUdpPort); SuccessOrExit(error = Get().SendMessage(*message, messageInfo)); - otLogInfoMeshCoP("sent dataset get request"); + LogInfo("sent dataset get request"); exit: FreeMessageOnError(message, error); @@ -811,7 +813,7 @@ void PendingDataset::StartDelayTimer(void) } mDelayTimer.StartAt(dataset.GetUpdateTime(), delay); - otLogInfoMeshCoP("delay timer started %d", delay); + LogInfo("delay timer started %d", delay); } } @@ -841,7 +843,7 @@ void PendingDataset::HandleDelayTimer(void) } } - otLogInfoMeshCoP("pending delay timer expired"); + LogInfo("pending delay timer expired"); dataset.ConvertToActive(); diff --git a/src/core/meshcop/dataset_manager_ftd.cpp b/src/core/meshcop/dataset_manager_ftd.cpp index 7447b172b..2e5b58ce4 100644 --- a/src/core/meshcop/dataset_manager_ftd.cpp +++ b/src/core/meshcop/dataset_manager_ftd.cpp @@ -46,7 +46,7 @@ #include "common/debug.hpp" #include "common/instance.hpp" #include "common/locator_getters.hpp" -#include "common/logging.hpp" +#include "common/log.hpp" #include "common/random.hpp" #include "common/timer.hpp" #include "meshcop/dataset.hpp" @@ -60,6 +60,8 @@ namespace ot { namespace MeshCoP { +RegisterLogModule("DatasetManager"); + Error DatasetManager::AppendMleDatasetTlv(Message &aMessage) const { Dataset dataset; @@ -277,7 +279,7 @@ void DatasetManager::SendSetResponse(const Coap::Message & aRequest, SuccessOrExit(error = Get().SendMessage(*message, aMessageInfo)); - otLogInfoMeshCoP("sent dataset set response"); + LogInfo("sent dataset set response"); exit: FreeMessageOnError(message, error); @@ -388,7 +390,7 @@ Error ActiveDataset::GenerateLocal(void) SuccessOrExit(error = mLocal.Save(dataset)); IgnoreError(Restore()); - otLogInfoMeshCoP("Generated local dataset"); + LogInfo("Generated local dataset"); exit: return error; diff --git a/src/core/meshcop/dataset_updater.cpp b/src/core/meshcop/dataset_updater.cpp index e0a6222ab..c3c97662d 100644 --- a/src/core/meshcop/dataset_updater.cpp +++ b/src/core/meshcop/dataset_updater.cpp @@ -39,7 +39,7 @@ #include "common/code_utils.hpp" #include "common/instance.hpp" #include "common/locator_getters.hpp" -#include "common/logging.hpp" +#include "common/log.hpp" #include "common/random.hpp" namespace ot { diff --git a/src/core/meshcop/dtls.cpp b/src/core/meshcop/dtls.cpp index 12a43032c..7e0fc598d 100644 --- a/src/core/meshcop/dtls.cpp +++ b/src/core/meshcop/dtls.cpp @@ -46,7 +46,7 @@ #include "common/encoding.hpp" #include "common/instance.hpp" #include "common/locator_getters.hpp" -#include "common/logging.hpp" +#include "common/log.hpp" #include "common/timer.hpp" #include "crypto/mbedtls.hpp" #include "crypto/sha256.hpp" @@ -57,6 +57,8 @@ namespace ot { namespace MeshCoP { +RegisterLogModule("Dtls"); + const mbedtls_ecp_group_id Dtls::sCurves[] = {MBEDTLS_ECP_DP_SECP256R1, MBEDTLS_ECP_DP_NONE}; #if defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED) || defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED) const int Dtls::sHashes[] = {MBEDTLS_MD_SHA256, MBEDTLS_MD_NONE}; @@ -338,12 +340,12 @@ Error Dtls::Setup(bool aClient) if (mCipherSuites[0] == MBEDTLS_TLS_ECJPAKE_WITH_AES_128_CCM_8) { - otLogInfoMeshCoP("DTLS started"); + LogInfo("DTLS started"); } #if OPENTHREAD_CONFIG_COAP_SECURE_API_ENABLE else { - otLogInfoCoap("Application Coap Secure DTLS started"); + LogInfo("Application Coap Secure DTLS started"); } #endif @@ -408,7 +410,7 @@ int Dtls::SetApplicationCoapSecureKeys(void) break; default: - otLogCritCoap("Application Coap Secure DTLS: Not supported cipher."); + LogCrit("Application Coap Secure: Not supported cipher."); rval = MBEDTLS_ERR_SSL_BAD_INPUT_DATA; ExitNow(); break; @@ -590,12 +592,12 @@ int Dtls::HandleMbedtlsTransmit(const unsigned char *aBuf, size_t aLength) if (mCipherSuites[0] == MBEDTLS_TLS_ECJPAKE_WITH_AES_128_CCM_8) { - otLogDebgMeshCoP("Dtls::HandleMbedtlsTransmit"); + LogDebg("HandleMbedtlsTransmit"); } #if OPENTHREAD_CONFIG_COAP_SECURE_API_ENABLE else { - otLogDebgCoap("Dtls::ApplicationCoapSecure HandleMbedtlsTransmit"); + LogDebg("ApplicationCoapSecure HandleMbedtlsTransmit"); } #endif @@ -615,7 +617,7 @@ int Dtls::HandleMbedtlsTransmit(const unsigned char *aBuf, size_t aLength) break; default: - otLogWarnMeshCoP("Dtls::HandleMbedtlsTransmit: %s error", ErrorToString(error)); + LogWarn("HandleMbedtlsTransmit: %s error", ErrorToString(error)); rval = MBEDTLS_ERR_NET_SEND_FAILED; break; } @@ -634,12 +636,12 @@ int Dtls::HandleMbedtlsReceive(unsigned char *aBuf, size_t aLength) if (mCipherSuites[0] == MBEDTLS_TLS_ECJPAKE_WITH_AES_128_CCM_8) { - otLogDebgMeshCoP("Dtls::HandleMbedtlsReceive"); + LogDebg("HandleMbedtlsReceive"); } #if OPENTHREAD_CONFIG_COAP_SECURE_API_ENABLE else { - otLogDebgCoap("Dtls:: ApplicationCoapSecure HandleMbedtlsReceive"); + LogDebg("ApplicationCoapSecure HandleMbedtlsReceive"); } #endif @@ -669,12 +671,12 @@ int Dtls::HandleMbedtlsGetTimer(void) if (mCipherSuites[0] == MBEDTLS_TLS_ECJPAKE_WITH_AES_128_CCM_8) { - otLogDebgMeshCoP("Dtls::HandleMbedtlsGetTimer"); + LogDebg("HandleMbedtlsGetTimer"); } #if OPENTHREAD_CONFIG_COAP_SECURE_API_ENABLE else { - otLogDebgCoap("Dtls:: ApplicationCoapSecure HandleMbedtlsGetTimer"); + LogDebg("ApplicationCoapSecure HandleMbedtlsGetTimer"); } #endif @@ -707,12 +709,12 @@ void Dtls::HandleMbedtlsSetTimer(uint32_t aIntermediate, uint32_t aFinish) { if (mCipherSuites[0] == MBEDTLS_TLS_ECJPAKE_WITH_AES_128_CCM_8) { - otLogDebgMeshCoP("Dtls::SetTimer"); + LogDebg("SetTimer"); } #if OPENTHREAD_CONFIG_COAP_SECURE_API_ENABLE else { - otLogDebgCoap("Dtls::ApplicationCoapSecure SetTimer"); + LogDebg("ApplicationCoapSecure SetTimer"); } #endif @@ -769,7 +771,7 @@ void Dtls::HandleMbedtlsExportKeys(mbedtls_ssl_key_export_type aType, sha256.Update(keyBlock, kDtlsKeyBlockSize); sha256.Finish(kek); - otLogDebgMeshCoP("Generated KEK"); + LogDebg("Generated KEK"); Get().SetKek(kek.GetBytes()); exit: @@ -806,7 +808,7 @@ int Dtls::HandleMbedtlsExportKeys(const unsigned char *aMasterSecret, sha256.Update(aKeyBlock, 2 * static_cast(aMacLength + aKeyLength + aIvLength)); sha256.Finish(kek); - otLogDebgMeshCoP("Generated KEK"); + LogDebg("Generated KEK"); Get().SetKek(kek.GetBytes()); exit: @@ -952,20 +954,20 @@ void Dtls::HandleMbedtlsDebug(int aLevel, const char *aFile, int aLine, const ch switch (aLevel) { case 1: - otLogCritMbedTls("[%hu] %s", mSocket.GetSockName().mPort, aStr); + LogCrit("[%hu] %s", mSocket.GetSockName().mPort, aStr); break; case 2: - otLogWarnMbedTls("[%hu] %s", mSocket.GetSockName().mPort, aStr); + LogWarn("[%hu] %s", mSocket.GetSockName().mPort, aStr); break; case 3: - otLogInfoMbedTls("[%hu] %s", mSocket.GetSockName().mPort, aStr); + LogInfo("[%hu] %s", mSocket.GetSockName().mPort, aStr); break; case 4: default: - otLogDebgMbedTls("[%hu] %s", mSocket.GetSockName().mPort, aStr); + LogDebg("[%hu] %s", mSocket.GetSockName().mPort, aStr); break; } } diff --git a/src/core/meshcop/energy_scan_client.cpp b/src/core/meshcop/energy_scan_client.cpp index e2273651c..9c178ba7d 100644 --- a/src/core/meshcop/energy_scan_client.cpp +++ b/src/core/meshcop/energy_scan_client.cpp @@ -42,7 +42,7 @@ #include "common/encoding.hpp" #include "common/instance.hpp" #include "common/locator_getters.hpp" -#include "common/logging.hpp" +#include "common/log.hpp" #include "meshcop/meshcop.hpp" #include "meshcop/meshcop_tlvs.hpp" #include "thread/thread_netif.hpp" @@ -50,6 +50,8 @@ namespace ot { +RegisterLogModule("EnergyScanClnt"); + EnergyScanClient::EnergyScanClient(Instance &aInstance) : InstanceLocator(aInstance) , mCallback(nullptr) @@ -94,7 +96,7 @@ Error EnergyScanClient::SendQuery(uint32_t aChannelMas messageInfo.SetPeerPort(Tmf::kUdpPort); SuccessOrExit(error = Get().SendMessage(*message, messageInfo)); - otLogInfoMeshCoP("sent energy scan query"); + LogInfo("sent query"); mCallback = aCallback; mContext = aContext; @@ -122,7 +124,7 @@ void EnergyScanClient::HandleReport(Coap::Message &aMessage, const Ip6::MessageI VerifyOrExit(aMessage.IsConfirmablePostRequest()); - otLogInfoMeshCoP("received energy scan report"); + LogInfo("received report"); VerifyOrExit((mask = MeshCoP::ChannelMaskTlv::GetChannelMask(aMessage)) != 0); @@ -136,7 +138,7 @@ void EnergyScanClient::HandleReport(Coap::Message &aMessage, const Ip6::MessageI SuccessOrExit(Get().SendEmptyAck(aMessage, aMessageInfo)); - otLogInfoMeshCoP("sent energy scan report response"); + LogInfo("sent report response"); exit: return; diff --git a/src/core/meshcop/joiner.cpp b/src/core/meshcop/joiner.cpp index e05a2bdbb..9d67941c4 100644 --- a/src/core/meshcop/joiner.cpp +++ b/src/core/meshcop/joiner.cpp @@ -44,7 +44,7 @@ #include "common/encoding.hpp" #include "common/instance.hpp" #include "common/locator_getters.hpp" -#include "common/logging.hpp" +#include "common/log.hpp" #include "common/string.hpp" #include "meshcop/meshcop.hpp" #include "radio/radio.hpp" @@ -55,6 +55,8 @@ namespace ot { namespace MeshCoP { +RegisterLogModule("Joiner"); + Joiner::Joiner(Instance &aInstance) : InstanceLocator(aInstance) , mId() @@ -121,7 +123,7 @@ void Joiner::SetState(State aState) SuccessOrExit(Get().Update(mState, aState, kEventJoinerStateChanged)); - otLogInfoMeshCoP("JoinerState: %s -> %s", StateToString(oldState), StateToString(aState)); + LogInfo("JoinerState: %s -> %s", StateToString(oldState), StateToString(aState)); exit: return; } @@ -140,7 +142,7 @@ Error Joiner::Start(const char * aPskd, Mac::ExtAddress randomAddress; SteeringData::HashBitIndexes filterIndexes; - otLogInfoMeshCoP("Joiner starting"); + LogInfo("Joiner starting"); VerifyOrExit(aProvisioningUrl == nullptr || IsValidUtf8String(aProvisioningUrl), error = kErrorInvalidArgs); VerifyOrExit(aVendorName == nullptr || IsValidUtf8String(aVendorName), error = kErrorInvalidArgs); @@ -197,7 +199,7 @@ exit: void Joiner::Stop(void) { - otLogInfoMeshCoP("Joiner stopped"); + LogInfo("Joiner stopped"); // Callback is set to `nullptr` to skip calling it from `Finish()` mCallback = nullptr; @@ -308,9 +310,9 @@ void Joiner::SaveDiscoveredJoinerRouter(const Mle::DiscoverScanner::ScanResult & doesAllowAny = AsCoreType(&aResult.mSteeringData).PermitsAllJoiners(); - otLogInfoMeshCoP("Joiner discover network: %s, pan:0x%04x, port:%d, chan:%d, rssi:%d, allow-any:%s", - AsCoreType(&aResult.mExtAddress).ToString().AsCString(), aResult.mPanId, aResult.mJoinerUdpPort, - aResult.mChannel, aResult.mRssi, ToYesNo(doesAllowAny)); + LogInfo("Joiner discover network: %s, pan:0x%04x, port:%d, chan:%d, rssi:%d, allow-any:%s", + AsCoreType(&aResult.mExtAddress).ToString().AsCString(), aResult.mPanId, aResult.mJoinerUdpPort, + aResult.mChannel, aResult.mRssi, ToYesNo(doesAllowAny)); priority = CalculatePriority(aResult.mRssi, doesAllowAny); @@ -385,8 +387,8 @@ Error Joiner::Connect(JoinerRouter &aRouter) Error error = kErrorNotFound; Ip6::SockAddr sockAddr(aRouter.mJoinerUdpPort); - otLogInfoMeshCoP("Joiner connecting to %s, pan:0x%04x, chan:%d", aRouter.mExtAddr.ToString().AsCString(), - aRouter.mPanId, aRouter.mChannel); + LogInfo("Joiner connecting to %s, pan:0x%04x, chan:%d", aRouter.mExtAddr.ToString().AsCString(), aRouter.mPanId, + aRouter.mChannel); Get().SetPanId(aRouter.mPanId); SuccessOrExit(error = Get().SetPanChannel(aRouter.mChannel)); @@ -515,7 +517,7 @@ void Joiner::SendJoinerFinalize(void) SuccessOrExit(Get().SendMessage(*mFinalizeMessage, Joiner::HandleJoinerFinalizeResponse, this)); mFinalizeMessage = nullptr; - otLogInfoMeshCoP("Joiner sent finalize"); + LogInfo("Joiner sent finalize"); exit: return; @@ -546,7 +548,7 @@ void Joiner::HandleJoinerFinalizeResponse(Coap::Message *aMessage, const Ip6::Me SetState(kStateEntrust); mTimer.Start(kReponseTimeout); - otLogInfoMeshCoP("Joiner received finalize response %d", state); + LogInfo("Joiner received finalize response %d", state); #if OPENTHREAD_CONFIG_REFERENCE_DEVICE_ENABLE LogCertMessage("[THCI] direction=recv | type=JOIN_FIN.rsp |", *aMessage); @@ -569,8 +571,8 @@ void Joiner::HandleJoinerEntrust(Coap::Message &aMessage, const Ip6::MessageInfo VerifyOrExit(mState == kStateEntrust && aMessage.IsConfirmablePostRequest(), error = kErrorDrop); - otLogInfoMeshCoP("Joiner received entrust"); - otLogCertMeshCoP("[THCI] direction=recv | type=JOIN_ENT.ntf"); + LogInfo("Joiner received entrust"); + LogCert("[THCI] direction=recv | type=JOIN_ENT.ntf"); datasetInfo.Clear(); @@ -581,7 +583,7 @@ void Joiner::HandleJoinerEntrust(Coap::Message &aMessage, const Ip6::MessageInfo IgnoreError(Get().Save(datasetInfo)); - otLogInfoMeshCoP("Joiner successful!"); + LogInfo("Joiner successful!"); SendJoinerEntrustResponse(aMessage, aMessageInfo); @@ -607,8 +609,8 @@ void Joiner::SendJoinerEntrustResponse(const Coap::Message &aRequest, const Ip6: SetState(kStateJoined); - otLogInfoMeshCoP("Joiner sent entrust response"); - otLogCertMeshCoP("[THCI] direction=send | type=JOIN_ENT.rsp"); + LogInfo("Joiner sent entrust response"); + LogCert("[THCI] direction=send | type=JOIN_ENT.rsp"); exit: FreeMessageOnError(message, error); @@ -676,12 +678,14 @@ const char *Joiner::StateToString(State aState) #if OPENTHREAD_CONFIG_REFERENCE_DEVICE_ENABLE void Joiner::LogCertMessage(const char *aText, const Coap::Message &aMessage) const { + OT_UNUSED_VARIABLE(aText); + uint8_t buf[OPENTHREAD_CONFIG_MESSAGE_BUFFER_SIZE]; VerifyOrExit(aMessage.GetLength() <= sizeof(buf)); aMessage.ReadBytes(aMessage.GetOffset(), buf, aMessage.GetLength() - aMessage.GetOffset()); - otDumpCertMeshCoP(aText, buf, aMessage.GetLength() - aMessage.GetOffset()); + DumpCert(aText, buf, aMessage.GetLength() - aMessage.GetOffset()); exit: return; diff --git a/src/core/meshcop/joiner.hpp b/src/core/meshcop/joiner.hpp index 0a1ebd887..ac894e97c 100644 --- a/src/core/meshcop/joiner.hpp +++ b/src/core/meshcop/joiner.hpp @@ -45,7 +45,7 @@ #include "coap/coap_secure.hpp" #include "common/as_core_type.hpp" #include "common/locator.hpp" -#include "common/logging.hpp" +#include "common/log.hpp" #include "common/message.hpp" #include "common/non_copyable.hpp" #include "mac/mac_types.hpp" diff --git a/src/core/meshcop/joiner_router.cpp b/src/core/meshcop/joiner_router.cpp index 5247b661a..26d2102bf 100644 --- a/src/core/meshcop/joiner_router.cpp +++ b/src/core/meshcop/joiner_router.cpp @@ -42,7 +42,7 @@ #include "common/encoding.hpp" #include "common/instance.hpp" #include "common/locator_getters.hpp" -#include "common/logging.hpp" +#include "common/log.hpp" #include "meshcop/meshcop.hpp" #include "meshcop/meshcop_tlvs.hpp" #include "thread/mle.hpp" @@ -52,6 +52,8 @@ namespace ot { namespace MeshCoP { +RegisterLogModule("JoinerRouter"); + JoinerRouter::JoinerRouter(Instance &aInstance) : InstanceLocator(aInstance) , mSocket(aInstance) @@ -84,7 +86,7 @@ void JoinerRouter::Start(void) IgnoreError(mSocket.Open(&JoinerRouter::HandleUdpReceive, this)); IgnoreError(mSocket.Bind(port)); IgnoreError(Get().AddUnsecurePort(port)); - otLogInfoMeshCoP("Joiner Router: start"); + LogInfo("Joiner Router: start"); } else { @@ -136,7 +138,7 @@ void JoinerRouter::HandleUdpReceive(Message &aMessage, const Ip6::MessageInfo &a uint16_t borderAgentRloc; uint16_t offset; - otLogInfoMeshCoP("JoinerRouter::HandleUdpReceive"); + LogInfo("JoinerRouter::HandleUdpReceive"); SuccessOrExit(error = GetBorderAgentRloc(Get(), borderAgentRloc)); @@ -163,7 +165,7 @@ void JoinerRouter::HandleUdpReceive(Message &aMessage, const Ip6::MessageInfo &a SuccessOrExit(error = Get().SendMessage(*message, messageInfo)); - otLogInfoMeshCoP("Sent relay rx"); + LogInfo("Sent relay rx"); exit: FreeMessageOnError(message, error); @@ -190,7 +192,7 @@ void JoinerRouter::HandleRelayTransmit(Coap::Message &aMessage, const Ip6::Messa VerifyOrExit(aMessage.IsNonConfirmablePostRequest(), error = kErrorDrop); - otLogInfoMeshCoP("Received relay transmit"); + LogInfo("Received relay transmit"); SuccessOrExit(error = Tlv::Find(aMessage, joinerPort)); SuccessOrExit(error = Tlv::Find(aMessage, joinerIid)); @@ -209,7 +211,7 @@ void JoinerRouter::HandleRelayTransmit(Coap::Message &aMessage, const Ip6::Messa if (Tlv::Find(aMessage, kek) == kErrorNone) { - otLogInfoMeshCoP("Received kek"); + LogInfo("Received kek"); DelaySendingJoinerEntrust(messageInfo, kek); } @@ -295,12 +297,12 @@ Error JoinerRouter::SendJoinerEntrust(const Ip6::MessageInfo &aMessageInfo) IgnoreError(Get().AbortTransaction(&JoinerRouter::HandleJoinerEntrustResponse, this)); - otLogInfoMeshCoP("Sending JOIN_ENT.ntf"); + LogInfo("Sending JOIN_ENT.ntf"); SuccessOrExit(error = Get().SendMessage(*message, aMessageInfo, &JoinerRouter::HandleJoinerEntrustResponse, this)); - otLogInfoMeshCoP("Sent joiner entrust length = %d", message->GetLength()); - otLogCertMeshCoP("[THCI] direction=send | type=JOIN_ENT.ntf"); + LogInfo("Sent joiner entrust length = %d", message->GetLength()); + LogCert("[THCI] direction=send | type=JOIN_ENT.ntf"); exit: FreeMessageOnError(message, error); @@ -406,8 +408,8 @@ void JoinerRouter::HandleJoinerEntrustResponse(Coap::Message * aMessage, VerifyOrExit(aMessage->GetCode() == Coap::kCodeChanged); - otLogInfoMeshCoP("Receive joiner entrust response"); - otLogCertMeshCoP("[THCI] direction=recv | type=JOIN_ENT.rsp"); + LogInfo("Receive joiner entrust response"); + LogCert("[THCI] direction=recv | type=JOIN_ENT.rsp"); exit: return; diff --git a/src/core/meshcop/meshcop.cpp b/src/core/meshcop/meshcop.cpp index 121144a7f..d561029d9 100644 --- a/src/core/meshcop/meshcop.cpp +++ b/src/core/meshcop/meshcop.cpp @@ -36,7 +36,7 @@ #include "common/crc16.hpp" #include "common/debug.hpp" #include "common/locator_getters.hpp" -#include "common/logging.hpp" +#include "common/log.hpp" #include "common/string.hpp" #include "crypto/pbkdf2_cmac.hpp" #include "crypto/sha256.hpp" @@ -44,6 +44,9 @@ #include "thread/thread_netif.hpp" namespace ot { + +RegisterLogModule("MeshCoP"); + namespace MeshCoP { Error JoinerPskd::SetFrom(const char *aPskdString) @@ -354,12 +357,12 @@ exit: } #endif // OPENTHREAD_FTD -#if (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_WARN) && (OPENTHREAD_CONFIG_LOG_MESHCOP == 1) +#if OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_WARN void LogError(const char *aActionText, Error aError) { if (aError != kErrorNone) { - otLogWarnMeshCoP("Failed to %s: %s", aActionText, ErrorToString(aError)); + LogWarn("Failed to %s: %s", aActionText, ErrorToString(aError)); } } #endif diff --git a/src/core/meshcop/meshcop.hpp b/src/core/meshcop/meshcop.hpp index 5598372ea..2cd3a8ee7 100644 --- a/src/core/meshcop/meshcop.hpp +++ b/src/core/meshcop/meshcop.hpp @@ -445,7 +445,7 @@ void ComputeJoinerId(const Mac::ExtAddress &aEui64, Mac::ExtAddress &aJoinerId); */ Error GetBorderAgentRloc(ThreadNetif &aNetIf, uint16_t &aRloc); -#if (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_WARN) && (OPENTHREAD_CONFIG_LOG_MESHCOP == 1) +#if OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_WARN /** * This function emits a log message indicating an error during a MeshCoP action. * diff --git a/src/core/meshcop/meshcop_leader.cpp b/src/core/meshcop/meshcop_leader.cpp index 570a80c03..f1f6a9f92 100644 --- a/src/core/meshcop/meshcop_leader.cpp +++ b/src/core/meshcop/meshcop_leader.cpp @@ -42,7 +42,7 @@ #include "common/code_utils.hpp" #include "common/instance.hpp" #include "common/locator_getters.hpp" -#include "common/logging.hpp" +#include "common/log.hpp" #include "common/random.hpp" #include "meshcop/meshcop.hpp" #include "meshcop/meshcop_tlvs.hpp" @@ -53,6 +53,8 @@ namespace ot { namespace MeshCoP { +RegisterLogModule("MeshCoPLeader"); + Leader::Leader(Instance &aInstance) : InstanceLocator(aInstance) , mPetition(UriPath::kLeaderPetition, Leader::HandlePetition, this) @@ -78,7 +80,7 @@ void Leader::HandlePetition(Coap::Message &aMessage, const Ip6::MessageInfo &aMe CommissionerIdTlv commissionerId; StateTlv::State state = StateTlv::kReject; - otLogInfoMeshCoP("received petition"); + LogInfo("received petition"); VerifyOrExit(Get().IsRoutingLocator(aMessageInfo.GetPeerAddr())); SuccessOrExit(Tlv::FindTlv(aMessage, commissionerId)); @@ -145,7 +147,7 @@ void Leader::SendPetitionResponse(const Coap::Message & aRequest, SuccessOrExit(error = Get().SendMessage(*message, aMessageInfo)); - otLogInfoMeshCoP("sent petition response"); + LogInfo("sent petition response"); exit: FreeMessageOnError(message, error); @@ -164,7 +166,7 @@ void Leader::HandleKeepAlive(Coap::Message &aMessage, const Ip6::MessageInfo &aM BorderAgentLocatorTlv *borderAgentLocator; StateTlv::State responseState; - otLogInfoMeshCoP("received keep alive"); + LogInfo("received keep alive"); SuccessOrExit(Tlv::Find(aMessage, state)); @@ -218,7 +220,7 @@ void Leader::SendKeepAliveResponse(const Coap::Message & aRequest, SuccessOrExit(error = Get().SendMessage(*message, aMessageInfo)); - otLogInfoMeshCoP("sent keep alive response"); + LogInfo("sent keep alive response"); exit: FreeMessageOnError(message, error); @@ -240,7 +242,7 @@ void Leader::SendDatasetChanged(const Ip6::Address &aAddress) messageInfo.SetPeerPort(Tmf::kUdpPort); SuccessOrExit(error = Get().SendMessage(*message, messageInfo)); - otLogInfoMeshCoP("sent dataset changed"); + LogInfo("sent dataset changed"); exit: FreeMessageOnError(message, error); @@ -294,7 +296,7 @@ void Leader::ResignCommissioner(void) mTimer.Stop(); SetEmptyCommissionerData(); - otLogInfoMeshCoP("commissioner inactive"); + LogInfo("commissioner inactive"); } } // namespace MeshCoP diff --git a/src/core/meshcop/panid_query_client.cpp b/src/core/meshcop/panid_query_client.cpp index 094b1c5c8..50b9a0322 100644 --- a/src/core/meshcop/panid_query_client.cpp +++ b/src/core/meshcop/panid_query_client.cpp @@ -41,7 +41,7 @@ #include "common/debug.hpp" #include "common/instance.hpp" #include "common/locator_getters.hpp" -#include "common/logging.hpp" +#include "common/log.hpp" #include "meshcop/meshcop.hpp" #include "meshcop/meshcop_tlvs.hpp" #include "thread/thread_netif.hpp" @@ -49,6 +49,8 @@ namespace ot { +RegisterLogModule("PanIdQueryClnt"); + PanIdQueryClient::PanIdQueryClient(Instance &aInstance) : InstanceLocator(aInstance) , mCallback(nullptr) @@ -89,7 +91,7 @@ Error PanIdQueryClient::SendQuery(uint16_t aPanId, messageInfo.SetPeerPort(Tmf::kUdpPort); SuccessOrExit(error = Get().SendMessage(*message, messageInfo)); - otLogInfoMeshCoP("sent panid query"); + LogInfo("sent panid query"); mCallback = aCallback; mContext = aContext; @@ -112,7 +114,7 @@ void PanIdQueryClient::HandleConflict(Coap::Message &aMessage, const Ip6::Messag VerifyOrExit(aMessage.IsConfirmablePostRequest()); - otLogInfoMeshCoP("received panid conflict"); + LogInfo("received panid conflict"); SuccessOrExit(Tlv::Find(aMessage, panId)); @@ -125,7 +127,7 @@ void PanIdQueryClient::HandleConflict(Coap::Message &aMessage, const Ip6::Messag SuccessOrExit(Get().SendEmptyAck(aMessage, responseInfo)); - otLogInfoMeshCoP("sent panid query conflict response"); + LogInfo("sent panid query conflict response"); exit: return; diff --git a/src/core/net/dhcp6_client.cpp b/src/core/net/dhcp6_client.cpp index eed2a2739..9c3e77278 100644 --- a/src/core/net/dhcp6_client.cpp +++ b/src/core/net/dhcp6_client.cpp @@ -40,7 +40,7 @@ #include "common/encoding.hpp" #include "common/instance.hpp" #include "common/locator_getters.hpp" -#include "common/logging.hpp" +#include "common/log.hpp" #include "mac/mac.hpp" #include "net/dhcp6.hpp" #include "thread/thread_netif.hpp" @@ -48,6 +48,8 @@ namespace ot { namespace Dhcp6 { +RegisterLogModule("Dhcp6Client"); + Client::Client(Instance &aInstance) : InstanceLocator(aInstance) , mSocket(aInstance) @@ -146,7 +148,7 @@ void Client::UpdateAddresses(void) } else { - otLogWarnIp6("Insufficient memory for new DHCP prefix"); + LogWarn("Insufficient memory for new DHCP prefix"); continue; } } @@ -283,13 +285,13 @@ void Client::Solicit(uint16_t aRloc16) messageInfo.mPeerPort = kDhcpServerPort; SuccessOrExit(error = mSocket.SendTo(*message, messageInfo)); - otLogInfoIp6("solicit"); + LogInfo("solicit"); exit: if (error != kErrorNone) { FreeMessage(message); - otLogWarnIp6("Failed to send DHCPv6 Solicit: %s", ErrorToString(error)); + LogWarn("Failed to send DHCPv6 Solicit: %s", ErrorToString(error)); } } diff --git a/src/core/net/dhcp6_server.cpp b/src/core/net/dhcp6_server.cpp index f654141f8..eaab1b4dd 100644 --- a/src/core/net/dhcp6_server.cpp +++ b/src/core/net/dhcp6_server.cpp @@ -41,13 +41,15 @@ #include "common/encoding.hpp" #include "common/instance.hpp" #include "common/locator_getters.hpp" -#include "common/logging.hpp" +#include "common/log.hpp" #include "thread/mle.hpp" #include "thread/thread_netif.hpp" namespace ot { namespace Dhcp6 { +RegisterLogModule("Dhcp6Server"); + Server::Server(Instance &aInstance) : InstanceLocator(aInstance) , mSocket(aInstance) @@ -176,7 +178,7 @@ exit: if (error != kErrorNone) { - otLogNoteIp6("Failed to add DHCPv6 prefix agent: %s", ErrorToString(error)); + LogNote("Failed to add DHCPv6 prefix agent: %s", ErrorToString(error)); } } diff --git a/src/core/net/dns_client.cpp b/src/core/net/dns_client.cpp index 3e79d79a1..29bc85e04 100644 --- a/src/core/net/dns_client.cpp +++ b/src/core/net/dns_client.cpp @@ -36,7 +36,7 @@ #include "common/debug.hpp" #include "common/instance.hpp" #include "common/locator_getters.hpp" -#include "common/logging.hpp" +#include "common/log.hpp" #include "net/udp6.hpp" #include "thread/network_data_types.hpp" #include "thread/thread_netif.hpp" @@ -49,6 +49,8 @@ namespace ot { namespace Dns { +RegisterLogModule("DnsClient"); + //--------------------------------------------------------------------------------------------------------------------- // Client::QueryConfig @@ -1050,7 +1052,7 @@ Error Client::ParseResponse(Response &aResponse, QueryType &aType, Error &aRespo exit: if (error != kErrorNone) { - otLogInfoDns("Failed to parse response %s", ErrorToString(error)); + LogInfo("Failed to parse response %s", ErrorToString(error)); } return error; diff --git a/src/core/net/dns_dso.cpp b/src/core/net/dns_dso.cpp index 31985749f..27222baf5 100644 --- a/src/core/net/dns_dso.cpp +++ b/src/core/net/dns_dso.cpp @@ -36,7 +36,7 @@ #include "common/debug.hpp" #include "common/instance.hpp" #include "common/locator_getters.hpp" -#include "common/logging.hpp" +#include "common/log.hpp" #include "common/random.hpp" /** @@ -47,6 +47,8 @@ namespace ot { namespace Dns { +RegisterLogModule("DnsDso"); + //--------------------------------------------------------------------------------------------------------------------- // otPlatDso transport callbacks @@ -111,8 +113,8 @@ void Dso::Connection::SetState(State aState) { VerifyOrExit(mState != aState); - otLogInfoDns("[dso] State: %s -> %s on connection with %s", StateToString(mState), StateToString(aState), - mPeerSockAddr.ToString().AsCString()); + LogInfo("State: %s -> %s on connection with %s", StateToString(mState), StateToString(aState), + mPeerSockAddr.ToString().AsCString()); mState = aState; mStateDidChange = true; @@ -254,7 +256,7 @@ void Dso::Connection::MarkAsDisconnected(void) mPendingRequests.Clear(); SetState(kStateDisconnected); - otLogInfoDns("[dso] Disconnect reason: %s", DisconnectReasonToString(mDisconnectReason)); + LogInfo("Disconnect reason: %s", DisconnectReasonToString(mDisconnectReason)); } void Dso::Connection::MarkSessionEstablished(void) @@ -297,7 +299,7 @@ void Dso::Connection::SetLongLivedOperation(bool aLongLivedOperation) mLongLivedOperation = aLongLivedOperation; - otLogInfoDns("[dso] Long-lived operation %s", mLongLivedOperation ? "started" : "stopped"); + LogInfo("Long-lived operation %s", mLongLivedOperation ? "started" : "stopped"); if (!mLongLivedOperation) { @@ -579,8 +581,8 @@ Error Dso::Connection::SendMessage(Message & aMessage, } } - otLogInfoDns("[dso] Sending %s message with id %u to %s", MessageTypeToString(aMessageType), aMessageId, - mPeerSockAddr.ToString().AsCString()); + LogInfo("Sending %s message with id %u to %s", MessageTypeToString(aMessageType), aMessageId, + mPeerSockAddr.ToString().AsCString()); switch (mState) { @@ -817,7 +819,7 @@ Error Dso::Connection::ProcessRequestOrUnidirectionalMessage(const Dns::Header & default: if (aHeader.GetMessageId() == 0) { - otLogInfoDns("[dso] Received unidirectional message from %s", mPeerSockAddr.ToString().AsCString()); + LogInfo("Received unidirectional message from %s", mPeerSockAddr.ToString().AsCString()); error = mCallbacks.mProcessUnidirectionalMessage(*this, aMessage, aPrimaryTlvType); } @@ -825,8 +827,7 @@ Error Dso::Connection::ProcessRequestOrUnidirectionalMessage(const Dns::Header & { MessageId messageId = aHeader.GetMessageId(); - otLogInfoDns("[dso] Received request message with id %u from %s", messageId, - mPeerSockAddr.ToString().AsCString()); + LogInfo("Received request message with id %u from %s", messageId, mPeerSockAddr.ToString().AsCString()); error = mCallbacks.mProcessRequestMessage(*this, messageId, aMessage, aPrimaryTlvType); @@ -956,8 +957,7 @@ Error Dso::Connection::ProcessKeepAliveMessage(const Dns::Header &aHeader, const VerifyOrExit(aHeader.GetMessageId() != 0); - otLogInfoDns("[dso] Received KeepAlive request message from client %s", - mPeerSockAddr.ToString().AsCString()); + LogInfo("Received KeepAlive request message from client %s", mPeerSockAddr.ToString().AsCString()); IgnoreError(SendKeepAliveMessage(kResponseMessage, aHeader.GetMessageId())); error = kErrorNone; @@ -971,8 +971,8 @@ Error Dso::Connection::ProcessKeepAliveMessage(const Dns::Header &aHeader, const VerifyOrExit(aHeader.GetMessageId() == 0); } - otLogInfoDns("[dso] Received Keep Alive %s message from server %s", - (aHeader.GetMessageId() == 0) ? "unidirectional" : "response", mPeerSockAddr.ToString().AsCString()); + LogInfo("Received Keep Alive %s message from server %s", + (aHeader.GetMessageId() == 0) ? "unidirectional" : "response", mPeerSockAddr.ToString().AsCString()); // Receiving a Keep Alive interval value from server less than the // minimum (ten seconds) is a fatal error and client MUST then @@ -990,7 +990,7 @@ Error Dso::Connection::ProcessKeepAliveMessage(const Dns::Header &aHeader, const AdjustInactivityTimeout(keepAliveTlv.GetInactivityTimeout()); mKeepAlive.SetInterval(keepAliveTlv.GetKeepAliveInterval()); - otLogInfoDns("[dso] Timeouts Inactivity:%u, KeepAlive:%u", mInactivity.GetInterval(), mKeepAlive.GetInterval()); + LogInfo("Timeouts Inactivity:%u, KeepAlive:%u", mInactivity.GetInterval(), mKeepAlive.GetInterval()); error = kErrorNone; @@ -1018,8 +1018,8 @@ Error Dso::Connection::ProcessRetryDelayMessage(const Dns::Header &aHeader, cons mRetryDelayErrorCode = aHeader.GetResponseCode(); mRetryDelay = retryDelayTlv.GetRetryDelay(); - otLogInfoDns("[dso] Received Retry Delay message from server %s", mPeerSockAddr.ToString().AsCString()); - otLogInfoDns("[dso] RetryDelay:%u ms, ResponseCode:%d", mRetryDelay, mRetryDelayErrorCode); + LogInfo("Received Retry Delay message from server %s", mPeerSockAddr.ToString().AsCString()); + LogInfo(" RetryDelay:%u ms, ResponseCode:%d", mRetryDelay, mRetryDelayErrorCode); Disconnect(kGracefullyClose, kReasonServerRetryDelayRequest); diff --git a/src/core/net/dns_types.cpp b/src/core/net/dns_types.cpp index 3862061ec..e65cd035a 100644 --- a/src/core/net/dns_types.cpp +++ b/src/core/net/dns_types.cpp @@ -36,7 +36,6 @@ #include "common/code_utils.hpp" #include "common/debug.hpp" #include "common/instance.hpp" -#include "common/logging.hpp" #include "common/random.hpp" #include "common/string.hpp" diff --git a/src/core/net/dnssd_server.cpp b/src/core/net/dnssd_server.cpp index ec4dbb4fa..40249ce7b 100644 --- a/src/core/net/dnssd_server.cpp +++ b/src/core/net/dnssd_server.cpp @@ -41,7 +41,7 @@ #include "common/debug.hpp" #include "common/instance.hpp" #include "common/locator_getters.hpp" -#include "common/logging.hpp" +#include "common/log.hpp" #include "common/string.hpp" #include "net/srp_server.hpp" #include "net/udp6.hpp" @@ -50,6 +50,8 @@ namespace ot { namespace Dns { namespace ServiceDiscovery { +RegisterLogModule("DnssdServer"); + const char Server::kDnssdProtocolUdp[] = "_udp"; const char Server::kDnssdProtocolTcp[] = "_tcp"; const char Server::kDnssdSubTypeLabel[] = "._sub."; @@ -79,7 +81,7 @@ Error Server::Start(void) #endif exit: - otLogInfoDns("[server] started: %s", ErrorToString(error)); + LogInfo("started: %s", ErrorToString(error)); if (error != kErrorNone) { @@ -103,7 +105,7 @@ void Server::Stop(void) mTimer.Stop(); IgnoreError(mSocket.Close()); - otLogInfoDns("[server] stopped"); + LogInfo("stopped"); #if OPENTHREAD_CONFIG_SRP_SERVER_ENABLE Get().HandleDnssdServerStateChange(); @@ -196,7 +198,7 @@ void Server::SendResponse(Header aHeader, if (aResponseCode == Header::kResponseServerFailure) { - otLogWarnDns("[server] failed to handle DNS query due to server failure"); + LogWarn("failed to handle DNS query due to server failure"); aHeader.SetQuestionCount(0); aHeader.SetAnswerCount(0); aHeader.SetAdditionalRecordCount(0); @@ -212,11 +214,11 @@ void Server::SendResponse(Header aHeader, if (error != kErrorNone) { - otLogWarnDns("[server] failed to send DNS-SD reply: %s", ErrorToString(error)); + LogWarn("failed to send DNS-SD reply: %s", ErrorToString(error)); } else { - otLogInfoDns("[server] send DNS-SD reply: %s, RCODE=%d", ErrorToString(error), aResponseCode); + LogInfo("send DNS-SD reply: %s, RCODE=%d", ErrorToString(error), aResponseCode); } } @@ -663,8 +665,8 @@ Header::Response Server::ResolveBySrp(Header & aResponseHeader, response = ResolveQuestionBySrp(name, question, aResponseHeader, aResponseMessage, aCompressInfo, /* aAdditional */ false); - otLogInfoDns("[server] ANSWER: TRANSACTION=0x%04x, QUESTION=[%s %d %d], RCODE=%d", - aResponseHeader.GetMessageId(), name, question.GetClass(), question.GetType(), response); + LogInfo("ANSWER: TRANSACTION=0x%04x, QUESTION=[%s %d %d], RCODE=%d", aResponseHeader.GetMessageId(), name, + question.GetClass(), question.GetType(), response); } // Answer the questions with additional RRs if required @@ -682,8 +684,8 @@ Header::Response Server::ResolveBySrp(Header & aResponseHeader, /* aAdditional */ true), response = Header::kResponseServerFailure); - otLogInfoDns("[server] ADDITIONAL: TRANSACTION=0x%04x, QUESTION=[%s %d %d], RCODE=%d", - aResponseHeader.GetMessageId(), name, question.GetClass(), question.GetType(), response); + LogInfo("ADDITIONAL: TRANSACTION=0x%04x, QUESTION=[%s %d %d], RCODE=%d", aResponseHeader.GetMessageId(), + name, question.GetClass(), question.GetType(), response); } } exit: diff --git a/src/core/net/icmp6.cpp b/src/core/net/icmp6.cpp index f41737459..fee412d71 100644 --- a/src/core/net/icmp6.cpp +++ b/src/core/net/icmp6.cpp @@ -37,7 +37,7 @@ #include "common/debug.hpp" #include "common/instance.hpp" #include "common/locator_getters.hpp" -#include "common/logging.hpp" +#include "common/log.hpp" #include "common/message.hpp" #include "net/checksum.hpp" #include "net/ip6.hpp" @@ -45,6 +45,8 @@ namespace ot { namespace Ip6 { +RegisterLogModule("Icmp6"); + Icmp::Icmp(Instance &aInstance) : InstanceLocator(aInstance) , mEchoSequence(1) @@ -79,7 +81,7 @@ Error Icmp::SendEchoRequest(Message &aMessage, const MessageInfo &aMessageInfo, aMessage.SetOffset(0); SuccessOrExit(error = Get().SendDatagram(aMessage, messageInfoLocal, kProtoIcmp6)); - otLogInfoIcmp("Sent echo request: (seq = %d)", icmpHeader.GetSequence()); + LogInfo("Sent echo request: (seq = %d)", icmpHeader.GetSequence()); exit: return error; @@ -116,7 +118,7 @@ Error Icmp::SendError(Header::Type aType, Header::Code aCode, const MessageInfo SuccessOrExit(error = Get().SendDatagram(*message, messageInfoLocal, kProtoIcmp6)); - otLogInfoIcmp("Sent ICMPv6 Error"); + LogInfo("Sent ICMPv6 Error"); exit: FreeMessageOnError(message, error); @@ -182,14 +184,14 @@ Error Icmp::HandleEchoRequest(Message &aRequestMessage, const MessageInfo &aMess // always handle Echo Request destined for RLOC or ALOC VerifyOrExit(ShouldHandleEchoRequest(aMessageInfo) || aMessageInfo.GetSockAddr().GetIid().IsLocator()); - otLogInfoIcmp("Received Echo Request"); + LogInfo("Received Echo Request"); icmp6Header.Clear(); icmp6Header.SetType(Header::kTypeEchoReply); if ((replyMessage = Get().NewMessage(0)) == nullptr) { - otLogDebgIcmp("Failed to allocate a new message"); + LogDebg("Failed to allocate a new message"); ExitNow(); } @@ -210,7 +212,7 @@ Error Icmp::HandleEchoRequest(Message &aRequestMessage, const MessageInfo &aMess SuccessOrExit(error = Get().SendDatagram(*replyMessage, replyMessageInfo, kProtoIcmp6)); IgnoreError(replyMessage->Read(replyMessage->GetOffset(), icmp6Header)); - otLogInfoIcmp("Sent Echo Reply (seq = %d)", icmp6Header.GetSequence()); + LogInfo("Sent Echo Reply (seq = %d)", icmp6Header.GetSequence()); exit: FreeMessageOnError(replyMessage, error); diff --git a/src/core/net/ip6.cpp b/src/core/net/ip6.cpp index 9ccbc1d73..62c1732ca 100644 --- a/src/core/net/ip6.cpp +++ b/src/core/net/ip6.cpp @@ -40,7 +40,7 @@ #include "common/debug.hpp" #include "common/instance.hpp" #include "common/locator_getters.hpp" -#include "common/logging.hpp" +#include "common/log.hpp" #include "common/message.hpp" #include "common/random.hpp" #include "net/checksum.hpp" @@ -62,6 +62,8 @@ static const IcmpType sForwardICMPTypes[] = { namespace ot { namespace Ip6 { +RegisterLogModule("Ip6"); + Ip6::Ip6(Instance &aInstance) : InstanceLocator(aInstance) , mForwardingEnabled(false) @@ -308,11 +310,11 @@ Error Ip6::InsertMplOption(Message &aMessage, Header &aHeader, MessageInfo &aMes if ((messageCopy = aMessage.Clone()) != nullptr) { IgnoreError(HandleDatagram(*messageCopy, nullptr, nullptr, /* aFromHost */ true)); - otLogInfoIp6("Message copy for indirect transmission to sleepy children"); + LogInfo("Message copy for indirect transmission to sleepy children"); } else { - otLogWarnIp6("No enough buffer for message copy for indirect transmission to sleepy children"); + LogWarn("No enough buffer for message copy for indirect transmission to sleepy children"); } } #endif @@ -499,12 +501,12 @@ Error Ip6::SendDatagram(Message &aMessage, MessageInfo &aMessageInfo, uint8_t aI if (messageCopy != nullptr) { - otLogInfoIp6("Message copy for indirect transmission to sleepy children"); + LogInfo("Message copy for indirect transmission to sleepy children"); EnqueueDatagram(*messageCopy); } else { - otLogWarnIp6("No enough buffer for message copy for indirect transmission to sleepy children"); + LogWarn("No enough buffer for message copy for indirect transmission to sleepy children"); } } #endif @@ -637,7 +639,7 @@ Error Ip6::FragmentDatagram(Message &aMessage, uint8_t aIpProto) payloadFragment = payloadLeft; payloadLeft = 0; - otLogDebgIp6("Last Fragment"); + LogDebg("Last Fragment"); } else { @@ -667,7 +669,7 @@ Error Ip6::FragmentDatagram(Message &aMessage, uint8_t aIpProto) fragmentCnt++; fragment = nullptr; - otLogInfoIp6("Fragment %d with %d bytes sent", fragmentCnt, payloadFragment); + LogInfo("Fragment %d with %d bytes sent", fragmentCnt, payloadFragment); } aMessage.Free(); @@ -676,7 +678,7 @@ exit: if (error == kErrorNoBufs) { - otLogWarnIp6("No buffer for Ip6 fragmentation"); + LogWarn("No buffer for Ip6 fragmentation"); } FreeMessageOnError(fragment, error); @@ -720,18 +722,18 @@ Error Ip6::HandleFragment(Message &aMessage, Netif *aNetif, MessageInfo &aMessag offset = FragmentHeader::FragmentOffsetToBytes(fragmentHeader.GetOffset()); payloadFragment = aMessage.GetLength() - aMessage.GetOffset() - sizeof(fragmentHeader); - otLogInfoIp6("Fragment with id %d received > %d bytes, offset %d", fragmentHeader.GetIdentification(), - payloadFragment, offset); + LogInfo("Fragment with id %d received > %d bytes, offset %d", fragmentHeader.GetIdentification(), payloadFragment, + offset); if (offset + payloadFragment + aMessage.GetOffset() > kMaxAssembledDatagramLength) { - otLogWarnIp6("Packet too large for fragment buffer"); + LogWarn("Packet too large for fragment buffer"); ExitNow(error = kErrorNoBufs); } if (message == nullptr) { - otLogDebgIp6("start reassembly"); + LogDebg("start reassembly"); VerifyOrExit((message = NewMessage(0)) != nullptr, error = kErrorNoBufs); mReassemblyList.Enqueue(*message); SuccessOrExit(error = message->SetLength(aMessage.GetOffset())); @@ -770,7 +772,7 @@ Error Ip6::HandleFragment(Message &aMessage, Netif *aNetif, MessageInfo &aMessag header.SetNextHeader(fragmentHeader.GetNextHeader()); message->Write(0, header); - otLogDebgIp6("Reassembly complete."); + LogDebg("Reassembly complete."); mReassemblyList.Dequeue(*message); @@ -785,7 +787,7 @@ exit: mReassemblyList.DequeueAndFree(*message); } - otLogWarnIp6("Reassembly failed: %s", ErrorToString(error)); + LogWarn("Reassembly failed: %s", ErrorToString(error)); } if (isFragmented) @@ -826,7 +828,7 @@ void Ip6::UpdateReassemblyList(void) } else { - otLogNoteIp6("Reassembly timeout."); + LogNote("Reassembly timeout."); SendIcmpError(*message, Icmp::Header::kTypeTimeExceeded, Icmp::Header::kCodeFragmReasTimeEx); mReassemblyList.DequeueAndFree(*message); @@ -853,7 +855,7 @@ exit: if (error != kErrorNone) { - otLogWarnIp6("Failed to send ICMP error: %s", ErrorToString(error)); + LogWarn("Failed to send ICMP error: %s", ErrorToString(error)); } } @@ -966,7 +968,7 @@ Error Ip6::HandlePayload(Header & aIp6Header, error = mTcp.HandleMessage(aIp6Header, *message, aMessageInfo); if (error == kErrorDrop) { - otLogNoteIp6("Error TCP Checksum"); + LogNote("Error TCP Checksum"); } break; #endif @@ -974,7 +976,7 @@ Error Ip6::HandlePayload(Header & aIp6Header, error = mUdp.HandleMessage(*message, aMessageInfo); if (error == kErrorDrop) { - otLogNoteIp6("Error UDP Checksum"); + LogNote("Error UDP Checksum"); } break; @@ -989,7 +991,7 @@ Error Ip6::HandlePayload(Header & aIp6Header, exit: if (error != kErrorNone) { - otLogNoteIp6("Failed to handle payload: %s", ErrorToString(error)); + LogNote("Failed to handle payload: %s", ErrorToString(error)); } FreeMessage(message); @@ -1064,7 +1066,7 @@ Error Ip6::ProcessReceiveCallback(Message & aMessage, if (message == nullptr) { - otLogWarnIp6("No buff to clone msg (len: %d) to pass to host", aMessage.GetLength()); + LogWarn("No buff to clone msg (len: %d) to pass to host", aMessage.GetLength()); ExitNow(error = kErrorNoBufs); } diff --git a/src/core/net/ip6_filter.cpp b/src/core/net/ip6_filter.cpp index 5ea480a0f..86a3e5420 100644 --- a/src/core/net/ip6_filter.cpp +++ b/src/core/net/ip6_filter.cpp @@ -38,7 +38,7 @@ #include "common/code_utils.hpp" #include "common/instance.hpp" #include "common/locator_getters.hpp" -#include "common/logging.hpp" +#include "common/log.hpp" #include "meshcop/meshcop.hpp" #include "net/ip6.hpp" #include "net/tcp6.hpp" @@ -48,6 +48,8 @@ namespace ot { namespace Ip6 { +RegisterLogModule("Ip6Filter"); + Filter::Filter(Instance &aInstance) : InstanceLocator(aInstance) { @@ -149,7 +151,7 @@ Error Filter::AddUnsecurePort(uint16_t aPort) if (unsecurePort == 0) { unsecurePort = aPort; - otLogInfoIp6("Added unsecure port %d", aPort); + LogInfo("Added unsecure port %d", aPort); ExitNow(); } } @@ -179,7 +181,7 @@ Error Filter::RemoveUnsecurePort(uint16_t aPort) // Clear the last port entry. mUnsecurePorts[i] = 0; - otLogInfoIp6("Removed unsecure port %d", aPort); + LogInfo("Removed unsecure port %d", aPort); ExitNow(); } } diff --git a/src/core/net/sntp_client.cpp b/src/core/net/sntp_client.cpp index 108370b19..65641dae6 100644 --- a/src/core/net/sntp_client.cpp +++ b/src/core/net/sntp_client.cpp @@ -36,7 +36,7 @@ #include "common/debug.hpp" #include "common/instance.hpp" #include "common/locator_getters.hpp" -#include "common/logging.hpp" +#include "common/log.hpp" #include "net/udp6.hpp" #include "thread/thread_netif.hpp" @@ -48,6 +48,8 @@ namespace ot { namespace Sntp { +RegisterLogModule("SntpClnt"); + Header::Header(void) : mFlags(kNtpVersion << kVersionOffset | kModeClient << kModeOffset) , mStratum(0) @@ -237,7 +239,7 @@ exit: if (error != kErrorNone) { FreeMessage(messageCopy); - otLogWarnIp6("Failed to send SNTP request: %s", ErrorToString(error)); + LogWarn("Failed to send SNTP request: %s", ErrorToString(error)); } } @@ -360,7 +362,7 @@ void Client::HandleUdpReceive(Message &aMessage, const Ip6::MessageInfo &aMessag memcpy(kissCode, responseHeader.GetKissCode(), Header::kKissCodeLength); kissCode[Header::kKissCodeLength] = 0; - otLogInfoIp6("SNTP response contains the Kiss-o'-death packet with %s code", kissCode); + LogInfo("SNTP response contains the Kiss-o'-death packet with %s code", kissCode); ExitNow(error = kErrorBusy); } diff --git a/src/core/net/srp_client.cpp b/src/core/net/srp_client.cpp index a9022b462..db302c42a 100644 --- a/src/core/net/srp_client.cpp +++ b/src/core/net/srp_client.cpp @@ -35,7 +35,7 @@ #include "common/debug.hpp" #include "common/instance.hpp" #include "common/locator_getters.hpp" -#include "common/logging.hpp" +#include "common/log.hpp" #include "common/numeric_limits.hpp" #include "common/random.hpp" #include "common/settings.hpp" @@ -50,6 +50,8 @@ namespace ot { namespace Srp { +RegisterLogModule("SrpClient"); + //--------------------------------------------------------------------- // Client::HostInfo @@ -72,7 +74,7 @@ void Client::HostInfo::SetState(ItemState aState) { if (aState != GetState()) { - otLogInfoSrp("[client] HostInfo %s -> %s", ItemStateToString(GetState()), ItemStateToString(aState)); + LogInfo("HostInfo %s -> %s", ItemStateToString(GetState()), ItemStateToString(aState)); mState = MapEnum(aState); } } @@ -82,11 +84,11 @@ void Client::HostInfo::SetAddresses(const Ip6::Address *aAddresses, uint8_t aNum mAddresses = aAddresses; mNumAddresses = aNumAddresses; - otLogInfoSrp("[client] HostInfo set %d addrs", GetNumAddresses()); + LogInfo("HostInfo set %d addrs", GetNumAddresses()); for (uint8_t index = 0; index < GetNumAddresses(); index++) { - otLogInfoSrp("[client] %s", GetAddress(index).ToString().AsCString()); + LogInfo("%s", GetAddress(index).ToString().AsCString()); } } @@ -112,8 +114,8 @@ void Client::Service::SetState(ItemState aState) { VerifyOrExit(GetState() != aState); - otLogInfoSrp("[client] Service %s -> %s, \"%s\" \"%s\"", ItemStateToString(GetState()), ItemStateToString(aState), - GetInstanceName(), GetName()); + LogInfo("Service %s -> %s, \"%s\" \"%s\"", ItemStateToString(GetState()), ItemStateToString(aState), + GetInstanceName(), GetName()); if (aState == kToAdd) { @@ -133,8 +135,8 @@ void Client::Service::SetState(ItemState aState) } } - otLogInfoSrp("[client] subtypes:[%s] port:%d weight:%d prio:%d txts:%d", string.AsCString(), GetPort(), - GetWeight(), GetPriority(), GetNumTxtEntries()); + LogInfo("subtypes:[%s] port:%d weight:%d prio:%d txts:%d", string.AsCString(), GetPort(), GetWeight(), + GetPriority(), GetNumTxtEntries()); } mState = MapEnum(aState); @@ -218,8 +220,8 @@ Error Client::Start(const Ip6::SockAddr &aServerSockAddr, Requester aRequester) SuccessOrExit(error = mSocket.Open(Client::HandleUdpReceive, this)); SuccessOrExit(error = mSocket.Connect(aServerSockAddr)); - otLogInfoSrp("[client] %starting, server %s", (aRequester == kRequesterUser) ? "S" : "Auto-s", - aServerSockAddr.ToString().AsCString()); + LogInfo("%starting, server %s", (aRequester == kRequesterUser) ? "S" : "Auto-s", + aServerSockAddr.ToString().AsCString()); Resume(); @@ -387,7 +389,7 @@ Error Client::SetDomainName(const char *aName) VerifyOrExit((mHostInfo.GetState() == kToAdd) || (mHostInfo.GetState() == kRemoved), error = kErrorInvalidState); mDomainName = (aName != nullptr) ? aName : kDefaultDomainName; - otLogInfoSrp("[client] Domain name \"%s\"", mDomainName); + LogInfo("Domain name \"%s\"", mDomainName); exit: return error; @@ -402,7 +404,7 @@ Error Client::SetHostName(const char *aName) VerifyOrExit((mHostInfo.GetState() == kToAdd) || (mHostInfo.GetState() == kRemoved), error = kErrorInvalidState); - otLogInfoSrp("[client] Host name \"%s\"", aName); + LogInfo("Host name \"%s\"", aName); mHostInfo.SetName(aName); mHostInfo.SetState(kToAdd); UpdateState(); @@ -506,7 +508,7 @@ Error Client::RemoveHostAndServices(bool aShouldRemoveKeyLease, bool aSendUnregT { Error error = kErrorNone; - otLogInfoSrp("[client] Remove host & services"); + LogInfo("Remove host & services"); VerifyOrExit(mHostInfo.GetState() != kRemoved, error = kErrorAlready); @@ -542,7 +544,7 @@ exit: void Client::ClearHostAndServices(void) { - otLogInfoSrp("[client] Clear host & services"); + LogInfo("Clear host & services"); switch (GetState()) { @@ -569,7 +571,7 @@ void Client::SetState(State aState) { VerifyOrExit(aState != mState); - otLogInfoSrp("[client] State %s -> %s", StateToString(mState), StateToString(aState)); + LogInfo("State %s -> %s", StateToString(mState), StateToString(aState)); mState = aState; switch (mState) @@ -663,7 +665,7 @@ void Client::SendUpdate(void) SuccessOrExit(error = PrepareUpdateMessage(*message)); SuccessOrExit(error = mSocket.SendTo(*message, Ip6::MessageInfo())); - otLogInfoSrp("[client] Send update"); + LogInfo("Send update"); // State changes: // kToAdd -> kAdding @@ -696,7 +698,7 @@ exit: // continue to retry using the `mRetryWaitInterval` (which keeps // growing on each failure). - otLogInfoSrp("[client] Failed to send update: %s", ErrorToString(error)); + LogInfo("Failed to send update: %s", ErrorToString(error)); FreeMessage(message); @@ -710,7 +712,7 @@ exit: interval = Random::NonCrypto::AddJitter(kTxFailureRetryInterval, kTxFailureRetryJitter); mTimer.Start(interval); - otLogInfoSrp("[client] Quick retry %d in %u msec", mTxFailureRetryCount, interval); + LogInfo("Quick retry %d in %u msec", mTxFailureRetryCount, interval); // Do not report message preparation errors to user // until `kMaxTxFailureRetries` are exhausted. @@ -1206,7 +1208,7 @@ void Client::ProcessResponse(Message &aMessage) // Response is for the earlier request message. - otLogInfoSrp("[client] Received response"); + LogInfo("Received response"); #if OPENTHREAD_CONFIG_SRP_CLIENT_AUTO_START_API_ENABLE && OPENTHREAD_CONFIG_SRP_CLIENT_SWITCH_SERVER_ON_FAILURE mTimoutFailureCount = 0; @@ -1216,7 +1218,7 @@ void Client::ProcessResponse(Message &aMessage) if (error != kErrorNone) { - otLogInfoSrp("[client] Server rejected %s code:%d", ErrorToString(error), header.GetResponseCode()); + LogInfo("Server rejected %s code:%d", ErrorToString(error), header.GetResponseCode()); if (mHostInfo.GetState() == kAdding) { @@ -1332,7 +1334,7 @@ void Client::ProcessResponse(Message &aMessage) exit: if (error != kErrorNone) { - otLogInfoSrp("[client] Failed to process response %s", ErrorToString(error)); + LogInfo("Failed to process response %s", ErrorToString(error)); } } @@ -1595,7 +1597,7 @@ void Client::HandleTimer(void) case kStateUpdating: LogRetryWaitInterval(); - otLogInfoSrp("[client] Timed out, no response"); + LogInfo("Timed out, no response"); GrowRetryWaitInterval(); SetState(kStateToUpdate); InvokeCallback(kErrorResponseTimeout); @@ -1685,7 +1687,7 @@ void Client::ProcessAutoStart(void) ExitNow(); } - otLogInfoSrp("[client] Found anycast server %d", anycastInfo.mSequenceNumber); + LogInfo("Found anycast server %d", anycastInfo.mSequenceNumber); serverSockAddr.SetAddress(anycastInfo.mAnycastAddress); serverSockAddr.SetPort(kAnycastServerPort); @@ -1866,7 +1868,7 @@ const char *Client::ItemStateToString(ItemState aState) return kItemStateStrings[aState]; } -#if (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO) && (OPENTHREAD_CONFIG_LOG_SRP == 1) +#if OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO const char *Client::StateToString(State aState) { @@ -1895,11 +1897,11 @@ void Client::LogRetryWaitInterval(void) const uint32_t interval = GetRetryWaitInterval(); - otLogInfoSrp("[client] Retry interval %u %s", (interval < kLogInMsecLimit) ? interval : Time::MsecToSec(interval), - (interval < kLogInMsecLimit) ? "ms" : "sec"); + LogInfo("Retry interval %u %s", (interval < kLogInMsecLimit) ? interval : Time::MsecToSec(interval), + (interval < kLogInMsecLimit) ? "ms" : "sec"); } -#endif // #if (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO) && (OPENTHREAD_CONFIG_LOG_SRP == 1) +#endif // #if OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO } // namespace Srp } // namespace ot diff --git a/src/core/net/srp_client.hpp b/src/core/net/srp_client.hpp index ec846f271..02fe240e5 100644 --- a/src/core/net/srp_client.hpp +++ b/src/core/net/srp_client.hpp @@ -843,7 +843,7 @@ private: #endif #endif -#if (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO) && (OPENTHREAD_CONFIG_LOG_SRP == 1) +#if OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO static const char *StateToString(State aState); void LogRetryWaitInterval(void) const; #else diff --git a/src/core/net/srp_server.cpp b/src/core/net/srp_server.cpp index cee8633ad..44c13db98 100644 --- a/src/core/net/srp_server.cpp +++ b/src/core/net/srp_server.cpp @@ -39,7 +39,7 @@ #include "common/const_cast.hpp" #include "common/instance.hpp" #include "common/locator_getters.hpp" -#include "common/logging.hpp" +#include "common/log.hpp" #include "common/new.hpp" #include "common/random.hpp" #include "net/dns_types.hpp" @@ -48,6 +48,8 @@ namespace ot { namespace Srp { +RegisterLogModule("SrpServer"); + static const char kDefaultDomain[] = "default.service.arpa."; static const char kServiceSubTypeLabel[] = "._sub."; @@ -109,7 +111,7 @@ Error Server::SetAddressMode(AddressMode aMode) VerifyOrExit(mState == kStateDisabled, error = kErrorInvalidState); VerifyOrExit(mAddressMode != aMode); - otLogInfoSrp("[server] Address Mode: %s -> %s", AddressModeToString(mAddressMode), AddressModeToString(aMode)); + LogInfo("Address Mode: %s -> %s", AddressModeToString(mAddressMode), AddressModeToString(aMode)); mAddressMode = aMode; exit: @@ -123,7 +125,7 @@ Error Server::SetAnycastModeSequenceNumber(uint8_t aSequenceNumber) VerifyOrExit(mState == kStateDisabled, error = kErrorInvalidState); mAnycastSequenceNumber = aSequenceNumber; - otLogInfoSrp("[server] Set Anycast Address Mode Seq Number to %d", aSequenceNumber); + LogInfo("Set Anycast Address Mode Seq Number to %d", aSequenceNumber); exit: return error; @@ -272,20 +274,20 @@ void Server::RemoveHost(Host *aHost, RetainName aRetainName, NotifyMode aNotifyS if (aRetainName) { - otLogInfoSrp("[server] remove host '%s' (but retain its name)", aHost->GetFullName()); + LogInfo("remove host '%s' (but retain its name)", aHost->GetFullName()); } else { aHost->mKeyLease = 0; IgnoreError(mHosts.Remove(*aHost)); - otLogInfoSrp("[server] fully remove host '%s'", aHost->GetFullName()); + LogInfo("fully remove host '%s'", aHost->GetFullName()); } if (aNotifyServiceHandler && mServiceUpdateHandler != nullptr) { uint32_t updateId = AllocateId(); - otLogInfoSrp("[server] SRP update handler is notified (updatedId = %u)", updateId); + LogInfo("SRP update handler is notified (updatedId = %u)", updateId); mServiceUpdateHandler(updateId, aHost, kDefaultEventsHandlerTimeout, mServiceUpdateHandlerContext); // We don't wait for the reply from the service update handler, // but always remove the host (and its services) regardless of @@ -342,14 +344,13 @@ void Server::HandleServiceUpdateResult(ServiceUpdateId aId, Error aError) } else { - otLogInfoSrp("[server] delayed SRP host update result, the SRP update has been committed (updateId = %u)", aId); + LogInfo("delayed SRP host update result, the SRP update has been committed (updateId = %u)", aId); } } void Server::HandleServiceUpdateResult(UpdateMetadata *aUpdate, Error aError) { - otLogInfoSrp("[server] handler result of SRP update (id = %u) is received: %s", aUpdate->GetId(), - otThreadErrorToString(aError)); + LogInfo("handler result of SRP update (id = %u) is received: %s", aUpdate->GetId(), otThreadErrorToString(aError)); IgnoreError(mOutstandingUpdates.Remove(*aUpdate)); CommitSrpUpdate(aError, *aUpdate); @@ -413,7 +414,7 @@ void Server::CommitSrpUpdate(Error aError, { if (aHost.GetKeyLease() == 0) { - otLogInfoSrp("[server] remove key of host %s", aHost.GetFullName()); + LogInfo("remove key of host %s", aHost.GetFullName()); RemoveHost(existingHost, kDeleteName, kDoNotNotifyServiceHandler); } else if (existingHost != nullptr) @@ -433,7 +434,7 @@ void Server::CommitSrpUpdate(Error aError, } else { - otLogInfoSrp("[server] add new host %s", aHost.GetFullName()); + LogInfo("add new host %s", aHost.GetFullName()); for (Service &service : aHost.GetServices()) { @@ -497,7 +498,7 @@ void Server::SelectPort(void) } #endif - otLogInfoSrp("[server] selected port %u", mPort); + LogInfo("selected port %u", mPort); } void Server::Start(void) @@ -506,7 +507,7 @@ void Server::Start(void) mState = kStateRunning; PrepareSocket(); - otLogInfoSrp("[server] start listening on port %u", mPort); + LogInfo("start listening on port %u", mPort); exit: return; @@ -537,7 +538,7 @@ void Server::PrepareSocket(void) exit: if (error != kErrorNone) { - otLogCritSrp("[server] failed to prepare socket: %s", ErrorToString(error)); + LogCrit("failed to prepare socket: %s", ErrorToString(error)); Stop(); } } @@ -613,7 +614,7 @@ void Server::Stop(void) mLeaseTimer.Stop(); mOutstandingUpdatesTimer.Stop(); - otLogInfoSrp("[server] stop listening on %u", mPort); + LogInfo("stop listening on %u", mPort); IgnoreError(mSocket.Close()); mHasRegisteredAnyService = false; @@ -660,15 +661,15 @@ void Server::ProcessDnsUpdate(Message &aMessage, MessageMetadata &aMetadata) Error error = kErrorNone; Host *host = nullptr; - otLogInfoSrp("[server] Received DNS update from %s", - aMetadata.IsDirectRxFromClient() ? aMetadata.mMessageInfo->GetPeerAddr().ToString().AsCString() - : "an SRPL Partner"); + LogInfo("Received DNS update from %s", aMetadata.IsDirectRxFromClient() + ? aMetadata.mMessageInfo->GetPeerAddr().ToString().AsCString() + : "an SRPL Partner"); SuccessOrExit(error = ProcessZoneSection(aMessage, aMetadata)); if (FindOutstandingUpdate(aMetadata) != nullptr) { - otLogInfoSrp("[server] Drop duplicated SRP update request: MessageId=%hu", aMetadata.mDnsHeader.GetMessageId()); + LogInfo("Drop duplicated SRP update request: MessageId=%hu", aMetadata.mDnsHeader.GetMessageId()); // Silently drop duplicate requests. // This could rarely happen, because the outstanding SRP update timer should @@ -1160,7 +1161,7 @@ exit: mOutstandingUpdates.Push(*update); mOutstandingUpdatesTimer.FireAtIfEarlier(update->GetExpireTime()); - otLogInfoSrp("[server] SRP update handler is notified (updatedId = %u)", update->GetId()); + LogInfo("SRP update handler is notified (updatedId = %u)", update->GetId()); mServiceUpdateHandler(update->GetId(), &aHost, kDefaultEventsHandlerTimeout, mServiceUpdateHandlerContext); } else @@ -1190,17 +1191,17 @@ void Server::SendResponse(const Dns::UpdateHeader & aHeader, if (aResponseCode != Dns::UpdateHeader::kResponseSuccess) { - otLogInfoSrp("[server] send fail response: %d", aResponseCode); + LogInfo("send fail response: %d", aResponseCode); } else { - otLogInfoSrp("[server] send success response"); + LogInfo("send success response"); } exit: if (error != kErrorNone) { - otLogWarnSrp("[server] failed to send response: %s", ErrorToString(error)); + LogWarn("failed to send response: %s", ErrorToString(error)); FreeMessage(response); } } @@ -1242,12 +1243,12 @@ void Server::SendResponse(const Dns::UpdateHeader &aHeader, SuccessOrExit(error = GetSocket().SendTo(*response, aMessageInfo)); - otLogInfoSrp("[server] send response with granted lease: %u and key lease: %u", aLease, aKeyLease); + LogInfo("send response with granted lease: %u and key lease: %u", aLease, aKeyLease); exit: if (error != kErrorNone) { - otLogWarnSrp("[server] failed to send response: %s", ErrorToString(error)); + LogWarn("failed to send response: %s", ErrorToString(error)); FreeMessage(response); } } @@ -1263,7 +1264,7 @@ void Server::HandleUdpReceive(Message &aMessage, const Ip6::MessageInfo &aMessag if (error != kErrorNone) { - otLogInfoSrp("[server] failed to handle DNS message: %s", ErrorToString(error)); + LogInfo("failed to handle DNS message: %s", ErrorToString(error)); } } @@ -1314,7 +1315,7 @@ void Server::HandleLeaseTimer(void) if (host->GetKeyExpireTime() <= now) { - otLogInfoSrp("[server] KEY LEASE of host %s expired", host->GetFullName()); + LogInfo("KEY LEASE of host %s expired", host->GetFullName()); // Removes the whole host and all services if the KEY RR expired. RemoveHost(host, kDeleteName, kNotifyServiceHandler); @@ -1347,7 +1348,7 @@ void Server::HandleLeaseTimer(void) } else if (host->GetExpireTime() <= now) { - otLogInfoSrp("[server] LEASE of host %s expired", host->GetFullName()); + LogInfo("LEASE of host %s expired", host->GetFullName()); // If the host expired, delete all resources of this host and its services. for (Service &service : host->mServices) @@ -1405,13 +1406,13 @@ void Server::HandleLeaseTimer(void) OT_ASSERT(earliestExpireTime >= now); if (!mLeaseTimer.IsRunning() || earliestExpireTime <= mLeaseTimer.GetFireTime()) { - otLogInfoSrp("[server] lease timer is scheduled for %u seconds", Time::MsecToSec(earliestExpireTime - now)); + LogInfo("lease timer is scheduled for %u seconds", Time::MsecToSec(earliestExpireTime - now)); mLeaseTimer.StartAt(earliestExpireTime, 0); } } else { - otLogInfoSrp("[server] lease timer is stopped"); + LogInfo("lease timer is stopped"); mLeaseTimer.Stop(); } } @@ -1425,8 +1426,7 @@ void Server::HandleOutstandingUpdatesTimer(void) { while (!mOutstandingUpdates.IsEmpty() && mOutstandingUpdates.GetTail()->GetExpireTime() <= TimerMilli::GetNow()) { - otLogInfoSrp("[server] outstanding service update timeout (updateId = %u)", - mOutstandingUpdates.GetTail()->GetId()); + LogInfo("outstanding service update timeout (updateId = %u)", mOutstandingUpdates.GetTail()->GetId()); HandleServiceUpdateResult(mOutstandingUpdates.GetTail(), kErrorResponseTimeout); } } @@ -1540,7 +1540,7 @@ exit: return matches; } -#if (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO) && OPENTHREAD_CONFIG_LOG_SRP +#if OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO void Server::Service::Log(Action aAction) const { static const char *const kActionStrings[] = { @@ -1570,15 +1570,15 @@ void Server::Service::Log(Action aAction) const { IgnoreError(GetServiceSubTypeLabel(subLabel, sizeof(subLabel))); - otLogInfoSrp("[server] %s service '%s'%s%s", kActionStrings[aAction], GetInstanceName(), - IsSubType() ? " subtype:" : "", subLabel); + LogInfo("%s service '%s'%s%s", kActionStrings[aAction], GetInstanceName(), IsSubType() ? " subtype:" : "", + subLabel); } } #else void Server::Service::Log(Action) const { } -#endif // #if (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO) && OPENTHREAD_CONFIG_LOG_SRP +#endif // #if OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO //--------------------------------------------------------------------------------------------------------------------- // Server::Service::Description @@ -1768,7 +1768,7 @@ void Server::Host::RemoveService(Service *aService, RetainName aRetainName, Noti { uint32_t updateId = server.AllocateId(); - otLogInfoSrp("[server] SRP update handler is notified (updatedId = %u)", updateId); + LogInfo("SRP update handler is notified (updatedId = %u)", updateId); server.mServiceUpdateHandler(updateId, this, kDefaultEventsHandlerTimeout, server.mServiceUpdateHandlerContext); // We don't wait for the reply from the service update handler, // but always remove the service regardless of service update result. @@ -1808,7 +1808,7 @@ Error Server::Host::MergeServicesAndResourcesFrom(Host &aHost) Error error = kErrorNone; - otLogInfoSrp("[server] update host %s", GetFullName()); + LogInfo("update host %s", GetFullName()); mAddresses = aHost.mAddresses; mKeyRecord = aHost.mKeyRecord; @@ -1909,7 +1909,7 @@ Error Server::Host::AddIp6Address(const Ip6::Address &aIp6Address) if (error == kErrorNoBufs) { - otLogWarnSrp("[server] too many addresses for host %s", GetFullName()); + LogWarn("too many addresses for host %s", GetFullName()); } exit: diff --git a/src/core/net/tcp6.cpp b/src/core/net/tcp6.cpp index d41bd45d1..ec5101341 100644 --- a/src/core/net/tcp6.cpp +++ b/src/core/net/tcp6.cpp @@ -41,7 +41,7 @@ #include "common/code_utils.hpp" #include "common/error.hpp" #include "common/instance.hpp" -#include "common/logging.hpp" +#include "common/log.hpp" #include "common/random.hpp" #include "net/checksum.hpp" #include "net/ip6.hpp" @@ -55,6 +55,8 @@ namespace Ip6 { using ot::Encoding::BigEndian::HostSwap16; using ot::Encoding::BigEndian::HostSwap32; +RegisterLogModule("Tcp"); + Tcp::Tcp(Instance &aInstance) : InstanceLocator(aInstance) , mTimer(aInstance, Tcp::HandleTimer) @@ -319,8 +321,8 @@ void Tcp::Endpoint::SetTimer(uint8_t aTimerFlag, uint32_t aDelay) uint8_t timerIndex = TimerFlagToIndex(aTimerFlag); mTimers[timerIndex] = newFireTime.GetValue(); - otLogDebgTcp("Endpoint %p set timer %u to %u ms", static_cast(this), static_cast(timerIndex), - static_cast(aDelay)); + LogDebg("Endpoint %p set timer %u to %u ms", static_cast(this), static_cast(timerIndex), + static_cast(aDelay)); GetInstance().Get().mTimer.FireAtIfEarlier(newFireTime); } @@ -335,8 +337,8 @@ void Tcp::Endpoint::CancelTimer(uint8_t aTimerFlag) OT_UNUSED_VARIABLE(aTimerFlag); - otLogDebgTcp("Endpoint %p cancelled timer %u", static_cast(this), - static_cast(TimerFlagToIndex(aTimerFlag))); + LogDebg("Endpoint %p cancelled timer %u", static_cast(this), + static_cast(TimerFlagToIndex(aTimerFlag))); } bool Tcp::Endpoint::FirePendingTimers(TimeMilli aNow, bool &aHasFutureTimer, TimeMilli &aEarliestFutureExpiry) @@ -727,7 +729,7 @@ exit: void Tcp::HandleTimer(Timer &aTimer) { OT_ASSERT(&aTimer == &aTimer.GetInstance().Get().mTimer); - otLogDebgTcp("Main TCP timer expired"); + LogDebg("Main TCP timer expired"); aTimer.GetInstance().Get().ProcessTimers(); } @@ -785,11 +787,11 @@ restart: * timers. */ mTimer.FireAtIfEarlier(earliestPendingTimerExpiry); - otLogDebgTcp("Reset main TCP timer to %u ms", static_cast(earliestPendingTimerExpiry - now)); + LogDebg("Reset main TCP timer to %u ms", static_cast(earliestPendingTimerExpiry - now)); } else { - otLogDebgTcp("Did not reset main TCP timer"); + LogDebg("Did not reset main TCP timer"); } } @@ -837,7 +839,7 @@ void tcplp_sys_send_message(otInstance *aInstance, otMessage *aMessage, otMessag Message & message = AsCoreType(aMessage); MessageInfo &info = AsCoreType(aMessageInfo); - otLogDebgTcp("Sending TCP segment: payload_size = %d", static_cast(message.GetLength())); + LogDebg("Sending TCP segment: payload_size = %d", static_cast(message.GetLength())); IgnoreError(instance.Get().SendDatagram(message, info, kProtoTcp)); } @@ -986,7 +988,7 @@ void tcplp_sys_log(const char *aFormat, ...) vsnprintf(buffer, sizeof(buffer), aFormat, args); va_end(args); - otLogDebgTcp(buffer); + LogDebg(buffer); } void tcplp_sys_panic(const char *aFormat, ...) @@ -997,7 +999,7 @@ void tcplp_sys_panic(const char *aFormat, ...) vsnprintf(buffer, sizeof(buffer), aFormat, args); va_end(args); - otLogCritTcp(buffer); + LogCrit("%s", buffer); OT_ASSERT(false); } diff --git a/src/core/radio/trel_interface.cpp b/src/core/radio/trel_interface.cpp index 2e5515c5f..24fac85b9 100644 --- a/src/core/radio/trel_interface.cpp +++ b/src/core/radio/trel_interface.cpp @@ -42,13 +42,15 @@ #include "common/debug.hpp" #include "common/instance.hpp" #include "common/locator_getters.hpp" -#include "common/logging.hpp" +#include "common/log.hpp" #include "common/string.hpp" #include "net/dns_types.hpp" namespace ot { namespace Trel { +RegisterLogModule("TrelInterface"); + const char Interface::kTxtRecordExtAddressKey[] = "xa"; const char Interface::kTxtRecordExtPanIdKey[] = "xp"; @@ -83,7 +85,7 @@ void Interface::Enable(void) otPlatTrelEnable(&GetInstance(), &mUdpPort); - otLogInfoMac("Trel: Enabled interface, local port:%u", mUdpPort); + LogInfo("Enabled interface, local port:%u", mUdpPort); mRegisterServiceTask.Post(); exit: @@ -99,7 +101,7 @@ void Interface::Disable(void) otPlatTrelDisable(&GetInstance()); mPeerTable.Clear(); - otLogDebgMac("Trel: Disabled interface"); + LogDebg("Disabled interface"); exit: return; @@ -108,7 +110,7 @@ exit: void Interface::HandleExtAddressChange(void) { VerifyOrExit(mInitialized && mEnabled); - otLogDebgMac("Trel: Extended Address changed, re-registering DNS-SD service"); + LogDebg("Extended Address changed, re-registering DNS-SD service"); mRegisterServiceTask.Post(); exit: @@ -118,7 +120,7 @@ exit: void Interface::HandleExtPanIdChange(void) { VerifyOrExit(mInitialized && mEnabled); - otLogDebgMac("Trel: Extended PAN ID changed, re-registering DNS-SD service"); + LogDebg("Extended PAN ID changed, re-registering DNS-SD service"); mRegisterServiceTask.Post(); exit: @@ -151,9 +153,9 @@ void Interface::RegisterService(void) txtData.Init(txtDataBuffer, sizeof(txtDataBuffer)); SuccessOrAssert(Dns::TxtEntry::AppendEntries(txtEntries, GetArrayLength(txtEntries), txtData)); - otLogInfoMac("Trel: Registering DNS-SD service: port:%u, txt:\"%s=%s, %s=%s\"", mUdpPort, kTxtRecordExtAddressKey, - Get().GetExtAddress().ToString().AsCString(), kTxtRecordExtPanIdKey, - Get().GetExtendedPanId().ToString().AsCString()); + LogInfo("Registering DNS-SD service: port:%u, txt:\"%s=%s, %s=%s\"", mUdpPort, kTxtRecordExtAddressKey, + Get().GetExtAddress().ToString().AsCString(), kTxtRecordExtPanIdKey, + Get().GetExtendedPanId().ToString().AsCString()); otPlatTrelRegisterService(&GetInstance(), mUdpPort, txtData.GetBytes(), static_cast(txtData.GetLength())); @@ -385,7 +387,7 @@ exit: void Interface::HandleReceived(uint8_t *aBuffer, uint16_t aLength) { - otLogDebgMac("Trel: HandleReceived(aLength:%u)", aLength); + LogDebg("HandleReceived(aLength:%u)", aLength); VerifyOrExit(mInitialized && mEnabled && !mFiltered); @@ -412,8 +414,8 @@ void Interface::Peer::Log(const char *aAction) const { OT_UNUSED_VARIABLE(aAction); - otLogInfoMac("Trel: %s peer mac:%s, xpan:%s, %s", aAction, GetExtAddress().ToString().AsCString(), - GetExtPanId().ToString().AsCString(), GetSockAddr().ToString().AsCString()); + LogInfo("%s peer mac:%s, xpan:%s, %s", aAction, GetExtAddress().ToString().AsCString(), + GetExtPanId().ToString().AsCString(), GetSockAddr().ToString().AsCString()); } } // namespace Trel diff --git a/src/core/radio/trel_link.cpp b/src/core/radio/trel_link.cpp index 263c98f5d..549633b0c 100644 --- a/src/core/radio/trel_link.cpp +++ b/src/core/radio/trel_link.cpp @@ -38,11 +38,13 @@ #include "common/debug.hpp" #include "common/instance.hpp" #include "common/locator_getters.hpp" -#include "common/logging.hpp" +#include "common/log.hpp" namespace ot { namespace Trel { +RegisterLogModule("TrelLink"); + Link::Link(Instance &aInstance) : InstanceLocator(aInstance) , mState(kStateDisabled) @@ -219,8 +221,7 @@ void Link::BeginTransmit(void) txPacket.GetHeader().SetDestination(destAddr.GetExtended()); } - otLogDebgMac("Trel: BeginTransmit() [%s] plen:%d", txPacket.GetHeader().ToString().AsCString(), - txPacket.GetPayloadLength()); + LogDebg("BeginTransmit() [%s] plen:%d", txPacket.GetHeader().ToString().AsCString(), txPacket.GetPayloadLength()); VerifyOrExit(mInterface.Send(txPacket, isDisovery) == kErrorNone, InvokeSendDone(kErrorAbort)); @@ -372,8 +373,7 @@ void Link::ProcessReceivedPacket(Packet &aPacket) } } - otLogDebgMac("Trel: ReceivedPacket() [%s] plen:%d", aPacket.GetHeader().ToString().AsCString(), - aPacket.GetPayloadLength()); + LogDebg("ReceivedPacket() [%s] plen:%d", aPacket.GetHeader().ToString().AsCString(), aPacket.GetPayloadLength()); if (aPacket.GetHeader().GetAckMode() == Header::kAckRequested) { @@ -404,7 +404,7 @@ void Link::HandleAck(Packet &aAckPacket) Neighbor * neighbor; uint32_t ackNumber; - otLogDebgMac("Trel: HandleAck() [%s]", aAckPacket.GetHeader().ToString().AsCString()); + LogDebg("HandleAck() [%s]", aAckPacket.GetHeader().ToString().AsCString()); srcAddress.SetExtended(aAckPacket.GetHeader().GetSource()); neighbor = Get().FindNeighbor(srcAddress, Neighbor::kInStateAnyExceptInvalid); @@ -450,15 +450,15 @@ void Link::SendAck(Packet &aRxPacket) ackPacket.GetHeader().SetSource(Get().GetExtAddress()); ackPacket.GetHeader().SetDestination(aRxPacket.GetHeader().GetSource()); - otLogDebgMac("Trel: SendAck [%s]", ackPacket.GetHeader().ToString().AsCString()); + LogDebg("SendAck [%s]", ackPacket.GetHeader().ToString().AsCString()); IgnoreError(mInterface.Send(ackPacket)); } void Link::ReportDeferredAckStatus(Neighbor &aNeighbor, Error aError) { - otLogDebgMac("Trel: ReportDeferredAckStatus(): %s for %s", aNeighbor.GetExtAddress().ToString().AsCString(), - ErrorToString(aError)); + LogDebg("ReportDeferredAckStatus(): %s for %s", aNeighbor.GetExtAddress().ToString().AsCString(), + ErrorToString(aError)); Get().HandleDeferredAck(aNeighbor, aError); } @@ -467,7 +467,7 @@ void Link::SetState(State aState) { if (mState != aState) { - otLogDebgMac("Trel: State: %s -> %s", StateToString(mState), StateToString(aState)); + LogDebg("State: %s -> %s", StateToString(mState), StateToString(aState)); mState = aState; } } diff --git a/src/core/radio/trel_packet.cpp b/src/core/radio/trel_packet.cpp index aaad695f9..9b5cabdfd 100644 --- a/src/core/radio/trel_packet.cpp +++ b/src/core/radio/trel_packet.cpp @@ -38,7 +38,6 @@ #include "common/debug.hpp" #include "common/instance.hpp" #include "common/locator_getters.hpp" -#include "common/logging.hpp" namespace ot { namespace Trel { diff --git a/src/core/thread/address_resolver.cpp b/src/core/thread/address_resolver.cpp index a843e311c..c5a2c99ca 100644 --- a/src/core/thread/address_resolver.cpp +++ b/src/core/thread/address_resolver.cpp @@ -42,7 +42,7 @@ #include "common/encoding.hpp" #include "common/instance.hpp" #include "common/locator_getters.hpp" -#include "common/logging.hpp" +#include "common/log.hpp" #include "common/time.hpp" #include "mac/mac_types.hpp" #include "thread/mesh_forwarder.hpp" @@ -52,6 +52,8 @@ namespace ot { +RegisterLogModule("AddrResolver"); + AddressResolver::AddressResolver(Instance &aInstance) : InstanceLocator(aInstance) , mAddressError(UriPath::kAddressError, &AddressResolver::HandleAddressError, this) @@ -573,7 +575,7 @@ Error AddressResolver::SendAddressQuery(const Ip6::Address &aEid) SuccessOrExit(error = Get().SendMessage(*message, messageInfo)); - otLogInfoArp("Sending address query for %s", aEid.ToString().AsCString()); + LogInfo("Sending address query for %s", aEid.ToString().AsCString()); exit: @@ -585,8 +587,8 @@ exit: { uint16_t selfRloc16 = Get().GetRloc16(); - otLogInfoArp("Extending ADDR.qry to BB.qry for target=%s, rloc16=%04x(self)", aEid.ToString().AsCString(), - selfRloc16); + LogInfo("Extending ADDR.qry to BB.qry for target=%s, rloc16=%04x(self)", aEid.ToString().AsCString(), + selfRloc16); IgnoreError(Get().SendBackboneQuery(aEid, selfRloc16)); } #endif @@ -627,8 +629,8 @@ void AddressResolver::HandleAddressNotification(Coap::Message &aMessage, const I ExitNow(); } - otLogInfoArp("Received address notification from 0x%04x for %s to 0x%04x", - aMessageInfo.GetPeerAddr().GetIid().GetLocator(), target.ToString().AsCString(), rloc16); + LogInfo("Received address notification from 0x%04x for %s to 0x%04x", + aMessageInfo.GetPeerAddr().GetIid().GetLocator(), target.ToString().AsCString(), rloc16); entry = FindCacheEntry(target, list, prev); VerifyOrExit(entry != nullptr); @@ -659,7 +661,7 @@ void AddressResolver::HandleAddressNotification(Coap::Message &aMessage, const I if (Get().SendEmptyAck(aMessage, aMessageInfo) == kErrorNone) { - otLogInfoArp("Sending address notification acknowledgment"); + LogInfo("Sending address notification acknowledgment"); } Get().HandleResolved(target, kErrorNone); @@ -699,14 +701,14 @@ void AddressResolver::SendAddressError(const Ip6::Address & aTarget, SuccessOrExit(error = Get().SendMessage(*message, messageInfo)); - otLogInfoArp("Sending address error for target %s", aTarget.ToString().AsCString()); + LogInfo("Sending address error for target %s", aTarget.ToString().AsCString()); exit: if (error != kErrorNone) { FreeMessage(message); - otLogInfoArp("Failed to send address error: %s", ErrorToString(error)); + LogInfo("Failed to send address error: %s", ErrorToString(error)); } } @@ -725,13 +727,13 @@ void AddressResolver::HandleAddressError(Coap::Message &aMessage, const Ip6::Mes VerifyOrExit(aMessage.IsPostRequest(), error = kErrorDrop); - otLogInfoArp("Received address error notification"); + LogInfo("Received address error notification"); if (aMessage.IsConfirmable() && !aMessageInfo.GetSockAddr().IsMulticast()) { if (Get().SendEmptyAck(aMessage, aMessageInfo) == kErrorNone) { - otLogInfoArp("Sent address error notification acknowledgment"); + LogInfo("Sent address error notification acknowledgment"); } } @@ -786,7 +788,7 @@ exit: if (error != kErrorNone) { - otLogWarnArp("Error while processing address error notification: %s", ErrorToString(error)); + LogWarn("Error while processing address error notification: %s", ErrorToString(error)); } } @@ -804,8 +806,8 @@ void AddressResolver::HandleAddressQuery(Coap::Message &aMessage, const Ip6::Mes SuccessOrExit(Tlv::Find(aMessage, target)); - otLogInfoArp("Received address query from 0x%04x for target %s", aMessageInfo.GetPeerAddr().GetIid().GetLocator(), - target.ToString().AsCString()); + LogInfo("Received address query from 0x%04x for target %s", aMessageInfo.GetPeerAddr().GetIid().GetLocator(), + target.ToString().AsCString()); if (Get().HasUnicastAddress(target)) { @@ -834,8 +836,7 @@ void AddressResolver::HandleAddressQuery(Coap::Message &aMessage, const Ip6::Mes { uint16_t srcRloc16 = aMessageInfo.GetPeerAddr().GetIid().GetLocator(); - otLogInfoArp("Extending ADDR.qry to BB.qry for target=%s, rloc16=%04x", target.ToString().AsCString(), - srcRloc16); + LogInfo("Extending ADDR.qry to BB.qry for target=%s, rloc16=%04x", target.ToString().AsCString(), srcRloc16); IgnoreError(Get().SendBackboneQuery(target, srcRloc16)); } #endif @@ -874,7 +875,7 @@ void AddressResolver::SendAddressQueryResponse(const Ip6::Address & a SuccessOrExit(error = Get().SendMessage(*message, messageInfo)); - otLogInfoArp("Sending address notification for target %s", aTarget.ToString().AsCString()); + LogInfo("Sending address notification for target %s", aTarget.ToString().AsCString()); exit: FreeMessageOnError(message, error); @@ -942,8 +943,8 @@ void AddressResolver::HandleTimeTick(void) mQueryList.PopAfter(prev); mQueryRetryList.Push(*entry); - otLogInfoArp("Timed out waiting for address notification for %s, retry: %d", - entry->GetTarget().ToString().AsCString(), entry->GetTimeout()); + LogInfo("Timed out waiting for address notification for %s, retry: %d", + entry->GetTarget().ToString().AsCString(), entry->GetTimeout()); Get().HandleResolved(entry->GetTarget(), kErrorDrop); @@ -994,7 +995,7 @@ exit: // LCOV_EXCL_START -#if (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_NOTE) && (OPENTHREAD_CONFIG_LOG_ARP == 1) +#if OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_NOTE void AddressResolver::LogCacheEntryChange(EntryChange aChange, Reason aReason, @@ -1031,9 +1032,8 @@ void AddressResolver::LogCacheEntryChange(EntryChange aChange, static_assert(6 == kReasonEvictingForNewEntry, "kReasonEvictingForNewEntry value is incorrect"); static_assert(7 == kReasonRemovingEid, "kReasonRemovingEid value is incorrect"); - otLogNoteArp("Cache entry %s: %s, 0x%04x%s%s - %s", kChangeStrings[aChange], - aEntry.GetTarget().ToString().AsCString(), aEntry.GetRloc16(), - (aList == nullptr) ? "" : ", list:", ListToString(aList), kReasonStrings[aReason]); + LogNote("Cache entry %s: %s, 0x%04x%s%s - %s", kChangeStrings[aChange], aEntry.GetTarget().ToString().AsCString(), + aEntry.GetRloc16(), (aList == nullptr) ? "" : ", list:", ListToString(aList), kReasonStrings[aReason]); } const char *AddressResolver::ListToString(const CacheEntryList *aList) const @@ -1049,13 +1049,13 @@ exit: return str; } -#else // #if (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_NOTE) && (OPENTHREAD_CONFIG_LOG_ARP == 1) +#else // #if OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_NOTE void AddressResolver::LogCacheEntryChange(EntryChange, Reason, const CacheEntry &, CacheEntryList *) { } -#endif // #if (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_NOTE) && (OPENTHREAD_CONFIG_LOG_ARP == 1) +#endif // #if OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_NOTE // LCOV_EXCL_STOP diff --git a/src/core/thread/announce_begin_server.cpp b/src/core/thread/announce_begin_server.cpp index b23713ee2..ddac782fa 100644 --- a/src/core/thread/announce_begin_server.cpp +++ b/src/core/thread/announce_begin_server.cpp @@ -41,13 +41,15 @@ #include "common/debug.hpp" #include "common/instance.hpp" #include "common/locator_getters.hpp" -#include "common/logging.hpp" +#include "common/log.hpp" #include "meshcop/meshcop_tlvs.hpp" #include "thread/thread_netif.hpp" #include "thread/uri_paths.hpp" namespace ot { +RegisterLogModule("MeshCoP"); + AnnounceBeginServer::AnnounceBeginServer(Instance &aInstance) : AnnounceSenderBase(aInstance, AnnounceBeginServer::HandleTimer) , mAnnounceBegin(UriPath::kAnnounceBegin, &AnnounceBeginServer::HandleRequest, this) @@ -86,7 +88,7 @@ void AnnounceBeginServer::HandleRequest(Coap::Message &aMessage, const Ip6::Mess if (aMessage.IsConfirmable() && !aMessageInfo.GetSockAddr().IsMulticast()) { SuccessOrExit(Get().SendEmptyAck(aMessage, responseInfo)); - otLogInfoMeshCoP("sent announce begin response"); + LogInfo("Sent announce begin response"); } exit: diff --git a/src/core/thread/announce_sender.cpp b/src/core/thread/announce_sender.cpp index d088896d7..37246f2f2 100644 --- a/src/core/thread/announce_sender.cpp +++ b/src/core/thread/announce_sender.cpp @@ -38,7 +38,7 @@ #include "common/code_utils.hpp" #include "common/instance.hpp" #include "common/locator_getters.hpp" -#include "common/logging.hpp" +#include "common/log.hpp" #include "common/random.hpp" #include "meshcop/meshcop.hpp" #include "meshcop/meshcop_tlvs.hpp" @@ -46,6 +46,8 @@ namespace ot { +RegisterLogModule("AnnounceSender"); + //--------------------------------------------------------------------------------------------------------------------- // AnnounceSenderBase @@ -168,7 +170,7 @@ void AnnounceSender::Stop(void) { AnnounceSenderBase::Stop(); mTrickleTimer.Stop(); - otLogInfoMle("[announce-sender] Stopped"); + LogInfo("Stopped"); } void AnnounceSender::HandleTimer(Timer &aTimer) @@ -191,7 +193,7 @@ void AnnounceSender::HandleTrickleTimer(void) // message transmissions. SendAnnounce(1); - otLogInfoMle("[announce-sender] Schedule tx for one cycle"); + LogInfo("Schedule tx for one cycle"); } void AnnounceSender::HandleNotifierEvents(Events aEvents) @@ -240,7 +242,7 @@ void AnnounceSender::HandleRoleChanged(void) // desired Announce Tx cycle interval. mTrickleTimer.Start(TrickleTimer::kModeTrickle, kInterval, kInterval, kRedundancyConstant); - otLogInfoMle("[announce-sender] Started"); + LogInfo("Started"); exit: return; @@ -257,7 +259,7 @@ void AnnounceSender::HandleActiveDatasetChanged(void) SetChannelMask(channelMask); SetPeriod(kTxInterval / channelMask.GetNumberOfChannels()); - otLogInfoMle("[announce-sender] ChannelMask:%s, period:%u", GetChannelMask().ToString().AsCString(), GetPeriod()); + LogInfo("ChannelMask:%s, period:%u", GetChannelMask().ToString().AsCString(), GetPeriod()); // When channel mask is changed, we also check and update the PAN // channel. This handles the case where `ThreadChannelChanged` event @@ -273,7 +275,7 @@ exit: void AnnounceSender::HandleThreadChannelChanged(void) { SetStartingChannel(Get().GetPanChannel()); - otLogInfoMle("[announce-sender] StartingChannel:%d", GetStartingChannel()); + LogInfo("StartingChannel:%d", GetStartingChannel()); } #endif // OPENTHREAD_CONFIG_ANNOUNCE_SENDER_ENABLE diff --git a/src/core/thread/csl_tx_scheduler.cpp b/src/core/thread/csl_tx_scheduler.cpp index 5347fd71b..15beb59b9 100644 --- a/src/core/thread/csl_tx_scheduler.cpp +++ b/src/core/thread/csl_tx_scheduler.cpp @@ -31,12 +31,14 @@ #if OPENTHREAD_FTD && OPENTHREAD_CONFIG_MAC_CSL_TRANSMITTER_ENABLE #include "common/locator_getters.hpp" -#include "common/logging.hpp" +#include "common/log.hpp" #include "common/time.hpp" #include "mac/mac.hpp" namespace ot { +RegisterLogModule("CslTxScheduler"); + CslTxScheduler::Callbacks::Callbacks(Instance &aInstance) : InstanceLocator(aInstance) { @@ -253,8 +255,8 @@ void CslTxScheduler::HandleSentFrame(const Mac::TxFrame &aFrame, Error aError, C OT_ASSERT(!aFrame.GetSecurityEnabled() || aFrame.IsHeaderUpdated()); aChild.IncrementCslTxAttempts(); - otLogInfoMac("CSL tx to child %04x failed, attempt %d/%d", aChild.GetRloc16(), aChild.GetCslTxAttempts(), - kMaxCslTriggeredTxAttempts); + LogInfo("CSL tx to child %04x failed, attempt %d/%d", aChild.GetRloc16(), aChild.GetCslTxAttempts(), + kMaxCslTriggeredTxAttempts); if (aChild.GetCslTxAttempts() >= kMaxCslTriggeredTxAttempts) { diff --git a/src/core/thread/discover_scanner.cpp b/src/core/thread/discover_scanner.cpp index 3a894223d..e9560213d 100644 --- a/src/core/thread/discover_scanner.cpp +++ b/src/core/thread/discover_scanner.cpp @@ -37,7 +37,6 @@ #include "common/code_utils.hpp" #include "common/instance.hpp" #include "common/locator_getters.hpp" -#include "common/logging.hpp" #include "thread/mesh_forwarder.hpp" #include "thread/mle.hpp" #include "thread/mle_router.hpp" diff --git a/src/core/thread/dua_manager.cpp b/src/core/thread/dua_manager.cpp index 8119a6916..57789bd67 100644 --- a/src/core/thread/dua_manager.cpp +++ b/src/core/thread/dua_manager.cpp @@ -39,7 +39,7 @@ #include "common/code_utils.hpp" #include "common/instance.hpp" #include "common/locator_getters.hpp" -#include "common/logging.hpp" +#include "common/log.hpp" #include "common/settings.hpp" #include "net/ip6_address.hpp" #include "thread/mle_types.hpp" @@ -50,6 +50,8 @@ namespace ot { +RegisterLogModule("DuaManager"); + DuaManager::DuaManager(Instance &aInstance) : InstanceLocator(aInstance) , mRegistrationTask(aInstance, DuaManager::HandleRegistrationTask) @@ -156,11 +158,11 @@ Error DuaManager::GenerateDomainUnicastAddressIid(void) IgnoreError(Store()); } - otLogInfoDua("Generated DUA: %s", mDomainUnicastAddress.GetAddress().ToString().AsCString()); + LogInfo("Generated DUA: %s", mDomainUnicastAddress.GetAddress().ToString().AsCString()); } else { - otLogWarnDua("Generate DUA: %s", ErrorToString(error)); + LogWarn("Generate DUA: %s", ErrorToString(error)); } return error; @@ -174,7 +176,7 @@ Error DuaManager::SetFixedDuaInterfaceIdentifier(const Ip6::InterfaceIdentifier VerifyOrExit(mFixedDuaInterfaceIdentifier.IsUnspecified() || mFixedDuaInterfaceIdentifier != aIid); mFixedDuaInterfaceIdentifier = aIid; - otLogInfoDua("Set DUA IID: %s", mFixedDuaInterfaceIdentifier.ToString().AsCString()); + LogInfo("Set DUA IID: %s", mFixedDuaInterfaceIdentifier.ToString().AsCString()); if (Get().HasUnicastAddress(GetDomainUnicastAddress())) { @@ -203,7 +205,7 @@ void DuaManager::ClearFixedDuaInterfaceIdentifier(void) } } - otLogInfoDua("Cleared DUA IID: %s", mFixedDuaInterfaceIdentifier.ToString().AsCString()); + LogInfo("Cleared DUA IID: %s", mFixedDuaInterfaceIdentifier.ToString().AsCString()); mFixedDuaInterfaceIdentifier.Clear(); exit: @@ -254,7 +256,7 @@ void DuaManager::UpdateRegistrationDelay(uint8_t aDelay) { mDelay.mFields.mRegistrationDelay = aDelay; - otLogDebgDua("update regdelay %d", mDelay.mFields.mRegistrationDelay); + LogDebg("update regdelay %d", mDelay.mFields.mRegistrationDelay); UpdateTimeTickerRegistration(); } } @@ -284,7 +286,7 @@ void DuaManager::UpdateReregistrationDelay(void) { mDelay.mFields.mReregistrationDelay = delay; UpdateTimeTickerRegistration(); - otLogDebgDua("update reregdelay %d", mDelay.mFields.mReregistrationDelay); + LogDebg("update reregdelay %d", mDelay.mFields.mReregistrationDelay); } exit: @@ -297,7 +299,7 @@ void DuaManager::UpdateCheckDelay(uint8_t aDelay) { mDelay.mFields.mCheckDelay = aDelay; - otLogDebgDua("update checkdelay %d", mDelay.mFields.mCheckDelay); + LogDebg("update checkdelay %d", mDelay.mFields.mCheckDelay); UpdateTimeTickerRegistration(); } } @@ -355,8 +357,8 @@ void DuaManager::HandleTimeTick(void) bool attempt = false; #if OPENTHREAD_CONFIG_DUA_ENABLE - otLogDebgDua("regdelay %d, reregdelay %d, checkdelay %d", mDelay.mFields.mRegistrationDelay, - mDelay.mFields.mReregistrationDelay, mDelay.mFields.mCheckDelay); + LogDebg("regdelay %d, reregdelay %d, checkdelay %d", mDelay.mFields.mRegistrationDelay, + mDelay.mFields.mReregistrationDelay, mDelay.mFields.mCheckDelay); if ((mDuaState != kNotExist) && (TimerMilli::GetNow() > (mLastRegistrationTime + TimeMilli::SecToMsec(Mle::kDuaDadPeriod)))) @@ -369,7 +371,7 @@ void DuaManager::HandleTimeTick(void) attempt = true; } #else - otLogDebgDua("reregdelay %d, checkdelay %d", mDelay.mFields.mReregistrationDelay, mDelay.mFields.mCheckDelay); + LogDebg("reregdelay %d, checkdelay %d", mDelay.mFields.mReregistrationDelay, mDelay.mFields.mCheckDelay); #endif if ((mDelay.mFields.mCheckDelay > 0) && (--mDelay.mFields.mCheckDelay == 0)) @@ -532,7 +534,7 @@ void DuaManager::PerformNextRegistration(void) Get().SendFastPolls(); } - otLogInfoDua("Sent DUA.req for DUA %s", dua.ToString().AsCString()); + LogInfo("Sent DUA.req for DUA %s", dua.ToString().AsCString()); exit: if (error == kErrorNoBufs) @@ -540,7 +542,7 @@ exit: UpdateCheckDelay(Mle::kNoBufDelay); } - otLogInfoDua("PerformNextRegistration: %s", ErrorToString(error)); + LogInfo("PerformNextRegistration: %s", ErrorToString(error)); FreeMessageOnError(message, error); } @@ -583,7 +585,7 @@ exit: mRegistrationTask.Post(); } - otLogInfoDua("Received DUA.rsp: %s", ErrorToString(error)); + LogInfo("Received DUA.rsp: %s", ErrorToString(error)); } void DuaManager::HandleDuaNotification(void *aContext, otMessage *aMessage, const otMessageInfo *aMessageInfo) @@ -600,14 +602,14 @@ void DuaManager::HandleDuaNotification(Coap::Message &aMessage, const Ip6::Messa if (aMessage.IsConfirmable() && Get().SendEmptyAck(aMessage, aMessageInfo) == kErrorNone) { - otLogInfoDua("Sent DUA.ntf acknowledgment"); + LogInfo("Sent DUA.ntf acknowledgment"); } error = ProcessDuaResponse(aMessage); exit: OT_UNUSED_VARIABLE(error); - otLogInfoDua("Received DUA.ntf: %d", ErrorToString(error)); + LogInfo("Received DUA.ntf: %d", ErrorToString(error)); } Error DuaManager::ProcessDuaResponse(Coap::Message &aMessage) @@ -741,7 +743,7 @@ void DuaManager::SendAddressNotification(Ip6::Address & aAddress, SuccessOrExit(error = Get().SendMessage(*message, messageInfo)); - otLogInfoDua("Sent ADDR_NTF for child %04x DUA %s", aChild.GetRloc16(), aAddress.ToString().AsCString()); + LogInfo("Sent ADDR_NTF for child %04x DUA %s", aChild.GetRloc16(), aAddress.ToString().AsCString()); exit: @@ -750,8 +752,8 @@ exit: FreeMessage(message); // TODO: (DUA) (P4) may enhance to guarantee the delivery of DUA.ntf - otLogWarnDua("Sent ADDR_NTF for child %04x DUA %s Error %s", aChild.GetRloc16(), - aAddress.ToString().AsCString(), ErrorToString(error)); + LogWarn("Sent ADDR_NTF for child %04x DUA %s Error %s", aChild.GetRloc16(), aAddress.ToString().AsCString(), + ErrorToString(error)); } } diff --git a/src/core/thread/energy_scan_server.cpp b/src/core/thread/energy_scan_server.cpp index 0a2c819f4..4bd56de14 100644 --- a/src/core/thread/energy_scan_server.cpp +++ b/src/core/thread/energy_scan_server.cpp @@ -39,7 +39,7 @@ #include "common/debug.hpp" #include "common/instance.hpp" #include "common/locator_getters.hpp" -#include "common/logging.hpp" +#include "common/log.hpp" #include "meshcop/meshcop.hpp" #include "meshcop/meshcop_tlvs.hpp" #include "thread/thread_netif.hpp" @@ -47,6 +47,8 @@ namespace ot { +RegisterLogModule("EnergyScanSrv"); + EnergyScanServer::EnergyScanServer(Instance &aInstance) : InstanceLocator(aInstance) , mChannelMask(0) @@ -97,7 +99,7 @@ void EnergyScanServer::HandleRequest(Coap::Message &aMessage, const Ip6::Message if (aMessage.IsConfirmable() && !aMessageInfo.GetSockAddr().IsMulticast()) { SuccessOrExit(Get().SendEmptyAck(aMessage, responseInfo)); - otLogInfoMeshCoP("sent energy scan query response"); + LogInfo("sent energy scan query response"); } exit: @@ -194,7 +196,7 @@ void EnergyScanServer::SendReport(void) messageInfo.SetPeerPort(Tmf::kUdpPort); SuccessOrExit(error = Get().SendMessage(*message, messageInfo)); - otLogInfoMeshCoP("sent scan results"); + LogInfo("sent scan results"); exit: FreeMessageOnError(message, error); diff --git a/src/core/thread/indirect_sender.cpp b/src/core/thread/indirect_sender.cpp index 34fd2710e..a6c88b90f 100644 --- a/src/core/thread/indirect_sender.cpp +++ b/src/core/thread/indirect_sender.cpp @@ -38,7 +38,6 @@ #include "common/code_utils.hpp" #include "common/instance.hpp" #include "common/locator_getters.hpp" -#include "common/logging.hpp" #include "common/message.hpp" #include "thread/mesh_forwarder.hpp" #include "thread/mle_tlvs.hpp" diff --git a/src/core/thread/key_manager.cpp b/src/core/thread/key_manager.cpp index 08c8b3e2b..a8a3944f7 100644 --- a/src/core/thread/key_manager.cpp +++ b/src/core/thread/key_manager.cpp @@ -37,7 +37,7 @@ #include "common/encoding.hpp" #include "common/instance.hpp" #include "common/locator_getters.hpp" -#include "common/logging.hpp" +#include "common/log.hpp" #include "common/timer.hpp" #include "crypto/hkdf_sha256.hpp" #include "crypto/storage.hpp" @@ -46,6 +46,8 @@ namespace ot { +RegisterLogModule("KeyManager"); + const uint8_t KeyManager::kThreadString[] = { 'T', 'h', 'r', 'e', 'a', 'd', }; @@ -486,7 +488,7 @@ void KeyManager::SetSecurityPolicy(const SecurityPolicy &aSecurityPolicy) { if (aSecurityPolicy.mRotationTime < SecurityPolicy::kMinKeyRotationTime) { - otLogNoteMeshCoP("Key Rotation Time too small: %d", aSecurityPolicy.mRotationTime); + LogNote("Key Rotation Time too small: %d", aSecurityPolicy.mRotationTime); ExitNow(); } diff --git a/src/core/thread/link_metrics.cpp b/src/core/thread/link_metrics.cpp index 265a96c69..c4265f605 100644 --- a/src/core/thread/link_metrics.cpp +++ b/src/core/thread/link_metrics.cpp @@ -39,7 +39,7 @@ #include "common/encoding.hpp" #include "common/instance.hpp" #include "common/locator_getters.hpp" -#include "common/logging.hpp" +#include "common/log.hpp" #include "mac/mac.hpp" #include "thread/link_metrics_tlvs.hpp" #include "thread/neighbor_table.hpp" @@ -47,6 +47,8 @@ namespace ot { namespace LinkMetrics { +RegisterLogModule("LinkMetrics"); + using ot::Encoding::BigEndian::HostSwap32; void SeriesInfo::Init(uint8_t aSeriesId, const SeriesFlags &aSeriesFlags, const Metrics &aMetrics) @@ -171,7 +173,7 @@ Error LinkMetrics::SendMgmtRequestForwardTrackingSeries(const Ip6::Address & error = Get().SendLinkMetricsManagementRequest(aDestination, subTlvs, fwdProbingSubTlv->GetSize()); exit: - otLogDebgMle("SendMgmtRequestForwardTrackingSeries, error:%s, Series ID:%u", ErrorToString(error), aSeriesId); + LogDebg("SendMgmtRequestForwardTrackingSeries, error:%s, Series ID:%u", ErrorToString(error), aSeriesId); return error; } @@ -233,7 +235,7 @@ Error LinkMetrics::SendLinkProbe(const Ip6::Address &aDestination, uint8_t aSeri error = Get().SendLinkProbe(aDestination, aSeriesId, buf, aLength); exit: - otLogDebgMle("SendLinkProbe, error:%s, Series ID:%u", ErrorToString(error), aSeriesId); + LogDebg("SendLinkProbe, error:%s, Series ID:%u", ErrorToString(error), aSeriesId); return error; } #endif // OPENTHREAD_CONFIG_MLE_LINK_METRICS_INITIATOR_ENABLE @@ -332,7 +334,7 @@ Error LinkMetrics::AppendReport(Message &aMessage, const Message &aRequestMessag aMessage.Write(startOffset, tlv); exit: - otLogDebgMle("AppendReport, error:%s", ErrorToString(error)); + LogDebg("AppendReport, error:%s", ErrorToString(error)); return error; } @@ -510,14 +512,14 @@ void LinkMetrics::HandleReport(const Message & aMessage, SuccessOrExit(aMessage.Read(pos, values.mPduCountValue)); values.mPduCountValue = HostSwap32(values.mPduCountValue); pos += sizeof(uint32_t); - otLogDebgMle(" - PDU Counter: %d (Count/Summation)", values.mPduCountValue); + LogDebg(" - PDU Counter: %d (Count/Summation)", values.mPduCountValue); break; case TypeIdFlags::kLqi: values.GetMetrics().mLqi = true; SuccessOrExit(aMessage.Read(pos, values.mLqiValue)); pos += sizeof(uint8_t); - otLogDebgMle(" - LQI: %d (Exponential Moving Average)", values.mLqiValue); + LogDebg(" - LQI: %d (Exponential Moving Average)", values.mLqiValue); break; case TypeIdFlags::kLinkMargin: @@ -526,7 +528,7 @@ void LinkMetrics::HandleReport(const Message & aMessage, // Reverse operation for linear scale, map from [0, 255] to [0, 130] values.mLinkMarginValue = rawValue * 130 / 255; pos += sizeof(uint8_t); - otLogDebgMle(" - Margin: %d (dB) (Exponential Moving Average)", values.mLinkMarginValue); + LogDebg(" - Margin: %d (dB) (Exponential Moving Average)", values.mLinkMarginValue); break; case TypeIdFlags::kRssi: @@ -535,7 +537,7 @@ void LinkMetrics::HandleReport(const Message & aMessage, // Reverse operation for linear scale, map from [0, 255] to [-130, 0] values.mRssiValue = rawValue * 130 / 255 - 130; pos += sizeof(uint8_t); - otLogDebgMle(" - RSSI: %d (dBm) (Exponential Moving Average)", values.mRssiValue); + LogDebg(" - RSSI: %d (dBm) (Exponential Moving Average)", values.mRssiValue); break; default: @@ -555,7 +557,7 @@ void LinkMetrics::HandleReport(const Message & aMessage, } exit: - otLogDebgMle("HandleReport, error:%s", ErrorToString(error)); + LogDebg("HandleReport, error:%s", ErrorToString(error)); return; } diff --git a/src/core/thread/mesh_forwarder.cpp b/src/core/thread/mesh_forwarder.cpp index c62257578..60c504b41 100644 --- a/src/core/thread/mesh_forwarder.cpp +++ b/src/core/thread/mesh_forwarder.cpp @@ -38,7 +38,6 @@ #include "common/encoding.hpp" #include "common/instance.hpp" #include "common/locator_getters.hpp" -#include "common/logging.hpp" #include "common/message.hpp" #include "common/random.hpp" #include "common/time_ticker.hpp" @@ -54,6 +53,8 @@ namespace ot { +RegisterLogModule("MeshForwarder"); + void ThreadLinkInfo::SetFrom(const Mac::RxFrame &aFrame) { Clear(); @@ -522,7 +523,7 @@ Mac::TxFrame *MeshForwarder::HandleFrameRequest(Mac::TxFrames &aTxFrames) if ((mSendMessage->GetSubType() == Message::kSubTypeMleChildIdRequest) && mSendMessage->IsLinkSecurityEnabled()) { - otLogNoteMac("Child ID Request requires fragmentation, aborting tx"); + LogNote("Child ID Request requires fragmentation, aborting tx"); mMessageNextOffset = mSendMessage->GetLength(); ExitNow(frame = nullptr); } @@ -970,8 +971,8 @@ void MeshForwarder::HandleDeferredAck(Neighbor &aNeighbor, Error aError) if (aError == kErrorNoAck) { - otLogInfoMac("Deferred ack timeout on trel for neighbor %s rloc16:0x%04x", - aNeighbor.GetExtAddress().ToString().AsCString(), aNeighbor.GetRloc16()); + LogInfo("Deferred ack timeout on trel for neighbor %s rloc16:0x%04x", + aNeighbor.GetExtAddress().ToString().AsCString(), aNeighbor.GetRloc16()); } #if OPENTHREAD_CONFIG_MULTI_RADIO @@ -1102,7 +1103,7 @@ void MeshForwarder::UpdateSendMessage(Error aFrameTxError, Mac::Address &aMacDes // shorter Child ID Request message (by only including mesh-local // address in the Address Registration TLV). - otLogInfoMac("Requesting shorter `Child ID Request`"); + LogInfo("Requesting shorter `Child ID Request`"); Get().RequestShorterChildIdRequest(); } @@ -1570,7 +1571,7 @@ Error MeshForwarder::SendEmptyMessage(void) exit: FreeMessageOnError(message, error); - otLogDebgMac("Send empty message, error:%s", ErrorToString(error)); + LogDebg("Send empty message, error:%s", ErrorToString(error)); return error; } #endif // OPENTHREAD_CONFIG_REFERENCE_DEVICE_ENABLE @@ -1703,7 +1704,7 @@ exit: return error; } -#if (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_NOTE) && (OPENTHREAD_CONFIG_LOG_MAC == 1) +#if OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_NOTE const char *MeshForwarder::MessageActionToString(MessageAction aAction, Error aError) { @@ -1735,28 +1736,28 @@ const char *MeshForwarder::MessagePriorityToString(const Message &aMessage) void MeshForwarder::LogIp6SourceDestAddresses(Ip6::Header &aIp6Header, uint16_t aSourcePort, uint16_t aDestPort, - otLogLevel aLogLevel) + LogLevel aLogLevel) { if (aSourcePort != 0) { - otLogMac(aLogLevel, " src:[%s]:%d", aIp6Header.GetSource().ToString().AsCString(), aSourcePort); + LogAt(aLogLevel, " src:[%s]:%d", aIp6Header.GetSource().ToString().AsCString(), aSourcePort); } else { - otLogMac(aLogLevel, " src:[%s]", aIp6Header.GetSource().ToString().AsCString()); + LogAt(aLogLevel, " src:[%s]", aIp6Header.GetSource().ToString().AsCString()); } if (aDestPort != 0) { - otLogMac(aLogLevel, " dst:[%s]:%d", aIp6Header.GetDestination().ToString().AsCString(), aDestPort); + LogAt(aLogLevel, " dst:[%s]:%d", aIp6Header.GetDestination().ToString().AsCString(), aDestPort); } else { - otLogMac(aLogLevel, " dst:[%s]", aIp6Header.GetDestination().ToString().AsCString()); + LogAt(aLogLevel, " dst:[%s]", aIp6Header.GetDestination().ToString().AsCString()); } } #else -void MeshForwarder::LogIp6SourceDestAddresses(Ip6::Header &, uint16_t, uint16_t, otLogLevel) +void MeshForwarder::LogIp6SourceDestAddresses(Ip6::Header &, uint16_t, uint16_t, LogLevel) { } #endif @@ -1765,7 +1766,7 @@ void MeshForwarder::LogIp6Message(MessageAction aAction, const Message & aMessage, const Mac::Address *aMacAddress, Error aError, - otLogLevel aLogLevel) + LogLevel aLogLevel) { Ip6::Header ip6Header; uint16_t checksum; @@ -1784,16 +1785,16 @@ void MeshForwarder::LogIp6Message(MessageAction aAction, radioString = aMessage.IsRadioTypeSet() ? RadioTypeToString(aMessage.GetRadioType()) : "all"; #endif - otLogMac(aLogLevel, "%s IPv6 %s msg, len:%d, chksum:%04x%s%s, sec:%s%s%s, prio:%s%s%s%s%s", - MessageActionToString(aAction, aError), Ip6::Ip6::IpProtoToString(ip6Header.GetNextHeader()), - aMessage.GetLength(), checksum, - (aMacAddress == nullptr) ? "" : ((aAction == kMessageReceive) ? ", from:" : ", to:"), - (aMacAddress == nullptr) ? "" : aMacAddress->ToString().AsCString(), - ToYesNo(aMessage.IsLinkSecurityEnabled()), - (aError == kErrorNone) ? "" : ", error:", (aError == kErrorNone) ? "" : ErrorToString(aError), - MessagePriorityToString(aMessage), shouldLogRss ? ", rss:" : "", - shouldLogRss ? aMessage.GetRssAverager().ToString().AsCString() : "", shouldLogRadio ? ", radio:" : "", - radioString); + LogAt(aLogLevel, "%s IPv6 %s msg, len:%d, chksum:%04x%s%s, sec:%s%s%s, prio:%s%s%s%s%s", + MessageActionToString(aAction, aError), Ip6::Ip6::IpProtoToString(ip6Header.GetNextHeader()), + aMessage.GetLength(), checksum, + (aMacAddress == nullptr) ? "" : ((aAction == kMessageReceive) ? ", from:" : ", to:"), + (aMacAddress == nullptr) ? "" : aMacAddress->ToString().AsCString(), + ToYesNo(aMessage.IsLinkSecurityEnabled()), + (aError == kErrorNone) ? "" : ", error:", (aError == kErrorNone) ? "" : ErrorToString(aError), + MessagePriorityToString(aMessage), shouldLogRss ? ", rss:" : "", + shouldLogRss ? aMessage.GetRssAverager().ToString().AsCString() : "", shouldLogRadio ? ", radio:" : "", + radioString); if (aAction != kMessagePrepareIndirect) { @@ -1809,20 +1810,20 @@ void MeshForwarder::LogMessage(MessageAction aAction, const Mac::Address *aMacAddress, Error aError) { - otLogLevel logLevel = OT_LOG_LEVEL_INFO; + LogLevel logLevel = kLogLevelInfo; switch (aAction) { case kMessageReceive: case kMessageTransmit: case kMessagePrepareIndirect: - logLevel = (aError == kErrorNone) ? OT_LOG_LEVEL_INFO : OT_LOG_LEVEL_NOTE; + logLevel = (aError == kErrorNone) ? kLogLevelInfo : kLogLevelNote; break; case kMessageDrop: case kMessageReassemblyDrop: case kMessageEvict: - logLevel = OT_LOG_LEVEL_NOTE; + logLevel = kLogLevelNote; break; } @@ -1852,11 +1853,11 @@ void MeshForwarder::LogFrame(const char *aActionText, const Mac::Frame &aFrame, { if (aError != kErrorNone) { - otLogNoteMac("%s, aError:%s, %s", aActionText, ErrorToString(aError), aFrame.ToInfoString().AsCString()); + LogNote("%s, aError:%s, %s", aActionText, ErrorToString(aError), aFrame.ToInfoString().AsCString()); } else { - otLogInfoMac("%s, %s", aActionText, aFrame.ToInfoString().AsCString()); + LogInfo("%s, %s", aActionText, aFrame.ToInfoString().AsCString()); } } @@ -1867,10 +1868,10 @@ void MeshForwarder::LogFragmentFrameDrop(Error aError, const Lowpan::FragmentHeader &aFragmentHeader, bool aIsSecure) { - otLogNoteMac("Dropping rx frag frame, error:%s, len:%d, src:%s, dst:%s, tag:%d, offset:%d, dglen:%d, sec:%s", - ErrorToString(aError), aFrameLength, aMacSource.ToString().AsCString(), - aMacDest.ToString().AsCString(), aFragmentHeader.GetDatagramTag(), aFragmentHeader.GetDatagramOffset(), - aFragmentHeader.GetDatagramSize(), ToYesNo(aIsSecure)); + LogNote("Dropping rx frag frame, error:%s, len:%d, src:%s, dst:%s, tag:%d, offset:%d, dglen:%d, sec:%s", + ErrorToString(aError), aFrameLength, aMacSource.ToString().AsCString(), aMacDest.ToString().AsCString(), + aFragmentHeader.GetDatagramTag(), aFragmentHeader.GetDatagramOffset(), aFragmentHeader.GetDatagramSize(), + ToYesNo(aIsSecure)); } void MeshForwarder::LogLowpanHcFrameDrop(Error aError, @@ -1879,11 +1880,11 @@ void MeshForwarder::LogLowpanHcFrameDrop(Error aError, const Mac::Address &aMacDest, bool aIsSecure) { - otLogNoteMac("Dropping rx lowpan HC frame, error:%s, len:%d, src:%s, dst:%s, sec:%s", ErrorToString(aError), - aFrameLength, aMacSource.ToString().AsCString(), aMacDest.ToString().AsCString(), ToYesNo(aIsSecure)); + LogNote("Dropping rx lowpan HC frame, error:%s, len:%d, src:%s, dst:%s, sec:%s", ErrorToString(aError), + aFrameLength, aMacSource.ToString().AsCString(), aMacDest.ToString().AsCString(), ToYesNo(aIsSecure)); } -#else // #if (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_NOTE) && (OPENTHREAD_CONFIG_LOG_MAC == 1) +#else // #if OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_NOTE void MeshForwarder::LogMessage(MessageAction, const Message &, const Mac::Address *, Error) { @@ -1906,7 +1907,7 @@ void MeshForwarder::LogLowpanHcFrameDrop(Error, uint16_t, const Mac::Address &, { } -#endif // #if (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_NOTE) && (OPENTHREAD_CONFIG_LOG_MAC == 1) +#endif // #if OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_NOTE // LCOV_EXCL_STOP diff --git a/src/core/thread/mesh_forwarder.hpp b/src/core/thread/mesh_forwarder.hpp index a0847a773..738b9b0e8 100644 --- a/src/core/thread/mesh_forwarder.hpp +++ b/src/core/thread/mesh_forwarder.hpp @@ -39,6 +39,7 @@ #include "common/as_core_type.hpp" #include "common/clearable.hpp" #include "common/locator.hpp" +#include "common/log.hpp" #include "common/non_copyable.hpp" #include "common/tasklet.hpp" #include "common/time_ticker.hpp" @@ -535,7 +536,7 @@ private: otError ForwardDuaToBackboneLink(Message &aMessage, const Ip6::Address &aDst); #endif -#if (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_NOTE) && (OPENTHREAD_CONFIG_LOG_MAC == 1) +#if OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_NOTE const char *MessageActionToString(MessageAction aAction, Error aError); const char *MessagePriorityToString(const Message &aMessage); @@ -555,28 +556,28 @@ private: uint16_t & aOffset, Mac::Address & aMeshSource, Mac::Address & aMeshDest, - otLogLevel aLogLevel); + LogLevel aLogLevel); void LogMeshIpHeader(const Message & aMessage, uint16_t aOffset, const Mac::Address &aMeshSource, const Mac::Address &aMeshDest, - otLogLevel aLogLevel); + LogLevel aLogLevel); void LogMeshMessage(MessageAction aAction, const Message & aMessage, const Mac::Address *aAddress, Error aError, - otLogLevel aLogLevel); + LogLevel aLogLevel); #endif void LogIp6SourceDestAddresses(Ip6::Header &aIp6Header, uint16_t aSourcePort, uint16_t aDestPort, - otLogLevel aLogLevel); + LogLevel aLogLevel); void LogIp6Message(MessageAction aAction, const Message & aMessage, const Mac::Address *aAddress, Error aError, - otLogLevel aLogLevel); -#endif // #if (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_NOTE) && (OPENTHREAD_CONFIG_LOG_MAC == 1) + LogLevel aLogLevel); +#endif // #if OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_NOTE PriorityQueue mSendQueue; MessageQueue mReassemblyList; diff --git a/src/core/thread/mesh_forwarder_ftd.cpp b/src/core/thread/mesh_forwarder_ftd.cpp index 0f9208670..ecc556cd6 100644 --- a/src/core/thread/mesh_forwarder_ftd.cpp +++ b/src/core/thread/mesh_forwarder_ftd.cpp @@ -36,7 +36,6 @@ #if OPENTHREAD_FTD #include "common/locator_getters.hpp" -#include "common/logging.hpp" #include "meshcop/meshcop.hpp" #include "net/ip6.hpp" #include "net/tcp6.hpp" @@ -44,6 +43,8 @@ namespace ot { +RegisterLogModule("MeshForwarder"); + Error MeshForwarder::SendMessage(Message &aMessage) { Mle::MleRouter &mle = Get(); @@ -835,8 +836,8 @@ exit: if (error != kErrorNone) { - otLogInfoMac("Dropping rx mesh frame, error:%s, len:%d, src:%s, sec:%s", ErrorToString(error), aFrameLength, - aMacSource.ToString().AsCString(), ToYesNo(aLinkInfo.IsLinkSecurityEnabled())); + LogInfo("Dropping rx mesh frame, error:%s, len:%d, src:%s, sec:%s", ErrorToString(error), aFrameLength, + aMacSource.ToString().AsCString(), ToYesNo(aLinkInfo.IsLinkSecurityEnabled())); FreeMessage(message); } } @@ -1010,8 +1011,8 @@ void MeshForwarder::GetForwardFramePriority(const uint8_t * aFrame, exit: if (error != kErrorNone) { - otLogNoteMac("Failed to get forwarded frame priority, error:%s, len:%d, src:%d, dst:%s", ErrorToString(error), - aFrameLength, aMeshSource.ToString().AsCString(), aMeshDest.ToString().AsCString()); + LogNote("Failed to get forwarded frame priority, error:%s, len:%d, src:%d, dst:%s", ErrorToString(error), + aFrameLength, aMeshSource.ToString().AsCString(), aMeshDest.ToString().AsCString()); } else if (isFragment) { @@ -1023,7 +1024,7 @@ exit: // LCOV_EXCL_START -#if (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_NOTE) && (OPENTHREAD_CONFIG_LOG_MAC == 1) +#if OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_NOTE Error MeshForwarder::LogMeshFragmentHeader(MessageAction aAction, const Message & aMessage, @@ -1032,7 +1033,7 @@ Error MeshForwarder::LogMeshFragmentHeader(MessageAction aAction, uint16_t & aOffset, Mac::Address & aMeshSource, Mac::Address & aMeshDest, - otLogLevel aLogLevel) + LogLevel aLogLevel) { Error error = kErrorFailed; bool hasFragmentHeader = false; @@ -1063,20 +1064,20 @@ Error MeshForwarder::LogMeshFragmentHeader(MessageAction aAction, radioString = aMessage.IsRadioTypeSet() ? RadioTypeToString(aMessage.GetRadioType()) : "all"; #endif - otLogMac(aLogLevel, "%s mesh frame, len:%d%s%s, msrc:%s, mdst:%s, hops:%d, frag:%s, sec:%s%s%s%s%s%s%s", - MessageActionToString(aAction, aError), aMessage.GetLength(), - (aMacAddress == nullptr) ? "" : ((aAction == kMessageReceive) ? ", from:" : ", to:"), - (aMacAddress == nullptr) ? "" : aMacAddress->ToString().AsCString(), aMeshSource.ToString().AsCString(), - aMeshDest.ToString().AsCString(), meshHeader.GetHopsLeft() + ((aAction == kMessageReceive) ? 1 : 0), - ToYesNo(hasFragmentHeader), ToYesNo(aMessage.IsLinkSecurityEnabled()), - (aError == kErrorNone) ? "" : ", error:", (aError == kErrorNone) ? "" : ErrorToString(aError), - shouldLogRss ? ", rss:" : "", shouldLogRss ? aMessage.GetRssAverager().ToString().AsCString() : "", - shouldLogRadio ? ", radio:" : "", radioString); + LogAt(aLogLevel, "%s mesh frame, len:%d%s%s, msrc:%s, mdst:%s, hops:%d, frag:%s, sec:%s%s%s%s%s%s%s", + MessageActionToString(aAction, aError), aMessage.GetLength(), + (aMacAddress == nullptr) ? "" : ((aAction == kMessageReceive) ? ", from:" : ", to:"), + (aMacAddress == nullptr) ? "" : aMacAddress->ToString().AsCString(), aMeshSource.ToString().AsCString(), + aMeshDest.ToString().AsCString(), meshHeader.GetHopsLeft() + ((aAction == kMessageReceive) ? 1 : 0), + ToYesNo(hasFragmentHeader), ToYesNo(aMessage.IsLinkSecurityEnabled()), + (aError == kErrorNone) ? "" : ", error:", (aError == kErrorNone) ? "" : ErrorToString(aError), + shouldLogRss ? ", rss:" : "", shouldLogRss ? aMessage.GetRssAverager().ToString().AsCString() : "", + shouldLogRadio ? ", radio:" : "", radioString); if (hasFragmentHeader) { - otLogMac(aLogLevel, " Frag tag:%04x, offset:%d, size:%d", fragmentHeader.GetDatagramTag(), - fragmentHeader.GetDatagramOffset(), fragmentHeader.GetDatagramSize()); + LogAt(aLogLevel, " Frag tag:%04x, offset:%d, size:%d", fragmentHeader.GetDatagramTag(), + fragmentHeader.GetDatagramOffset(), fragmentHeader.GetDatagramSize()); VerifyOrExit(fragmentHeader.GetDatagramOffset() == 0); } @@ -1163,7 +1164,7 @@ void MeshForwarder::LogMeshIpHeader(const Message & aMessage, uint16_t aOffset, const Mac::Address &aMeshSource, const Mac::Address &aMeshDest, - otLogLevel aLogLevel) + LogLevel aLogLevel) { uint16_t checksum; uint16_t sourcePort; @@ -1173,8 +1174,8 @@ void MeshForwarder::LogMeshIpHeader(const Message & aMessage, SuccessOrExit(DecompressIp6UdpTcpHeader(aMessage, aOffset, aMeshSource, aMeshDest, ip6Header, checksum, sourcePort, destPort)); - otLogMac(aLogLevel, " IPv6 %s msg, chksum:%04x, prio:%s", Ip6::Ip6::IpProtoToString(ip6Header.GetNextHeader()), - checksum, MessagePriorityToString(aMessage)); + LogAt(aLogLevel, " IPv6 %s msg, chksum:%04x, prio:%s", Ip6::Ip6::IpProtoToString(ip6Header.GetNextHeader()), + checksum, MessagePriorityToString(aMessage)); LogIp6SourceDestAddresses(ip6Header, sourcePort, destPort, aLogLevel); @@ -1186,7 +1187,7 @@ void MeshForwarder::LogMeshMessage(MessageAction aAction, const Message & aMessage, const Mac::Address *aMacAddress, Error aError, - otLogLevel aLogLevel) + LogLevel aLogLevel) { uint16_t offset; Mac::Address meshSource; @@ -1208,7 +1209,7 @@ exit: return; } -#endif // #if (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_NOTE) && (OPENTHREAD_CONFIG_LOG_MAC == 1) +#endif // #if OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_NOTE // LCOV_EXCL_STOP diff --git a/src/core/thread/mle.cpp b/src/core/thread/mle.cpp index 4091a554a..0fa5a201c 100644 --- a/src/core/thread/mle.cpp +++ b/src/core/thread/mle.cpp @@ -43,7 +43,7 @@ #include "common/encoding.hpp" #include "common/instance.hpp" #include "common/locator_getters.hpp" -#include "common/logging.hpp" +#include "common/log.hpp" #include "common/random.hpp" #include "common/serial_number.hpp" #include "common/settings.hpp" @@ -64,6 +64,8 @@ using ot::Encoding::BigEndian::HostSwap16; namespace ot { namespace Mle { +RegisterLogModule("Mle"); + Mle::Mle(Instance &aInstance) : InstanceLocator(aInstance) , mRetrieveNewNetworkData(false) @@ -268,7 +270,7 @@ void Mle::SetRole(DeviceRole aRole) SuccessOrExit(Get().Update(mRole, aRole, kEventThreadRoleChanged)); - otLogNoteMle("Role %s -> %s", RoleToString(oldRole), RoleToString(mRole)); + LogNote("Role %s -> %s", RoleToString(oldRole), RoleToString(mRole)); switch (mRole) { @@ -302,7 +304,7 @@ exit: void Mle::SetAttachState(AttachState aState) { VerifyOrExit(aState != mAttachState); - otLogInfoMle("AttachState %s -> %s", AttachStateToString(mAttachState), AttachStateToString(aState)); + LogInfo("AttachState %s -> %s", AttachStateToString(mAttachState), AttachStateToString(aState)); mAttachState = aState; exit: @@ -365,8 +367,8 @@ Error Mle::Restore(void) // setting by skipping the re-attach ("Child Update Request" // exchange) and going through the full attach process. - otLogWarnMle("Invalid settings - no saved parent info with valid end-device RLOC16 0x%04x", - networkInfo.GetRloc16()); + LogWarn("Invalid settings - no saved parent info with valid end-device RLOC16 0x%04x", + networkInfo.GetRloc16()); ExitNow(); } @@ -452,7 +454,7 @@ Error Mle::Store(void) Get().SetStoredMleFrameCounter(networkInfo.GetMleFrameCounter()); Get().SetStoredMacFrameCounter(networkInfo.GetMacFrameCounter()); - otLogDebgMle("Store Network Information"); + LogDebg("Store Network Information"); exit: return error; @@ -591,8 +593,8 @@ uint32_t Mle::GetAttachStartDelay(void) const delay += jitter; } - otLogNoteMle("Attach attempt %d unsuccessful, will try again in %u.%03u seconds", mAttachCounter, delay / 1000, - delay % 1000); + LogNote("Attach attempt %d unsuccessful, will try again in %u.%03u seconds", mAttachCounter, delay / 1000, + delay % 1000); exit: return delay; @@ -759,7 +761,7 @@ Error Mle::SetDeviceMode(DeviceMode aDeviceMode) Get().EmitDeviceMode(mDeviceMode); #endif - otLogNoteMle("Mode 0x%02x -> 0x%02x [%s]", oldMode.Get(), mDeviceMode.Get(), mDeviceMode.ToString().AsCString()); + LogNote("Mode 0x%02x -> 0x%02x [%s]", oldMode.Get(), mDeviceMode.Get(), mDeviceMode.ToString().AsCString()); IgnoreError(Store()); @@ -920,7 +922,7 @@ void Mle::SetRloc16(uint16_t aRloc16) if (aRloc16 != oldRloc16) { - otLogNoteMle("RLOC16 %04x -> %04x", oldRloc16, aRloc16); + LogNote("RLOC16 %04x -> %04x", oldRloc16, aRloc16); } if (Get().HasUnicastAddress(mMeshLocal16) && @@ -1764,13 +1766,13 @@ void Mle::HandleAttachTimer(void) case kAttachStateStart: if (mAttachCounter > 0) { - otLogNoteMle("Attempt to attach - attempt %d, %s %s", mAttachCounter, - AttachModeToString(mParentRequestMode), ReattachStateToString(mReattachState)); + LogNote("Attempt to attach - attempt %d, %s %s", mAttachCounter, AttachModeToString(mParentRequestMode), + ReattachStateToString(mReattachState)); } else { - otLogNoteMle("Attempt to attach - %s %s", AttachModeToString(mParentRequestMode), - ReattachStateToString(mReattachState)); + LogNote("Attempt to attach - %s %s", AttachModeToString(mParentRequestMode), + ReattachStateToString(mReattachState)); } SetAttachState(kAttachStateParentRequestRouter); @@ -2128,7 +2130,7 @@ Error Mle::SendChildIdRequest(void) { if (IsChild()) { - otLogInfoMle("Already attached to candidate parent"); + LogInfo("Already attached to candidate parent"); ExitNow(error = kErrorAlready); } else @@ -2373,7 +2375,7 @@ Error Mle::SendChildUpdateRequest(void) if (!mParent.IsStateValidOrRestoring()) { - otLogWarnMle("No valid parent when sending Child Update Request"); + LogWarn("No valid parent when sending Child Update Request"); IgnoreError(BecomeDetached()); ExitNow(); } @@ -2564,7 +2566,7 @@ void Mle::SendAnnounce(uint8_t aChannel, const Ip6::Address &aDestination, Annou SuccessOrExit(error = SendMessage(*message, aDestination)); - otLogInfoMle("Send Announce on channel %d", aChannel); + LogInfo("Send Announce on channel %d", aChannel); exit: FreeMessageOnError(message, error); @@ -2748,7 +2750,7 @@ void Mle::HandleUdpReceive(Message &aMessage, const Ip6::MessageInfo &aMessageIn Neighbor * neighbor; bool skipLoggingError = false; - otLogDebgMle("Receive UDP message"); + LogDebg("Receive UDP message"); VerifyOrExit(aMessageInfo.GetLinkInfo() != nullptr); VerifyOrExit(aMessageInfo.GetHopLimit() == kMleHopLimit, error = kErrorParse); @@ -3838,7 +3840,7 @@ void Mle::HandleChildUpdateRequest(const Message &aMessage, const Ip6::MessageIn { if (numTlvs >= sizeof(tlvs)) { - otLogWarnMle("Failed to respond with TLVs: %d of %d", i, requestedTlvs.mNumTlvs); + LogWarn("Failed to respond with TLVs: %d of %d", i, requestedTlvs.mNumTlvs); break; } @@ -4033,7 +4035,7 @@ void Mle::HandleAnnounce(const Message &aMessage, const Ip6::MessageInfo &aMessa mAttachTimer.Start(kAnnounceProcessTimeout); mAttachCounter = 0; - otLogNoteMle("Delay processing Announce - channel %d, panid 0x%02x", channel, panId); + LogNote("Delay processing Announce - channel %d, panid 0x%02x", channel, panId); } else if (MeshCoP::Timestamp::Compare(×tamp, localTimestamp) < 0) { @@ -4122,7 +4124,7 @@ void Mle::ProcessAnnounce(void) OT_ASSERT(mAttachState == kAttachStateProcessAnnounce); - otLogNoteMle("Processing Announce - channel %d, panid 0x%02x", newChannel, newPanId); + LogNote("Processing Announce - channel %d, panid 0x%02x", newChannel, newPanId); Stop(kKeepNetworkDatasets); @@ -4190,13 +4192,13 @@ void Mle::InformPreviousParent(void) SuccessOrExit(error = Get().SendDatagram(*message, messageInfo, Ip6::kProtoNone)); - otLogNoteMle("Sending message to inform previous parent 0x%04x", mPreviousParentRloc); + LogNote("Sending message to inform previous parent 0x%04x", mPreviousParentRloc); exit: if (error != kErrorNone) { - otLogWarnMle("Failed to inform previous parent: %s", ErrorToString(error)); + LogWarn("Failed to inform previous parent: %s", ErrorToString(error)); FreeMessage(message); } @@ -4213,7 +4215,7 @@ void Mle::HandleParentSearchTimer(void) { int8_t parentRss; - otLogInfoMle("PeriodicParentSearch: %s interval passed", mParentSearchIsInBackoff ? "Backoff" : "Check"); + LogInfo("PeriodicParentSearch: %s interval passed", mParentSearchIsInBackoff ? "Backoff" : "Check"); if (mParentSearchBackoffWasCanceled) { @@ -4224,7 +4226,7 @@ void Mle::HandleParentSearchTimer(void) if (TimerMilli::GetNow() - mParentSearchBackoffCancelTime >= kParentSearchBackoffInterval) { mParentSearchBackoffWasCanceled = false; - otLogInfoMle("PeriodicParentSearch: Backoff cancellation is allowed on parent switch"); + LogInfo("PeriodicParentSearch: Backoff cancellation is allowed on parent switch"); } } @@ -4233,13 +4235,12 @@ void Mle::HandleParentSearchTimer(void) VerifyOrExit(IsChild()); parentRss = GetParent().GetLinkInfo().GetAverageRss(); - otLogInfoMle("PeriodicParentSearch: Parent RSS %d", parentRss); + LogInfo("PeriodicParentSearch: Parent RSS %d", parentRss); VerifyOrExit(parentRss != OT_RADIO_RSSI_INVALID); if (parentRss < kParentSearchRssThreadhold) { - otLogInfoMle("PeriodicParentSearch: Parent RSS less than %d, searching for new parents", - kParentSearchRssThreadhold); + LogInfo("PeriodicParentSearch: Parent RSS less than %d, searching for new parents", kParentSearchRssThreadhold); mParentSearchIsInBackoff = true; IgnoreError(BecomeChild(kAttachAny)); } @@ -4265,8 +4266,7 @@ void Mle::StartParentSearchTimer(void) mParentSearchTimer.Start(interval); - otLogInfoMle("PeriodicParentSearch: (Re)starting timer for %s interval", - mParentSearchIsInBackoff ? "backoff" : "check"); + LogInfo("PeriodicParentSearch: (Re)starting timer for %s interval", mParentSearchIsInBackoff ? "backoff" : "check"); } void Mle::UpdateParentSearchState(void) @@ -4295,7 +4295,7 @@ void Mle::UpdateParentSearchState(void) mParentSearchIsInBackoff = false; mParentSearchBackoffWasCanceled = true; mParentSearchBackoffCancelTime = TimerMilli::GetNow(); - otLogInfoMle("PeriodicParentSearch: Canceling backoff on switching to a new parent"); + LogInfo("PeriodicParentSearch: Canceling backoff on switching to a new parent"); } } @@ -4310,7 +4310,7 @@ void Mle::UpdateParentSearchState(void) } #endif // OPENTHREAD_CONFIG_PARENT_SEARCH_ENABLE -#if (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO) && (OPENTHREAD_CONFIG_LOG_MLE == 1) +#if OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO void Mle::Log(MessageAction aAction, MessageType aType, const Ip6::Address &aAddress) { Log(aAction, aType, aAddress, Mac::kShortAddrInvalid); @@ -4330,13 +4330,12 @@ void Mle::Log(MessageAction aAction, MessageType aType, const Ip6::Address &aAdd rlocString.Append(",0x%04x", aRloc); } - otLogInfoMle("%s %s%s (%s%s)", MessageActionToString(aAction), MessageTypeToString(aType), - MessageTypeActionToSuffixString(aType, aAction), aAddress.ToString().AsCString(), - rlocString.AsCString()); + LogInfo("%s %s%s (%s%s)", MessageActionToString(aAction), MessageTypeToString(aType), + MessageTypeActionToSuffixString(aType, aAction), aAddress.ToString().AsCString(), rlocString.AsCString()); } #endif -#if (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_WARN) && (OPENTHREAD_CONFIG_LOG_MLE == 1) +#if OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_WARN void Mle::LogProcessError(MessageType aType, Error aError) { LogError(kMessageReceive, aType, aError); @@ -4351,8 +4350,8 @@ void Mle::LogError(MessageAction aAction, MessageType aType, Error aError) { if (aError != kErrorNone) { - otLogWarnMle("Failed to %s %s%s: %s", aAction == kMessageSend ? "send" : "process", MessageTypeToString(aType), - MessageTypeActionToSuffixString(aType, aAction), ErrorToString(aError)); + LogWarn("Failed to %s %s%s: %s", aAction == kMessageSend ? "send" : "process", MessageTypeToString(aType), + MessageTypeActionToSuffixString(aType, aAction), ErrorToString(aError)); } } @@ -4505,7 +4504,7 @@ const char *Mle::MessageTypeActionToSuffixString(MessageType aType, MessageActio return str; } -#endif // #if (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_WARN) && (OPENTHREAD_CONFIG_LOG_MLE == 1) +#endif // #if OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_WARN const char *Mle::RoleToString(DeviceRole aRole) { @@ -4528,7 +4527,7 @@ const char *Mle::RoleToString(DeviceRole aRole) // LCOV_EXCL_START -#if (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_NOTE) && (OPENTHREAD_CONFIG_LOG_MLE == 1) +#if OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_NOTE const char *Mle::AttachModeToString(AttachMode aMode) { @@ -4589,7 +4588,7 @@ const char *Mle::ReattachStateToString(ReattachState aState) return kReattachStateStrings[aState]; } -#endif // (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_NOTE) && (OPENTHREAD_CONFIG_LOG_MLE == 1) +#endif // OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_NOTE // LCOV_EXCL_STOP diff --git a/src/core/thread/mle.hpp b/src/core/thread/mle.hpp index c2f0193fc..4d7845db4 100644 --- a/src/core/thread/mle.hpp +++ b/src/core/thread/mle.hpp @@ -1453,7 +1453,7 @@ protected: */ Error AddDelayedResponse(Message &aMessage, const Ip6::Address &aDestination, uint16_t aDelay); -#if (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO) && (OPENTHREAD_CONFIG_LOG_MLE == 1) +#if OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO /** * This static method emits a log message with an IPv6 address. * @@ -1477,9 +1477,9 @@ protected: #else static void Log(MessageAction, MessageType, const Ip6::Address &) {} static void Log(MessageAction, MessageType, const Ip6::Address &, uint16_t) {} -#endif // #if (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO) && (OPENTHREAD_CONFIG_LOG_MLE == 1) +#endif // #if OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO -#if (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_WARN) && (OPENTHREAD_CONFIG_LOG_MLE == 1) +#if OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_WARN /** * This static method emits a log message indicating an error in processing of a message. * @@ -1506,7 +1506,7 @@ protected: #else static void LogProcessError(MessageType, Error) {} static void LogSendError(MessageType, Error) {} -#endif // #if (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_WARN) && (OPENTHREAD_CONFIG_LOG_MLE == 1) +#endif // #if OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_WARN /** * This method triggers MLE Announce on previous channel after the Thread device successfully @@ -1526,7 +1526,7 @@ protected: */ bool IsAnnounceAttach(void) const { return mAlternatePanId != Mac::kPanIdBroadcast; } -#if (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_NOTE) && (OPENTHREAD_CONFIG_LOG_MLE == 1) +#if OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_NOTE /** * This method converts an `AttachMode` enumeration value into a human-readable string. * @@ -1861,7 +1861,7 @@ private: void UpdateParentSearchState(void); #endif -#if (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_WARN) && (OPENTHREAD_CONFIG_LOG_MLE == 1) +#if OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_WARN static void LogError(MessageAction aAction, MessageType aType, Error aError); static const char *MessageActionToString(MessageAction aAction); static const char *MessageTypeToString(MessageType aType); diff --git a/src/core/thread/mle_router.cpp b/src/core/thread/mle_router.cpp index 62c70cdb4..cbad84ffb 100644 --- a/src/core/thread/mle_router.cpp +++ b/src/core/thread/mle_router.cpp @@ -40,7 +40,7 @@ #include "common/encoding.hpp" #include "common/instance.hpp" #include "common/locator_getters.hpp" -#include "common/logging.hpp" +#include "common/log.hpp" #include "common/random.hpp" #include "common/serial_number.hpp" #include "common/settings.hpp" @@ -57,6 +57,8 @@ namespace ot { namespace Mle { +RegisterLogModule("Mle"); + MleRouter::MleRouter(Instance &aInstance) : Mle(aInstance) , mAdvertiseTrickleTimer(aInstance, MleRouter::HandleAdvertiseTrickleTimer) @@ -191,7 +193,7 @@ Error MleRouter::BecomeRouter(ThreadStatusTlv::Status aStatus) VerifyOrExit(!IsRouter(), error = kErrorNone); VerifyOrExit(IsRouterEligible(), error = kErrorNotCapable); - otLogInfoMle("Attempt to become router"); + LogInfo("Attempt to become router"); Get().SetRxOnWhenIdle(true); mRouterSelectionJitterTimeout = 0; @@ -436,7 +438,7 @@ void MleRouter::SetStateLeader(uint16_t aRloc16) } } - otLogNoteMle("Leader partition id 0x%x", mLeaderData.GetPartitionId()); + LogNote("Leader partition id 0x%x", mLeaderData.GetPartitionId()); } void MleRouter::HandleAdvertiseTrickleTimer(TrickleTimer &aTimer) @@ -1212,7 +1214,7 @@ Error MleRouter::HandleAdvertisement(const Message &aMessage, const Ip6::Message if (partitionId != mLeaderData.GetPartitionId()) { - otLogNoteMle("Different partition (peer:%u, local:%u)", partitionId, mLeaderData.GetPartitionId()); + LogNote("Different partition (peer:%u, local:%u)", partitionId, mLeaderData.GetPartitionId()); VerifyOrExit(linkMargin >= OPENTHREAD_CONFIG_MLE_PARTITION_MERGE_MARGIN_MIN, error = kErrorLinkMarginLow); @@ -1246,7 +1248,7 @@ Error MleRouter::HandleAdvertisement(const Message &aMessage, const Ip6::Message if (!IsChild()) { - otLogInfoMle("Leader ID mismatch"); + LogInfo("Leader ID mismatch"); IgnoreError(BecomeDetached()); error = kErrorDrop; } @@ -1550,18 +1552,18 @@ void MleRouter::UpdateRoutes(const RouteTlv &aRoute, uint8_t aRouterId) ResetAdvertiseInterval(); } -#if (OPENTHREAD_CONFIG_LOG_MLE && (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO)) +#if OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO VerifyOrExit(changed); - otLogInfoMle("Route table updated"); + LogInfo("Route table updated"); for (Router &router : Get().Iterate()) { - otLogInfoMle(" %04x -> %04x, cost:%d %d, lqin:%d, lqout:%d, link:%s", router.GetRloc16(), - (router.GetNextHop() == kInvalidRouterId) ? 0xffff : Rloc16FromRouterId(router.GetNextHop()), - router.GetCost(), mRouterTable.GetLinkCost(router), router.GetLinkInfo().GetLinkQuality(), - router.GetLinkQualityOut(), - router.GetRloc16() == GetRloc16() ? "device" : ToYesNo(router.IsStateValid())); + LogInfo(" %04x -> %04x, cost:%d %d, lqin:%d, lqout:%d, link:%s", router.GetRloc16(), + (router.GetNextHop() == kInvalidRouterId) ? 0xffff : Rloc16FromRouterId(router.GetNextHop()), + router.GetCost(), mRouterTable.GetLinkCost(router), router.GetLinkInfo().GetLinkQuality(), + router.GetLinkQualityOut(), + router.GetRloc16() == GetRloc16() ? "device" : ToYesNo(router.IsStateValid())); } #else @@ -1810,18 +1812,18 @@ void MleRouter::HandleTimeTick(void) case kRoleRouter: // verify path to leader - otLogDebgMle("network id timeout = %d", mRouterTable.GetLeaderAge()); + LogDebg("network id timeout = %d", mRouterTable.GetLeaderAge()); if ((mRouterTable.GetActiveRouterCount() > 0) && (mRouterTable.GetLeaderAge() >= mNetworkIdTimeout)) { - otLogInfoMle("Router ID Sequence timeout"); + LogInfo("Router ID Sequence timeout"); IgnoreError(BecomeChild(kAttachSame1)); } if (routerStateUpdate && mRouterTable.GetActiveRouterCount() > mRouterDowngradeThreshold) { // downgrade to REED - otLogNoteMle("Downgrade to REED"); + LogNote("Downgrade to REED"); IgnoreError(BecomeChild(kAttachSameDowngrade)); } @@ -1859,7 +1861,7 @@ void MleRouter::HandleTimeTick(void) if (child.IsCslSynchronized() && TimerMilli::GetNow() - child.GetCslLastHeard() >= Time::SecToMsec(child.GetCslTimeout())) { - otLogInfoMle("Child CSL synchronization expired"); + LogInfo("Child CSL synchronization expired"); child.SetCslSynchronized(false); Get().Update(); } @@ -1867,7 +1869,7 @@ void MleRouter::HandleTimeTick(void) if (TimerMilli::GetNow() - child.GetLastHeard() >= timeout) { - otLogInfoMle("Child timeout expired"); + LogInfo("Child timeout expired"); RemoveNeighbor(child); } else if (IsRouterOrLeader() && child.IsStateRestored()) @@ -1895,7 +1897,7 @@ void MleRouter::HandleTimeTick(void) if (age >= Time::SecToMsec(kMaxNeighborAge)) { - otLogInfoMle("Router timeout expired"); + LogInfo("Router timeout expired"); RemoveNeighbor(router); continue; } @@ -1906,7 +1908,7 @@ void MleRouter::HandleTimeTick(void) { if (age < Time::SecToMsec(kMaxNeighborAge) + kMaxTransmissionCount * kUnicastRetransmissionDelay) { - otLogInfoMle("Router timeout expired"); + LogInfo("Router timeout expired"); IgnoreError(SendLinkRequest(&router)); } else @@ -1922,7 +1924,7 @@ void MleRouter::HandleTimeTick(void) { if (age >= kMaxLinkRequestTimeout) { - otLogInfoMle("Link Request timeout expired"); + LogInfo("Link Request timeout expired"); RemoveNeighbor(router); continue; } @@ -1933,7 +1935,7 @@ void MleRouter::HandleTimeTick(void) if (mRouterTable.GetRouter(router.GetNextHop()) == nullptr && mRouterTable.GetLinkCost(router) >= kMaxRouteCost && age >= Time::SecToMsec(kMaxLeaderToRouterTimeout)) { - otLogInfoMle("Router ID timeout expired (no route)"); + LogInfo("Router ID timeout expired (no route)"); IgnoreError(mRouterTable.Release(router.GetRouterId())); } } @@ -2112,8 +2114,8 @@ Error MleRouter::UpdateChildAddresses(const Message &aMessage, uint16_t aOffset, { if (Get().GetContext(entry.GetContextId(), context) != kErrorNone) { - otLogWarnMle("Failed to get context %d for compressed address from child 0x%04x", entry.GetContextId(), - aChild.GetRloc16()); + LogWarn("Failed to get context %d for compressed address from child 0x%04x", entry.GetContextId(), + aChild.GetRloc16()); continue; } @@ -2162,8 +2164,8 @@ Error MleRouter::UpdateChildAddresses(const Message &aMessage, uint16_t aOffset, } #endif - otLogInfoMle("Child 0x%04x IPv6 address[%d]=%s", aChild.GetRloc16(), storedCount, - address.ToString().AsCString()); + LogInfo("Child 0x%04x IPv6 address[%d]=%s", aChild.GetRloc16(), storedCount, + address.ToString().AsCString()); } else { @@ -2175,8 +2177,8 @@ Error MleRouter::UpdateChildAddresses(const Message &aMessage, uint16_t aOffset, } #endif - otLogWarnMle("Error %s adding IPv6 address %s to child 0x%04x", ErrorToString(error), - address.ToString().AsCString(), aChild.GetRloc16()); + LogWarn("Error %s adding IPv6 address %s to child 0x%04x", ErrorToString(error), + address.ToString().AsCString(), aChild.GetRloc16()); } if (address.IsMulticast()) @@ -2221,12 +2223,12 @@ Error MleRouter::UpdateChildAddresses(const Message &aMessage, uint16_t aOffset, if (registeredCount == 0) { - otLogInfoMle("Child 0x%04x has no registered IPv6 address", aChild.GetRloc16()); + LogInfo("Child 0x%04x has no registered IPv6 address", aChild.GetRloc16()); } else { - otLogInfoMle("Child 0x%04x has %d registered IPv6 address%s, %d address%s stored", aChild.GetRloc16(), - registeredCount, (registeredCount == 1) ? "" : "es", storedCount, (storedCount == 1) ? "" : "es"); + LogInfo("Child 0x%04x has %d registered IPv6 address%s, %d address%s stored", aChild.GetRloc16(), + registeredCount, (registeredCount == 1) ? "" : "es", storedCount, (storedCount == 1) ? "" : "es"); } error = kErrorNone; @@ -2568,8 +2570,8 @@ void MleRouter::HandleChildUpdateRequest(const Message &aMessage, const Ip6::Mes if (oldMode != child->GetDeviceMode()) { - otLogNoteMle("Child 0x%04x mode change 0x%02x -> 0x%02x [%s]", child->GetRloc16(), oldMode.Get(), - child->GetDeviceMode().Get(), child->GetDeviceMode().ToString().AsCString()); + LogNote("Child 0x%04x mode change 0x%02x -> 0x%02x [%s]", child->GetRloc16(), oldMode.Get(), + child->GetDeviceMode().Get(), child->GetDeviceMode().ToString().AsCString()); childDidChange = true; @@ -3313,7 +3315,7 @@ void MleRouter::SendDataResponse(const Ip6::Address &aDestination, if (mRetrieveNewNetworkData) { - otLogInfoMle("Suppressing Data Response - waiting for new network data"); + LogInfo("Suppressing Data Response - waiting for new network data"); ExitNow(); } @@ -3874,7 +3876,7 @@ void MleRouter::HandleAddressSolicit(Coap::Message &aMessage, const Ip6::Message } else { - otLogInfoMle("router id requested and provided!"); + LogInfo("router id requested and provided!"); } if (router != nullptr) @@ -3883,7 +3885,7 @@ void MleRouter::HandleAddressSolicit(Coap::Message &aMessage, const Ip6::Message } else { - otLogInfoMle("router address unavailable!"); + LogInfo("router address unavailable!"); } exit: diff --git a/src/core/thread/mlr_manager.cpp b/src/core/thread/mlr_manager.cpp index 36230896c..b871ad178 100644 --- a/src/core/thread/mlr_manager.cpp +++ b/src/core/thread/mlr_manager.cpp @@ -39,7 +39,7 @@ #include "common/code_utils.hpp" #include "common/instance.hpp" #include "common/locator_getters.hpp" -#include "common/logging.hpp" +#include "common/log.hpp" #include "net/ip6_address.hpp" #include "thread/thread_netif.hpp" #include "thread/uri_paths.hpp" @@ -47,6 +47,8 @@ namespace ot { +RegisterLogModule("MlrManager"); + MlrManager::MlrManager(Instance &aInstance) : InstanceLocator(aInstance) #if (OPENTHREAD_FTD && OPENTHREAD_CONFIG_TMF_PROXY_MLR_ENABLE) && OPENTHREAD_CONFIG_COMMISSIONER_ENABLE @@ -331,7 +333,7 @@ Error MlrManager::RegisterMulticastListeners(const otIp6Address * #else if (!Get().IsActive()) { - otLogWarnMlr("MLR.req without active commissioner session for test."); + LogWarn("MLR.req without active commissioner session for test."); } #endif @@ -447,10 +449,10 @@ Error MlrManager::SendMulticastListenerRegistrationMessage(const otIp6Address * error = Get().SendMessage(*message, messageInfo, aResponseHandler, aResponseContext); - otLogInfoMlr("Sent MLR.req: addressNum=%d", aAddressNum); + LogInfo("Sent MLR.req: addressNum=%d", aAddressNum); exit: - otLogInfoMlr("SendMulticastListenerRegistrationMessage(): %s", ErrorToString(error)); + LogInfo("SendMulticastListenerRegistrationMessage(): %s", ErrorToString(error)); FreeMessageOnError(message, error); return error; } @@ -621,7 +623,7 @@ void MlrManager::HandleTimeTick(void) void MlrManager::Reregister(void) { - otLogInfoMlr("MLR Reregister!"); + LogInfo("MLR Reregister!"); SetMulticastAddressMlrState(kMlrStateRegistered, kMlrStateToRegister); CheckInvariants(); @@ -674,19 +676,19 @@ void MlrManager::UpdateReregistrationDelay(bool aRereg) UpdateTimeTickerRegistration(); - otLogDebgMlr("MlrManager::UpdateReregistrationDelay: rereg=%d, needSendMlr=%d, ReregDelay=%lu", aRereg, needSendMlr, - mReregistrationDelay); + LogDebg("MlrManager::UpdateReregistrationDelay: rereg=%d, needSendMlr=%d, ReregDelay=%lu", aRereg, needSendMlr, + mReregistrationDelay); } void MlrManager::LogMulticastAddresses(void) { -#if OPENTHREAD_CONFIG_LOG_MLR && OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_DEBG - otLogDebgMlr("-------- Multicast Addresses --------"); +#if OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_DEBG + LogDebg("-------- Multicast Addresses --------"); #if OPENTHREAD_CONFIG_MLR_ENABLE for (const Ip6::Netif::ExternalMulticastAddress &addr : Get().IterateExternalMulticastAddresses()) { - otLogDebgMlr("%-32s%c", addr.GetAddress().ToString().AsCString(), "-rR"[addr.GetMlrState()]); + LogDebg("%-32s%c", addr.GetAddress().ToString().AsCString(), "-rR"[addr.GetMlrState()]); } #endif @@ -695,13 +697,13 @@ void MlrManager::LogMulticastAddresses(void) { for (const Ip6::Address &address : child.IterateIp6Addresses(Ip6::Address::kTypeMulticastLargerThanRealmLocal)) { - otLogDebgMlr("%-32s%c %04x", address.ToString().AsCString(), "-rR"[child.GetAddressMlrState(address)], - child.GetRloc16()); + LogDebg("%-32s%c %04x", address.ToString().AsCString(), "-rR"[child.GetAddressMlrState(address)], + child.GetRloc16()); } } #endif -#endif // OPENTHREAD_CONFIG_LOG_MLR && OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_DEBG +#endif // OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_DEBG } void MlrManager::AppendToUniqueAddressList(Ip6::Address (&aAddresses)[kIp6AddressesNumMax], @@ -759,19 +761,19 @@ void MlrManager::LogMlrResponse(Error aResult, OT_UNUSED_VARIABLE(aFailedAddresses); OT_UNUSED_VARIABLE(aFailedAddressNum); -#if (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_WARN) && (OPENTHREAD_CONFIG_LOG_MLR == 1) +#if OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_WARN if (aResult == kErrorNone && aError == kErrorNone && aStatus == ThreadStatusTlv::MlrStatus::kMlrSuccess) { - otLogInfoMlr("Receive MLR.rsp OK"); + LogInfo("Receive MLR.rsp OK"); } else { - otLogWarnMlr("Receive MLR.rsp: result=%s, error=%s, status=%d, failedAddressNum=%d", ErrorToString(aResult), - ErrorToString(aError), aStatus, aFailedAddressNum); + LogWarn("Receive MLR.rsp: result=%s, error=%s, status=%d, failedAddressNum=%d", ErrorToString(aResult), + ErrorToString(aError), aStatus, aFailedAddressNum); for (uint8_t i = 0; i < aFailedAddressNum; i++) { - otLogWarnMlr("MA failed: %s", aFailedAddresses[i].ToString().AsCString()); + LogWarn("MA failed: %s", aFailedAddresses[i].ToString().AsCString()); } } #endif diff --git a/src/core/thread/network_data.cpp b/src/core/thread/network_data.cpp index 94e61c930..31bb8c809 100644 --- a/src/core/thread/network_data.cpp +++ b/src/core/thread/network_data.cpp @@ -38,7 +38,7 @@ #include "common/debug.hpp" #include "common/instance.hpp" #include "common/locator_getters.hpp" -#include "common/logging.hpp" +#include "common/log.hpp" #include "mac/mac_types.hpp" #include "thread/thread_netif.hpp" #include "thread/thread_tlvs.hpp" @@ -47,6 +47,8 @@ namespace ot { namespace NetworkData { +RegisterLogModule("NetworkData"); + Error NetworkData::CopyNetworkData(Type aType, uint8_t *aData, uint8_t &aDataLength) const { Error error; @@ -665,7 +667,7 @@ Error NetworkData::SendServerDataNotification(uint16_t aRloc16, messageInfo.SetPeerPort(Tmf::kUdpPort); SuccessOrExit(error = Get().SendMessage(*message, messageInfo, aHandler, aContext)); - otLogInfoNetData("Sent server data notification"); + LogInfo("Sent server data notification"); exit: FreeMessageOnError(message, error); diff --git a/src/core/thread/network_data_leader.cpp b/src/core/thread/network_data_leader.cpp index 53c5e4b24..80c358cf9 100644 --- a/src/core/thread/network_data_leader.cpp +++ b/src/core/thread/network_data_leader.cpp @@ -53,6 +53,8 @@ namespace ot { namespace NetworkData { +RegisterLogModule("NetworkData"); + void LeaderBase::Reset(void) { mVersion = Random::NonCrypto::GetUint8(); @@ -376,7 +378,7 @@ Error LeaderBase::SetNetworkData(uint8_t aVersion, } #endif - otDumpDebgNetData("SetNetworkData", GetBytes(), GetLength()); + DumpDebg("SetNetworkData", GetBytes(), GetLength()); Get().Signal(kEventThreadNetdataChanged); diff --git a/src/core/thread/network_data_leader_ftd.cpp b/src/core/thread/network_data_leader_ftd.cpp index f318d6e70..ef6a4e04c 100644 --- a/src/core/thread/network_data_leader_ftd.cpp +++ b/src/core/thread/network_data_leader_ftd.cpp @@ -42,7 +42,7 @@ #include "common/encoding.hpp" #include "common/instance.hpp" #include "common/locator_getters.hpp" -#include "common/logging.hpp" +#include "common/log.hpp" #include "common/message.hpp" #include "common/timer.hpp" #include "mac/mac_types.hpp" @@ -56,6 +56,8 @@ namespace ot { namespace NetworkData { +RegisterLogModule("NetworkData"); + Leader::Leader(Instance &aInstance) : LeaderBase(aInstance) , mTimer(aInstance, Leader::HandleTimer) @@ -142,7 +144,7 @@ void Leader::HandleServerData(Coap::Message &aMessage, const Ip6::MessageInfo &a ThreadNetworkDataTlv networkDataTlv; uint16_t rloc16; - otLogInfoNetData("Received network data registration"); + LogInfo("Received network data registration"); VerifyOrExit(aMessageInfo.GetPeerAddr().GetIid().IsRoutingLocator()); @@ -170,7 +172,7 @@ void Leader::HandleServerData(Coap::Message &aMessage, const Ip6::MessageInfo &a SuccessOrExit(Get().SendEmptyAck(aMessage, aMessageInfo)); - otLogInfoNetData("Sent network data registration acknowledgment"); + LogInfo("Sent network data registration acknowledgment"); exit: return; @@ -346,7 +348,7 @@ void Leader::SendCommissioningGetResponse(const Coap::Message & aRequest, SuccessOrExit(error = Get().SendMessage(*message, aMessageInfo)); - otLogInfoMeshCoP("sent commissioning dataset get response"); + LogInfo("sent commissioning dataset get response"); exit: FreeMessageOnError(message, error); @@ -368,7 +370,7 @@ void Leader::SendCommissioningSetResponse(const Coap::Message & aRequest, SuccessOrExit(error = Get().SendMessage(*message, aMessageInfo)); - otLogInfoMeshCoP("sent commissioning dataset set response"); + LogInfo("sent commissioning dataset set response"); exit: FreeMessageOnError(message, error); @@ -729,13 +731,13 @@ void Leader::RegisterNetworkData(uint16_t aRloc16, const NetworkData &aNetworkDa IncrementVersions(flags); - otDumpDebgNetData("Register", GetBytes(), GetLength()); + DumpDebg("Register", GetBytes(), GetLength()); exit: if (error != kErrorNone) { - otLogNoteNetData("Failed to register network data: %s", ErrorToString(error)); + LogNote("Failed to register network data: %s", ErrorToString(error)); } } @@ -972,7 +974,7 @@ Error Leader::AllocateServiceId(uint8_t &aServiceId) const { aServiceId = serviceId; error = kErrorNone; - otLogInfoNetData("Allocated Service ID = %d", serviceId); + LogInfo("Allocated Service ID = %d", serviceId); break; } } @@ -1007,7 +1009,7 @@ Error Leader::AllocateContextId(uint8_t &aContextId) mContextUsed |= (1 << contextId); aContextId = contextId; error = kErrorNone; - otLogInfoNetData("Allocated Context ID = %d", contextId); + LogInfo("Allocated Context ID = %d", contextId); break; } } @@ -1017,7 +1019,7 @@ Error Leader::AllocateContextId(uint8_t &aContextId) void Leader::FreeContextId(uint8_t aContextId) { - otLogInfoNetData("Free Context Id = %d", aContextId); + LogInfo("Free Context Id = %d", aContextId); RemoveContext(aContextId); mContextUsed &= ~(1 << aContextId); IncrementVersions(/* aIncludeStable */ true); diff --git a/src/core/thread/network_data_local.cpp b/src/core/thread/network_data_local.cpp index 53366a1ee..8095a95bb 100644 --- a/src/core/thread/network_data_local.cpp +++ b/src/core/thread/network_data_local.cpp @@ -39,7 +39,7 @@ #include "common/debug.hpp" #include "common/instance.hpp" #include "common/locator_getters.hpp" -#include "common/logging.hpp" +#include "common/log.hpp" #include "mac/mac_types.hpp" #include "thread/mle_types.hpp" #include "thread/thread_netif.hpp" @@ -47,6 +47,8 @@ namespace ot { namespace NetworkData { +RegisterLogModule("NetworkData"); + #if OPENTHREAD_CONFIG_BORDER_ROUTER_ENABLE Error Local::AddOnMeshPrefix(const OnMeshPrefixConfig &aConfig) @@ -125,7 +127,7 @@ Error Local::AddPrefix(const Ip6::Prefix &aPrefix, NetworkDataTlv::Type aSubTlvT prefixTlv->GetSubTlvs()->SetStable(); } - otDumpDebgNetData("AddPrefix", GetBytes(), GetLength()); + DumpDebg("AddPrefix", GetBytes(), GetLength()); exit: return error; @@ -141,7 +143,7 @@ Error Local::RemovePrefix(const Ip6::Prefix &aPrefix, NetworkDataTlv::Type aSubT RemoveTlv(tlv); exit: - otDumpDebgNetData("RmvPrefix", GetBytes(), GetLength()); + DumpDebg("RmvPrefix", GetBytes(), GetLength()); return error; } @@ -210,7 +212,7 @@ Error Local::AddService(uint32_t aEnterpriseNumber, serverTlv->SetStable(); } - otDumpDebgNetData("AddService", GetBytes(), GetLength()); + DumpDebg("AddService", GetBytes(), GetLength()); exit: return error; @@ -226,7 +228,7 @@ Error Local::RemoveService(uint32_t aEnterpriseNumber, const ServiceData &aServi RemoveTlv(tlv); exit: - otDumpDebgNetData("RmvService", GetBytes(), GetLength()); + DumpDebg("RmvService", GetBytes(), GetLength()); return error; } diff --git a/src/core/thread/network_data_publisher.cpp b/src/core/thread/network_data_publisher.cpp index 52981c6cc..5f46008d6 100644 --- a/src/core/thread/network_data_publisher.cpp +++ b/src/core/thread/network_data_publisher.cpp @@ -41,7 +41,7 @@ #include "common/const_cast.hpp" #include "common/instance.hpp" #include "common/locator_getters.hpp" -#include "common/logging.hpp" +#include "common/log.hpp" #include "common/random.hpp" #include "thread/network_data_local.hpp" #include "thread/network_data_service.hpp" @@ -49,6 +49,8 @@ namespace ot { namespace NetworkData { +RegisterLogModule("NetDataPublshr"); + //--------------------------------------------------------------------------------------------------------------------- // Publisher @@ -263,8 +265,8 @@ void Publisher::Entry::SetState(State aState) { VerifyOrExit(mState != aState); - otLogInfoNetData("Publisher: %s - State: %s -> %s", ToString(/* aIncludeState */ false).AsCString(), - StateToString(mState), StateToString(aState)); + LogInfo("%s - State: %s -> %s", ToString(/* aIncludeState */ false).AsCString(), StateToString(mState), + StateToString(aState)); mState = aState; exit: @@ -291,8 +293,8 @@ void Publisher::Entry::UpdateState(uint8_t aNumEntries, uint8_t aNumPreferredEnt // entries we aim to have in the Network Data to decide whether or // not to take any action (add or remove our entry). - otLogInfoNetData("Publisher: %s in netdata - total:%d, preferred:%d, desired:%d", ToString().AsCString(), - aNumEntries, aNumPreferredEntries, aDesiredNumEntries); + LogInfo("%s in netdata - total:%d, preferred:%d, desired:%d", ToString().AsCString(), aNumEntries, + aNumPreferredEntries, aDesiredNumEntries); switch (GetState()) { @@ -480,7 +482,7 @@ exit: void Publisher::Entry::LogUpdateTime(void) const { - otLogInfoNetData("Publisher: %s - update in %u msec", ToString().AsCString(), mUpdateTime - TimerMilli::GetNow()); + LogInfo("%s - update in %u msec", ToString().AsCString(), mUpdateTime - TimerMilli::GetNow()); } const char *Publisher::Entry::StateToString(State aState) @@ -522,20 +524,19 @@ void Publisher::DnsSrpServiceEntry::SetCallback(DnsSrpServiceCallback aCallback, void Publisher::DnsSrpServiceEntry::PublishAnycast(uint8_t aSequenceNumber) { - otLogInfoNetData("Publisher: Publishing DNS/SRP service anycast (seq-num:%d)", aSequenceNumber); + LogInfo("Publishing DNS/SRP service anycast (seq-num:%d)", aSequenceNumber); Publish(Info::InfoAnycast(aSequenceNumber)); } void Publisher::DnsSrpServiceEntry::PublishUnicast(const Ip6::Address &aAddress, uint16_t aPort) { - otLogInfoNetData("Publisher: Publishing DNS/SRP service unicast (%s, port:%d)", aAddress.ToString().AsCString(), - aPort); + LogInfo("Publishing DNS/SRP service unicast (%s, port:%d)", aAddress.ToString().AsCString(), aPort); Publish(Info::InfoUnicast(kTypeUnicast, aAddress, aPort)); } void Publisher::DnsSrpServiceEntry::PublishUnicast(uint16_t aPort) { - otLogInfoNetData("Publisher: Publishing DNS/SRP service unicast (ml-eid, port:%d)", aPort); + LogInfo("Publishing DNS/SRP service unicast (ml-eid, port:%d)", aPort); Publish(Info::InfoUnicast(kTypeUnicastMeshLocalEid, Get().GetMeshLocal64(), aPort)); } @@ -547,7 +548,7 @@ void Publisher::DnsSrpServiceEntry::Publish(const Info &aInfo) { if (aInfo == mInfo) { - otLogInfoNetData("Publisher: %s is already being published", ToString().AsCString()); + LogInfo("%s is already being published", ToString().AsCString()); ExitNow(); } @@ -572,7 +573,7 @@ void Publisher::DnsSrpServiceEntry::Unpublish(void) { bool registerWithLeader; - otLogInfoNetData("Publisher: Unpublishing DNS/SRP service"); + LogInfo("Unpublishing DNS/SRP service"); registerWithLeader = Remove(/* aNextState */ kNoEntry); @@ -844,7 +845,7 @@ Publisher::DnsSrpServiceEntry::Info::Info(Type aType, uint16_t aPortOrSeqNumber, void Publisher::PrefixEntry::Publish(const OnMeshPrefixConfig &aConfig) { - otLogInfoNetData("Publisher: Publishing OnMeshPrefix %s", aConfig.GetPrefix().ToString().AsCString()); + LogInfo("Publishing OnMeshPrefix %s", aConfig.GetPrefix().ToString().AsCString()); mType = kTypeOnMeshPrefix; mPrefix = aConfig.GetPrefix(); @@ -857,7 +858,7 @@ void Publisher::PrefixEntry::Publish(const OnMeshPrefixConfig &aConfig) void Publisher::PrefixEntry::Publish(const ExternalRouteConfig &aConfig) { - otLogInfoNetData("Publisher: Publishing ExternalRoute %s", aConfig.GetPrefix().ToString().AsCString()); + LogInfo("Publishing ExternalRoute %s", aConfig.GetPrefix().ToString().AsCString()); mType = kTypeExternalRoute; mPrefix = aConfig.GetPrefix(); @@ -872,7 +873,7 @@ void Publisher::PrefixEntry::Unpublish(void) { bool registerWithLeader = false; - otLogInfoNetData("Publisher: Unpublishing %s", mPrefix.ToString().AsCString()); + LogInfo("Unpublishing %s", mPrefix.ToString().AsCString()); registerWithLeader = Remove(/* aNextState */ kNoEntry); diff --git a/src/core/thread/network_diagnostic.cpp b/src/core/thread/network_diagnostic.cpp index 1600c8456..862ddab80 100644 --- a/src/core/thread/network_diagnostic.cpp +++ b/src/core/thread/network_diagnostic.cpp @@ -43,7 +43,7 @@ #include "common/encoding.hpp" #include "common/instance.hpp" #include "common/locator_getters.hpp" -#include "common/logging.hpp" +#include "common/log.hpp" #include "mac/mac.hpp" #include "net/netif.hpp" #include "thread/mesh_forwarder.hpp" @@ -54,6 +54,8 @@ namespace ot { +RegisterLogModule("NetDiag"); + namespace NetworkDiagnostic { NetworkDiagnostic::NetworkDiagnostic(Instance &aInstance) @@ -122,7 +124,7 @@ Error NetworkDiagnostic::SendDiagnosticGet(const Ip6::Address & aDesti mReceiveDiagnosticGetCallback = aCallback; mReceiveDiagnosticGetCallbackContext = aCallbackContext; - otLogInfoNetDiag("Sent diagnostic get"); + LogInfo("Sent diagnostic get"); exit: FreeMessageOnError(message, error); @@ -152,7 +154,7 @@ exit: } else { - otLogDebgNetDiag("Received diagnostic get response, error = %s", ErrorToString(aResult)); + LogDebg("Received diagnostic get response, error = %s", ErrorToString(aResult)); } return; } @@ -169,7 +171,7 @@ void NetworkDiagnostic::HandleDiagnosticGetAnswer(Coap::Message &aMessage, const { VerifyOrExit(aMessage.IsConfirmablePostRequest()); - otLogInfoNetDiag("Diagnostic get answer received"); + LogInfo("Diagnostic get answer received"); if (mReceiveDiagnosticGetCallback) { @@ -178,7 +180,7 @@ void NetworkDiagnostic::HandleDiagnosticGetAnswer(Coap::Message &aMessage, const SuccessOrExit(Get().SendEmptyAck(aMessage, aMessageInfo)); - otLogInfoNetDiag("Sent diagnostic answer acknowledgment"); + LogInfo("Sent diagnostic answer acknowledgment"); exit: return; @@ -295,7 +297,7 @@ Error NetworkDiagnostic::FillRequestedTlvs(const Message & aRequest, { SuccessOrExit(error = aRequest.Read(offset, type)); - otLogInfoNetDiag("Type %d", type); + LogInfo("Type %d", type); switch (type) { @@ -469,7 +471,7 @@ void NetworkDiagnostic::HandleDiagnosticGetQuery(Coap::Message &aMessage, const VerifyOrExit(aMessage.IsPostRequest(), error = kErrorDrop); - otLogInfoNetDiag("Received diagnostic get query"); + LogInfo("Received diagnostic get query"); SuccessOrExit(error = aMessage.Read(aMessage.GetOffset(), networkDiagnosticTlv)); @@ -480,7 +482,7 @@ void NetworkDiagnostic::HandleDiagnosticGetQuery(Coap::Message &aMessage, const { if (Get().SendEmptyAck(aMessage, aMessageInfo) == kErrorNone) { - otLogInfoNetDiag("Sent diagnostic get query acknowledgment"); + LogInfo("Sent diagnostic get query acknowledgment"); } } @@ -509,7 +511,7 @@ void NetworkDiagnostic::HandleDiagnosticGetQuery(Coap::Message &aMessage, const SuccessOrExit(error = Get().SendMessage(*message, messageInfo, nullptr, this)); - otLogInfoNetDiag("Sent diagnostic get answer"); + LogInfo("Sent diagnostic get answer"); exit: FreeMessageOnError(message, error); @@ -532,7 +534,7 @@ void NetworkDiagnostic::HandleDiagnosticGetRequest(Coap::Message &aMessage, cons VerifyOrExit(aMessage.IsConfirmablePostRequest(), error = kErrorDrop); - otLogInfoNetDiag("Received diagnostic get request"); + LogInfo("Received diagnostic get request"); SuccessOrExit(error = aMessage.Read(aMessage.GetOffset(), networkDiagnosticTlv)); @@ -547,7 +549,7 @@ void NetworkDiagnostic::HandleDiagnosticGetRequest(Coap::Message &aMessage, cons SuccessOrExit(error = Get().SendMessage(*message, messageInfo)); - otLogInfoNetDiag("Sent diagnostic get response"); + LogInfo("Sent diagnostic get response"); exit: FreeMessageOnError(message, error); @@ -589,7 +591,7 @@ Error NetworkDiagnostic::SendDiagnosticReset(const Ip6::Address &aDestination, SuccessOrExit(error = Get().SendMessage(*message, messageInfo)); - otLogInfoNetDiag("Sent network diagnostic reset"); + LogInfo("Sent network diagnostic reset"); exit: FreeMessageOnError(message, error); @@ -608,7 +610,7 @@ void NetworkDiagnostic::HandleDiagnosticReset(Coap::Message &aMessage, const Ip6 uint8_t type; NetworkDiagnosticTlv tlv; - otLogInfoNetDiag("Received diagnostic reset request"); + LogInfo("Received diagnostic reset request"); VerifyOrExit(aMessage.IsConfirmablePostRequest()); @@ -626,18 +628,18 @@ void NetworkDiagnostic::HandleDiagnosticReset(Coap::Message &aMessage, const Ip6 { case NetworkDiagnosticTlv::kMacCounters: Get().ResetCounters(); - otLogInfoNetDiag("Received diagnostic reset type kMacCounters(9)"); + LogInfo("Received diagnostic reset type kMacCounters(9)"); break; default: - otLogInfoNetDiag("Received diagnostic reset other type %d not resetable", type); + LogInfo("Received diagnostic reset other type %d not resetable", type); break; } } SuccessOrExit(Get().SendEmptyAck(aMessage, aMessageInfo)); - otLogInfoNetDiag("Sent diagnostic reset acknowledgment"); + LogInfo("Sent diagnostic reset acknowledgment"); exit: return; diff --git a/src/core/thread/panid_query_server.cpp b/src/core/thread/panid_query_server.cpp index 6a31b0af5..92415097e 100644 --- a/src/core/thread/panid_query_server.cpp +++ b/src/core/thread/panid_query_server.cpp @@ -39,7 +39,7 @@ #include "common/debug.hpp" #include "common/instance.hpp" #include "common/locator_getters.hpp" -#include "common/logging.hpp" +#include "common/log.hpp" #include "meshcop/meshcop.hpp" #include "meshcop/meshcop_tlvs.hpp" #include "thread/thread_netif.hpp" @@ -47,6 +47,8 @@ namespace ot { +RegisterLogModule("MeshCoP"); + PanIdQueryServer::PanIdQueryServer(Instance &aInstance) : InstanceLocator(aInstance) , mChannelMask(0) @@ -81,7 +83,7 @@ void PanIdQueryServer::HandleQuery(Coap::Message &aMessage, const Ip6::MessageIn if (aMessage.IsConfirmable() && !aMessageInfo.GetSockAddr().IsMulticast()) { SuccessOrExit(Get().SendEmptyAck(aMessage, responseInfo)); - otLogInfoMeshCoP("sent panid query response"); + LogInfo("sent panid query response"); } exit: @@ -131,7 +133,7 @@ void PanIdQueryServer::SendConflict(void) messageInfo.SetPeerPort(Tmf::kUdpPort); SuccessOrExit(error = Get().SendMessage(*message, messageInfo)); - otLogInfoMeshCoP("sent panid conflict"); + LogInfo("sent panid conflict"); exit: FreeMessageOnError(message, error); diff --git a/src/core/thread/radio_selector.cpp b/src/core/thread/radio_selector.cpp index 74ea6bc07..bf0798b6c 100644 --- a/src/core/thread/radio_selector.cpp +++ b/src/core/thread/radio_selector.cpp @@ -38,11 +38,13 @@ #include "common/code_utils.hpp" #include "common/instance.hpp" #include "common/locator_getters.hpp" -#include "common/logging.hpp" +#include "common/log.hpp" #include "common/random.hpp" namespace ot { +RegisterLogModule("RadioSelector"); + // This array defines the order in which different radio link types are // selected for message tx (direct message). const Mac::RadioType RadioSelector::sRadioSelectionOrder[Mac::kNumRadioTypes] = { @@ -80,7 +82,7 @@ void RadioSelector::NeighborInfo::PopulateMultiRadioInfo(MultiRadioInfo &aInfo) #endif } -otLogLevel RadioSelector::UpdatePreference(Neighbor &aNeighbor, Mac::RadioType aRadioType, int16_t aDifference) +LogLevel RadioSelector::UpdatePreference(Neighbor &aNeighbor, Mac::RadioType aRadioType, int16_t aDifference) { uint8_t old = aNeighbor.GetRadioPreference(aRadioType); int16_t preferecne = static_cast(old); @@ -104,12 +106,12 @@ otLogLevel RadioSelector::UpdatePreference(Neighbor &aNeighbor, Mac::RadioType a // return a suggested log level. If there is cross, suggest info // log level, otherwise debug log level. - return ((old >= kHighPreference) != (preferecne >= kHighPreference)) ? OT_LOG_LEVEL_INFO : OT_LOG_LEVEL_DEBG; + return ((old >= kHighPreference) != (preferecne >= kHighPreference)) ? kLogLevelInfo : kLogLevelDebg; } void RadioSelector::UpdateOnReceive(Neighbor &aNeighbor, Mac::RadioType aRadioType, bool aIsDuplicate) { - otLogLevel logLevel = OT_LOG_LEVEL_INFO; + LogLevel logLevel = kLogLevelInfo; if (aNeighbor.GetSupportedRadioTypes().Contains(aRadioType)) { @@ -129,7 +131,7 @@ void RadioSelector::UpdateOnReceive(Neighbor &aNeighbor, Mac::RadioType aRadioTy void RadioSelector::UpdateOnSendDone(Mac::TxFrame &aFrame, Error aTxError) { - otLogLevel logLevel = OT_LOG_LEVEL_INFO; + LogLevel logLevel = kLogLevelInfo; Mac::RadioType radioType = aFrame.GetRadioType(); Mac::Address macDest; Neighbor * neighbor; @@ -173,7 +175,7 @@ exit: #if OPENTHREAD_CONFIG_RADIO_LINK_TREL_ENABLE void RadioSelector::UpdateOnDeferredAck(Neighbor &aNeighbor, Error aTxError, bool &aAllowNeighborRemove) { - otLogLevel logLevel = OT_LOG_LEVEL_INFO; + LogLevel logLevel = kLogLevelInfo; aAllowNeighborRemove = true; @@ -292,7 +294,7 @@ Mac::TxFrame &RadioSelector::SelectRadio(Message &aMessage, const Mac::Address & selectedRadio = Select(neighbor->GetSupportedRadioTypes(), *neighbor); selections.Add(selectedRadio); - Log(OT_LOG_LEVEL_DEBG, "SelectRadio", selectedRadio, *neighbor); + Log(kLogLevelDebg, "SelectRadio", selectedRadio, *neighbor); aMessage.SetRadioType(selectedRadio); @@ -316,7 +318,7 @@ Mac::TxFrame &RadioSelector::SelectRadio(Message &aMessage, const Mac::Address & aTxFrames.SetRequiredRadioTypes(selections); selections.Add(Mac::kRadioTypeTrel); - Log(OT_LOG_LEVEL_DEBG, "Probe", Mac::kRadioTypeTrel, *neighbor); + Log(kLogLevelDebg, "Probe", Mac::kRadioTypeTrel, *neighbor); } #endif @@ -353,9 +355,9 @@ Mac::RadioType RadioSelector::SelectPollFrameRadio(const Neighbor &aParent) // LCOV_EXCL_START -#if (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO) && (OPENTHREAD_CONFIG_LOG_MAC == 1) +#if OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO -void RadioSelector::Log(otLogLevel aLogLevel, +void RadioSelector::Log(LogLevel aLogLevel, const char * aActionText, Mac::RadioType aRadioType, const Neighbor &aNeighbor) @@ -363,7 +365,7 @@ void RadioSelector::Log(otLogLevel aLogLevel, String preferenceString; bool isFirstEntry = true; - VerifyOrExit(otLoggingGetLevel() >= aLogLevel); + VerifyOrExit(Instance::GetLogLevel() >= aLogLevel); for (Mac::RadioType radio : sRadioSelectionOrder) { @@ -375,21 +377,21 @@ void RadioSelector::Log(otLogLevel aLogLevel, } } - otLogMac(aLogLevel, "RadioSelector: %s %s - neighbor:[%s rloc16:0x%04x radio-pref:{%s} state:%s]", aActionText, - RadioTypeToString(aRadioType), aNeighbor.GetExtAddress().ToString().AsCString(), aNeighbor.GetRloc16(), - preferenceString.AsCString(), Neighbor::StateToString(aNeighbor.GetState())); + LogAt(aLogLevel, "RadioSelector: %s %s - neighbor:[%s rloc16:0x%04x radio-pref:{%s} state:%s]", aActionText, + RadioTypeToString(aRadioType), aNeighbor.GetExtAddress().ToString().AsCString(), aNeighbor.GetRloc16(), + preferenceString.AsCString(), Neighbor::StateToString(aNeighbor.GetState())); exit: return; } -#else // #if (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO) && (OPENTHREAD_CONFIG_LOG_MAC == 1) +#else // #if OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO -void RadioSelector::Log(otLogLevel, const char *, Mac::RadioType, const Neighbor &) +void RadioSelector::Log(LogLevel, const char *, Mac::RadioType, const Neighbor &) { } -#endif // #if (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO) && (OPENTHREAD_CONFIG_LOG_MAC == 1) +#endif // #if OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO // LCOV_EXCL_STOP diff --git a/src/core/thread/radio_selector.hpp b/src/core/thread/radio_selector.hpp index c86f1c10a..75da6a8e7 100644 --- a/src/core/thread/radio_selector.hpp +++ b/src/core/thread/radio_selector.hpp @@ -41,6 +41,7 @@ #include #include "common/locator.hpp" +#include "common/log.hpp" #include "common/message.hpp" #include "mac/mac_frame.hpp" #include "mac/mac_links.hpp" @@ -198,9 +199,9 @@ private: static constexpr uint16_t kRadioPreferenceStringSize = 75; - otLogLevel UpdatePreference(Neighbor &aNeighbor, Mac::RadioType aRadioType, int16_t aDifference); + LogLevel UpdatePreference(Neighbor &aNeighbor, Mac::RadioType aRadioType, int16_t aDifference); Mac::RadioType Select(Mac::RadioTypes aRadioOptions, const Neighbor &aNeighbor); - void Log(otLogLevel aLogLevel, const char *aActionText, Mac::RadioType aType, const Neighbor &aNeighbor); + void Log(LogLevel aLogLevel, const char *aActionText, Mac::RadioType aType, const Neighbor &aNeighbor); static const Mac::RadioType sRadioSelectionOrder[Mac::kNumRadioTypes]; }; diff --git a/src/core/thread/router_table.cpp b/src/core/thread/router_table.cpp index 7b8101734..c7b37b84d 100644 --- a/src/core/thread/router_table.cpp +++ b/src/core/thread/router_table.cpp @@ -33,7 +33,7 @@ #include "common/code_utils.hpp" #include "common/instance.hpp" #include "common/locator_getters.hpp" -#include "common/logging.hpp" +#include "common/log.hpp" #include "common/timer.hpp" #include "thread/mle.hpp" #include "thread/mle_router.hpp" @@ -42,6 +42,8 @@ namespace ot { +RegisterLogModule("RouterTable"); + RouterTable::Iterator::Iterator(Instance &aInstance) : InstanceLocator(aInstance) , ItemPtrIterator(Get().GetFirstEntry()) @@ -268,7 +270,7 @@ Router *RouterTable::Allocate(uint8_t aRouterId) mRouterIdSequenceLastUpdated = TimerMilli::GetNow(); Get().ResetAdvertiseInterval(); - otLogNoteMle("Allocate router id %d", aRouterId); + LogNote("Allocate router id %d", aRouterId); exit: return rval; @@ -313,7 +315,7 @@ Error RouterTable::Release(uint8_t aRouterId) Get().RemoveBorderRouter(rloc16, NetworkData::Leader::kMatchModeRouterId); Get().ResetAdvertiseInterval(); - otLogNoteMle("Release router id %d", aRouterId); + LogNote("Release router id %d", aRouterId); exit: return error; diff --git a/src/core/thread/src_match_controller.cpp b/src/core/thread/src_match_controller.cpp index 810118b88..371405f7a 100644 --- a/src/core/thread/src_match_controller.cpp +++ b/src/core/thread/src_match_controller.cpp @@ -39,7 +39,7 @@ #include "common/debug.hpp" #include "common/instance.hpp" #include "common/locator_getters.hpp" -#include "common/logging.hpp" +#include "common/log.hpp" #include "mac/mac_types.hpp" #include "radio/radio.hpp" #include "thread/mesh_forwarder.hpp" @@ -48,6 +48,8 @@ namespace ot { +RegisterLogModule("SrcMatchCtrl"); + SourceMatchController::SourceMatchController(Instance &aInstance) : InstanceLocator(aInstance) , mEnabled(false) @@ -69,7 +71,7 @@ void SourceMatchController::DecrementMessageCount(Child &aChild) { if (aChild.GetIndirectMessageCount() == 0) { - otLogWarnMac("DecrementMessageCount(child 0x%04x) called when already at zero count.", aChild.GetRloc16()); + LogWarn("DecrementMessageCount(child 0x%04x) called when already at zero count.", aChild.GetRloc16()); ExitNow(); } @@ -113,14 +115,14 @@ void SourceMatchController::ClearTable(void) { Get().ClearSrcMatchShortEntries(); Get().ClearSrcMatchExtEntries(); - otLogDebgMac("SrcAddrMatch - Cleared all entries"); + LogDebg("Cleared all entries"); } void SourceMatchController::Enable(bool aEnable) { mEnabled = aEnable; Get().EnableSrcMatch(mEnabled); - otLogDebgMac("SrcAddrMatch - %sabling", mEnabled ? "En" : "Dis"); + LogDebg("%sabling", mEnabled ? "En" : "Dis"); } void SourceMatchController::AddEntry(Child &aChild) @@ -150,8 +152,7 @@ Error SourceMatchController::AddAddress(const Child &aChild) { error = Get().AddSrcMatchShortEntry(aChild.GetRloc16()); - otLogDebgMac("SrcAddrMatch - Adding short addr: 0x%04x -- %s (%d)", aChild.GetRloc16(), ErrorToString(error), - error); + LogDebg("Adding short addr: 0x%04x -- %s (%d)", aChild.GetRloc16(), ErrorToString(error), error); } else { @@ -160,8 +161,8 @@ Error SourceMatchController::AddAddress(const Child &aChild) address.Set(aChild.GetExtAddress().m8, Mac::ExtAddress::kReverseByteOrder); error = Get().AddSrcMatchExtEntry(address); - otLogDebgMac("SrcAddrMatch - Adding addr: %s -- %s (%d)", aChild.GetExtAddress().ToString().AsCString(), - ErrorToString(error), error); + LogDebg("Adding addr: %s -- %s (%d)", aChild.GetExtAddress().ToString().AsCString(), ErrorToString(error), + error); } return error; @@ -173,7 +174,7 @@ void SourceMatchController::ClearEntry(Child &aChild) if (aChild.IsIndirectSourceMatchPending()) { - otLogDebgMac("SrcAddrMatch - Clearing pending flag for 0x%04x", aChild.GetRloc16()); + LogDebg("Clearing pending flag for 0x%04x", aChild.GetRloc16()); aChild.SetIndirectSourceMatchPending(false); ExitNow(); } @@ -182,8 +183,7 @@ void SourceMatchController::ClearEntry(Child &aChild) { error = Get().ClearSrcMatchShortEntry(aChild.GetRloc16()); - otLogDebgMac("SrcAddrMatch - Clearing short addr: 0x%04x -- %s (%d)", aChild.GetRloc16(), ErrorToString(error), - error); + LogDebg("Clearing short addr: 0x%04x -- %s (%d)", aChild.GetRloc16(), ErrorToString(error), error); } else { @@ -192,8 +192,8 @@ void SourceMatchController::ClearEntry(Child &aChild) address.Set(aChild.GetExtAddress().m8, Mac::ExtAddress::kReverseByteOrder); error = Get().ClearSrcMatchExtEntry(address); - otLogDebgMac("SrcAddrMatch - Clearing addr: %s -- %s (%d)", aChild.GetExtAddress().ToString().AsCString(), - ErrorToString(error), error); + LogDebg("Clearing addr: %s -- %s (%d)", aChild.GetExtAddress().ToString().AsCString(), ErrorToString(error), + error); } SuccessOrExit(error); diff --git a/src/core/thread/time_sync_service.cpp b/src/core/thread/time_sync_service.cpp index 001997d86..e938f3820 100644 --- a/src/core/thread/time_sync_service.cpp +++ b/src/core/thread/time_sync_service.cpp @@ -43,12 +43,14 @@ #include "common/instance.hpp" #include "common/locator_getters.hpp" -#include "common/logging.hpp" +#include "common/log.hpp" #define ABS(value) (((value) >= 0) ? (value) : -(value)) namespace ot { +RegisterLogModule("TimeSync"); + TimeSync::TimeSync(Instance &aInstance) : InstanceLocator(aInstance) , mTimeSyncRequired(false) @@ -90,8 +92,7 @@ void TimeSync::HandleTimeSyncMessage(const Message &aMessage) // synchronized with the current sequence, so forward it. mTimeSyncRequired = true; - otLogInfoCore("Older time sync seq received:%u. Forwarding current seq:%u", aMessage.GetTimeSyncSeq(), - mTimeSyncSeq); + LogInfo("Older time sync seq received:%u. Forwarding current seq:%u", aMessage.GetTimeSyncSeq(), mTimeSyncSeq); } else if (Get().IsLeader() && timeSyncSeqDelta > 0) { @@ -101,8 +102,8 @@ void TimeSync::HandleTimeSyncMessage(const Message &aMessage) mTimeSyncSeq = aMessage.GetTimeSyncSeq() + 1; mTimeSyncRequired = true; - otLogInfoCore("Newer time sync seq:%u received by leader. Setting current seq to:%u and forwarding", - aMessage.GetTimeSyncSeq(), mTimeSyncSeq); + LogInfo("Newer time sync seq:%u received by leader. Setting current seq to:%u and forwarding", + aMessage.GetTimeSyncSeq(), mTimeSyncSeq); } else if (!Get().IsLeader()) { @@ -118,7 +119,7 @@ void TimeSync::HandleTimeSyncMessage(const Message &aMessage) mNetworkTimeOffset = aMessage.GetNetworkTimeOffset(); mTimeSyncRequired = true; - otLogInfoCore("Newer time sync seq:%u received. Forwarding", mTimeSyncSeq); + LogInfo("Newer time sync seq:%u received. Forwarding", mTimeSyncSeq); // Only notify listeners of an update for network time offset jumps of more than // OPENTHREAD_CONFIG_TIME_SYNC_JUMP_NOTIF_MIN_US but notify listeners regardless if the status changes. @@ -156,7 +157,7 @@ void TimeSync::ProcessTimeSync(void) IncrementTimeSyncSeq(); mTimeSyncRequired = true; - otLogInfoCore("Leader seeding new time sync seq:%u", mTimeSyncSeq); + LogInfo("Leader seeding new time sync seq:%u", mTimeSyncSeq); } if (mTimeSyncRequired) @@ -194,7 +195,7 @@ void TimeSync::HandleNotifierEvents(Events aEvents) stateChanged = true; - otLogInfoCore("Resetting time sync seq, partition changed"); + LogInfo("Resetting time sync seq, partition changed"); } if (stateChanged) @@ -226,7 +227,7 @@ void TimeSync::CheckAndHandleChanges(bool aTimeUpdated) case Mle::kRoleDisabled: case Mle::kRoleDetached: networkTimeStatus = OT_NETWORK_TIME_UNSYNCHRONIZED; - otLogInfoCore("Time sync status UNSYNCHRONIZED as role:DISABLED/DETACHED"); + LogInfo("Time sync status UNSYNCHRONIZED as role:DISABLED/DETACHED"); break; case Mle::kRoleChild: @@ -235,26 +236,26 @@ void TimeSync::CheckAndHandleChanges(bool aTimeUpdated) { // Haven't yet received any time sync networkTimeStatus = OT_NETWORK_TIME_UNSYNCHRONIZED; - otLogInfoCore("Time sync status UNSYNCHRONIZED as mLastTimeSyncReceived:0"); + LogInfo("Time sync status UNSYNCHRONIZED as mLastTimeSyncReceived:0"); } else if (timeSyncLastSyncMs > resyncNeededThresholdMs) { // The device hasn’t received time sync for more than two periods time. networkTimeStatus = OT_NETWORK_TIME_RESYNC_NEEDED; - otLogInfoCore("Time sync status RESYNC_NEEDED as timeSyncLastSyncMs:%u > resyncNeededThresholdMs:%u", - timeSyncLastSyncMs, resyncNeededThresholdMs); + LogInfo("Time sync status RESYNC_NEEDED as timeSyncLastSyncMs:%u > resyncNeededThresholdMs:%u", + timeSyncLastSyncMs, resyncNeededThresholdMs); } else { // Schedule a check 1 millisecond after two periods of time OT_ASSERT(resyncNeededThresholdMs >= timeSyncLastSyncMs); mTimer.Start(resyncNeededThresholdMs - timeSyncLastSyncMs + 1); - otLogInfoCore("Time sync status SYNCHRONIZED"); + LogInfo("Time sync status SYNCHRONIZED"); } break; case Mle::kRoleLeader: - otLogInfoCore("Time sync status SYNCHRONIZED as role:LEADER"); + LogInfo("Time sync status SYNCHRONIZED as role:LEADER"); break; } diff --git a/src/core/thread/topology.cpp b/src/core/thread/topology.cpp index 1010bf717..47120fe0a 100644 --- a/src/core/thread/topology.cpp +++ b/src/core/thread/topology.cpp @@ -38,7 +38,6 @@ #include "common/debug.hpp" #include "common/instance.hpp" #include "common/locator_getters.hpp" -#include "common/logging.hpp" namespace ot { diff --git a/src/core/utils/channel_manager.cpp b/src/core/utils/channel_manager.cpp index ac2c6bae9..93c24f598 100644 --- a/src/core/utils/channel_manager.cpp +++ b/src/core/utils/channel_manager.cpp @@ -39,7 +39,7 @@ #include "common/code_utils.hpp" #include "common/instance.hpp" #include "common/locator_getters.hpp" -#include "common/logging.hpp" +#include "common/log.hpp" #include "common/random.hpp" #include "common/string.hpp" #include "meshcop/dataset_updater.hpp" @@ -48,6 +48,8 @@ namespace ot { namespace Utils { +RegisterLogModule("ChannelManager"); + ChannelManager::ChannelManager(Instance &aInstance) : InstanceLocator(aInstance) , mSupportedChannelMask(0) @@ -64,11 +66,11 @@ ChannelManager::ChannelManager(Instance &aInstance) void ChannelManager::RequestChannelChange(uint8_t aChannel) { - otLogInfoUtil("ChannelManager: Request to change to channel %d with delay %d sec", aChannel, mDelay); + LogInfo("Request to change to channel %d with delay %d sec", aChannel, mDelay); if (aChannel == Get().GetPanChannel()) { - otLogInfoUtil("ChannelManager: Already operating on the requested channel %d", aChannel); + LogInfo("Already operating on the requested channel %d", aChannel); ExitNow(); } @@ -120,7 +122,7 @@ void ChannelManager::StartDatasetUpdate(void) break; case kErrorInvalidState: - otLogInfoUtil("ChannelManager: Request to change to channel %d failed. Device is disabled", mChannel); + LogInfo("Request to change to channel %d failed. Device is disabled", mChannel); OT_FALL_THROUGH; @@ -140,12 +142,12 @@ void ChannelManager::HandleDatasetUpdateDone(Error aError) { if (aError == kErrorNone) { - otLogInfoUtil("ChannelManager: Channel changed to %d", mChannel); + LogInfo("Channel changed to %d", mChannel); } else { - otLogInfoUtil("ChannelManager: Canceling channel change to %d%s", mChannel, - (aError == kErrorAlready) ? " since current ActiveDataset is more recent" : ""); + LogInfo("Canceling channel change to %d%s", mChannel, + (aError == kErrorAlready) ? " since current ActiveDataset is more recent" : ""); } mState = kStateIdle; @@ -162,7 +164,7 @@ void ChannelManager::HandleTimer(void) switch (mState) { case kStateIdle: - otLogInfoUtil("ChannelManager: Auto-triggered channel select"); + LogInfo("Auto-triggered channel select"); IgnoreError(RequestChannelSelect(false)); StartAutoSelectTimer(); break; @@ -189,8 +191,8 @@ Error ChannelManager::FindBetterChannel(uint8_t &aNewChannel, uint16_t &aOccupan if (Get().GetSampleCount() <= kMinChannelMonitorSampleCount) { - otLogInfoUtil("ChannelManager: Too few samples (%d <= %d) to select channel", - Get().GetSampleCount(), kMinChannelMonitorSampleCount); + LogInfo("Too few samples (%d <= %d) to select channel", Get().GetSampleCount(), + kMinChannelMonitorSampleCount); ExitNow(error = kErrorInvalidState); } @@ -200,10 +202,8 @@ Error ChannelManager::FindBetterChannel(uint8_t &aNewChannel, uint16_t &aOccupan favoredBest = Get().FindBestChannels(favoredAndSupported, favoredOccupancy); supportedBest = Get().FindBestChannels(mSupportedChannelMask, supportedOccupancy); - otLogInfoUtil("ChannelManager: Best favored %s, occupancy 0x%04x", favoredBest.ToString().AsCString(), - favoredOccupancy); - otLogInfoUtil("ChannelManager: Best overall %s, occupancy 0x%04x", supportedBest.ToString().AsCString(), - supportedOccupancy); + LogInfo("Best favored %s, occupancy 0x%04x", favoredBest.ToString().AsCString(), favoredOccupancy); + LogInfo("Best overall %s, occupancy 0x%04x", supportedBest.ToString().AsCString(), supportedOccupancy); // Prefer favored channels unless there is no favored channel, // or the occupancy rate of the best favored channel is worse @@ -214,7 +214,7 @@ Error ChannelManager::FindBetterChannel(uint8_t &aNewChannel, uint16_t &aOccupan { if (!favoredBest.IsEmpty()) { - otLogInfoUtil("ChannelManager: Preferring an unfavored channel due to high occupancy rate diff"); + LogInfo("Preferring an unfavored channel due to high occupancy rate diff"); } favoredBest = supportedBest; @@ -235,8 +235,8 @@ bool ChannelManager::ShouldAttemptChannelChange(void) uint16_t ccaFailureRate = Get().GetCcaFailureRate(); bool shouldAttempt = (ccaFailureRate >= mCcaFailureRateThreshold); - otLogInfoUtil("ChannelManager: CCA-err-rate: 0x%04x %s 0x%04x, selecting channel: %s", ccaFailureRate, - shouldAttempt ? ">=" : "<", mCcaFailureRateThreshold, ToYesNo(shouldAttempt)); + LogInfo("CCA-err-rate: 0x%04x %s 0x%04x, selecting channel: %s", ccaFailureRate, shouldAttempt ? ">=" : "<", + mCcaFailureRateThreshold, ToYesNo(shouldAttempt)); return shouldAttempt; } @@ -247,7 +247,7 @@ Error ChannelManager::RequestChannelSelect(bool aSkipQualityCheck) uint8_t curChannel, newChannel; uint16_t curOccupancy, newOccupancy; - otLogInfoUtil("ChannelManager: Request to select channel (skip quality check: %s)", ToYesNo(aSkipQualityCheck)); + LogInfo("Request to select channel (skip quality check: %s)", ToYesNo(aSkipQualityCheck)); VerifyOrExit(!Get().IsDisabled(), error = kErrorInvalidState); @@ -260,12 +260,12 @@ Error ChannelManager::RequestChannelSelect(bool aSkipQualityCheck) if (newChannel == curChannel) { - otLogInfoUtil("ChannelManager: Already on best possible channel %d", curChannel); + LogInfo("Already on best possible channel %d", curChannel); ExitNow(); } - otLogInfoUtil("ChannelManager: Cur channel %d, occupancy 0x%04x - Best channel %d, occupancy 0x%04x", curChannel, - curOccupancy, newChannel, newOccupancy); + LogInfo("Cur channel %d, occupancy 0x%04x - Best channel %d, occupancy 0x%04x", curChannel, curOccupancy, + newChannel, newOccupancy); // Switch only if new channel's occupancy rate is better than current // channel's occupancy rate by threshold `kThresholdToChangeChannel`. @@ -273,7 +273,7 @@ Error ChannelManager::RequestChannelSelect(bool aSkipQualityCheck) if ((newOccupancy >= curOccupancy) || (static_cast(curOccupancy - newOccupancy) < kThresholdToChangeChannel)) { - otLogInfoUtil("ChannelManager: Occupancy rate diff too small to change channel"); + LogInfo("Occupancy rate diff too small to change channel"); ExitNow(); } @@ -283,7 +283,7 @@ exit: if (error != kErrorNone) { - otLogInfoUtil("ChannelManager: Request to select better channel failed, error: %s", ErrorToString(error)); + LogInfo("Request to select better channel failed, error: %s", ErrorToString(error)); } return error; @@ -339,21 +339,21 @@ void ChannelManager::SetSupportedChannels(uint32_t aChannelMask) { mSupportedChannelMask.SetMask(aChannelMask & Get().GetSupportedChannelMask().GetMask()); - otLogInfoUtil("ChannelManager: Supported channels: %s", mSupportedChannelMask.ToString().AsCString()); + LogInfo("Supported channels: %s", mSupportedChannelMask.ToString().AsCString()); } void ChannelManager::SetFavoredChannels(uint32_t aChannelMask) { mFavoredChannelMask.SetMask(aChannelMask & Get().GetSupportedChannelMask().GetMask()); - otLogInfoUtil("ChannelManager: Favored channels: %s", mFavoredChannelMask.ToString().AsCString()); + LogInfo("Favored channels: %s", mFavoredChannelMask.ToString().AsCString()); } void ChannelManager::SetCcaFailureRateThreshold(uint16_t aThreshold) { mCcaFailureRateThreshold = aThreshold; - otLogInfoUtil("ChannelManager: CCA threshold: 0x%04x", mCcaFailureRateThreshold); + LogInfo("CCA threshold: 0x%04x", mCcaFailureRateThreshold); } } // namespace Utils diff --git a/src/core/utils/channel_monitor.cpp b/src/core/utils/channel_monitor.cpp index a6fe604bb..e96c6698c 100644 --- a/src/core/utils/channel_monitor.cpp +++ b/src/core/utils/channel_monitor.cpp @@ -37,12 +37,14 @@ #include "common/code_utils.hpp" #include "common/locator_getters.hpp" -#include "common/logging.hpp" +#include "common/log.hpp" #include "common/random.hpp" namespace ot { namespace Utils { +RegisterLogModule("ChannelMonitor"); + const uint32_t ChannelMonitor::mScanChannelMasks[kNumChannelMasks] = { #if OPENTHREAD_CONFIG_RADIO_915MHZ_OQPSK_SUPPORT OT_CHANNEL_1_MASK | OT_CHANNEL_5_MASK | OT_CHANNEL_9_MASK, @@ -74,7 +76,7 @@ Error ChannelMonitor::Start(void) VerifyOrExit(!IsRunning(), error = kErrorAlready); Clear(); mTimer.Start(kTimerInterval); - otLogDebgUtil("ChannelMonitor: Starting"); + LogDebg("Starting"); exit: return error; @@ -86,7 +88,7 @@ Error ChannelMonitor::Stop(void) VerifyOrExit(IsRunning(), error = kErrorAlready); mTimer.Stop(); - otLogDebgUtil("ChannelMonitor: Stopping"); + LogDebg("Stopping"); exit: return error; @@ -98,7 +100,7 @@ void ChannelMonitor::Clear(void) mSampleCount = 0; memset(mChannelOccupancy, 0, sizeof(mChannelOccupancy)); - otLogDebgUtil("ChannelMonitor: Clearing data"); + LogDebg("Clearing data"); } uint16_t ChannelMonitor::GetChannelOccupancy(uint8_t aChannel) const @@ -154,7 +156,7 @@ void ChannelMonitor::HandleEnergyScanResult(Mac::EnergyScanResult *aResult) OT_ASSERT(channelIndex < kNumChannels); - otLogDebgUtil("ChannelMonitor: channel: %d, rssi:%d", aResult->mChannel, aResult->mMaxRssi); + LogDebg("channel: %d, rssi:%d", aResult->mChannel, aResult->mMaxRssi); if (aResult->mMaxRssi != OT_RADIO_RSSI_INVALID) { @@ -189,7 +191,7 @@ void ChannelMonitor::HandleEnergyScanResult(Mac::EnergyScanResult *aResult) void ChannelMonitor::LogResults(void) { -#if (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO) && (OPENTHREAD_CONFIG_LOG_UTIL == 1) +#if OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO const size_t kStringSize = 128; String logString; @@ -198,7 +200,7 @@ void ChannelMonitor::LogResults(void) logString.Append("%02x ", channel >> 8); } - otLogInfoUtil("ChannelMonitor: %u [%s]", mSampleCount, logString.AsCString()); + LogInfo("%u [%s]", mSampleCount, logString.AsCString()); #endif } diff --git a/src/core/utils/child_supervision.cpp b/src/core/utils/child_supervision.cpp index 7f6368aec..b0f45bdd1 100644 --- a/src/core/utils/child_supervision.cpp +++ b/src/core/utils/child_supervision.cpp @@ -37,12 +37,14 @@ #include "common/code_utils.hpp" #include "common/instance.hpp" #include "common/locator_getters.hpp" -#include "common/logging.hpp" +#include "common/log.hpp" #include "thread/thread_netif.hpp" namespace ot { namespace Utils { +RegisterLogModule("ChildSupervsn"); + #if OPENTHREAD_CONFIG_CHILD_SUPERVISION_ENABLE #if OPENTHREAD_FTD @@ -94,7 +96,7 @@ void ChildSupervisor::SendMessage(Child &aChild) SuccessOrExit(Get().SendMessage(*message)); message = nullptr; - otLogInfoUtil("Sending supervision message to child 0x%04x", aChild.GetRloc16()); + LogInfo("Sending supervision message to child 0x%04x", aChild.GetRloc16()); exit: FreeMessage(message); @@ -132,13 +134,13 @@ void ChildSupervisor::CheckState(void) if (shouldRun && !Get().IsReceiverRegistered(TimeTicker::kChildSupervisor)) { Get().RegisterReceiver(TimeTicker::kChildSupervisor); - otLogInfoUtil("Starting Child Supervision"); + LogInfo("Starting Child Supervision"); } if (!shouldRun && Get().IsReceiverRegistered(TimeTicker::kChildSupervisor)) { Get().UnregisterReceiver(TimeTicker::kChildSupervisor); - otLogInfoUtil("Stopping Child Supervision"); + LogInfo("Stopping Child Supervision"); } } @@ -213,7 +215,7 @@ void SupervisionListener::HandleTimer(void) { VerifyOrExit(Get().IsChild() && !Get().GetRxOnWhenIdle()); - otLogWarnUtil("Supervision timeout. No frame from parent in %d sec", mTimeout); + LogWarn("Supervision timeout. No frame from parent in %d sec", mTimeout); IgnoreError(Get().SendChildUpdateRequest()); diff --git a/src/core/utils/jam_detector.cpp b/src/core/utils/jam_detector.cpp index 44353ee69..ce4a4bcf7 100644 --- a/src/core/utils/jam_detector.cpp +++ b/src/core/utils/jam_detector.cpp @@ -38,13 +38,15 @@ #include "common/code_utils.hpp" #include "common/instance.hpp" #include "common/locator_getters.hpp" -#include "common/logging.hpp" +#include "common/log.hpp" #include "common/random.hpp" #include "thread/thread_netif.hpp" namespace ot { namespace Utils { +RegisterLogModule("JamDetector"); + JamDetector::JamDetector(Instance &aInstance) : InstanceLocator(aInstance) , mHandler(nullptr) @@ -73,7 +75,7 @@ Error JamDetector::Start(Handler aHandler, void *aContext) mContext = aContext; mEnabled = true; - otLogInfoUtil("JamDetector - Started"); + LogInfo("Started"); CheckState(); @@ -92,7 +94,7 @@ Error JamDetector::Stop(void) mTimer.Stop(); - otLogInfoUtil("JamDetector - Stopped"); + LogInfo("Stopped"); exit: return error; @@ -128,7 +130,7 @@ exit: void JamDetector::SetRssiThreshold(int8_t aThreshold) { mRssiThreshold = aThreshold; - otLogInfoUtil("JamDetector - RSSI threshold set to %d", mRssiThreshold); + LogInfo("RSSI threshold set to %d", mRssiThreshold); } Error JamDetector::SetWindow(uint8_t aWindow) @@ -139,7 +141,7 @@ Error JamDetector::SetWindow(uint8_t aWindow) VerifyOrExit(aWindow <= kMaxWindow, error = kErrorInvalidArgs); mWindow = aWindow; - otLogInfoUtil("JamDetector - window set to %d", mWindow); + LogInfo("window set to %d", mWindow); exit: return error; @@ -153,7 +155,7 @@ Error JamDetector::SetBusyPeriod(uint8_t aBusyPeriod) VerifyOrExit(aBusyPeriod <= mWindow, error = kErrorInvalidArgs); mBusyPeriod = aBusyPeriod; - otLogInfoUtil("JamDetector - busy period set to %d", mBusyPeriod); + LogInfo("busy period set to %d", mBusyPeriod); exit: return error; @@ -261,7 +263,7 @@ void JamDetector::SetJamState(bool aNewState) { mJamState = aNewState; shouldInvokeHandler = true; - otLogInfoUtil("JamDetector - jamming %s", mJamState ? "detected" : "cleared"); + LogInfo("Jamming %s", mJamState ? "detected" : "cleared"); } if (shouldInvokeHandler) diff --git a/src/core/utils/otns.cpp b/src/core/utils/otns.cpp index 7bcd13d91..0030fba0c 100644 --- a/src/core/utils/otns.cpp +++ b/src/core/utils/otns.cpp @@ -38,11 +38,13 @@ #include "common/debug.hpp" #include "common/locator_getters.hpp" -#include "common/logging.hpp" +#include "common/log.hpp" namespace ot { namespace Utils { +RegisterLogModule("Otns"); + const int kMaxStatusStringLength = 128; void Otns::EmitShortAddress(uint16_t aShortAddress) @@ -170,7 +172,7 @@ void Otns::EmitCoapSend(const Coap::Message &aMessage, const Ip6::MessageInfo &a exit: if (error != kErrorNone) { - otLogWarnCore("Otns::EmitCoapSend failed: %s", ErrorToString(error)); + LogWarn("EmitCoapSend failed: %s", ErrorToString(error)); } } @@ -186,7 +188,7 @@ void Otns::EmitCoapReceive(const Coap::Message &aMessage, const Ip6::MessageInfo exit: if (error != kErrorNone) { - otLogWarnCore("Otns::EmitCoapReceive failed: %s", ErrorToString(error)); + LogWarn("EmitCoapReceive failed: %s", ErrorToString(error)); } } @@ -203,7 +205,7 @@ void Otns::EmitCoapSendFailure(Error aError, Coap::Message &aMessage, const Ip6: exit: if (error != kErrorNone) { - otLogWarnCore("Otns::EmitCoapSendFailure failed: %s", ErrorToString(error)); + LogWarn("EmitCoapSendFailure failed: %s", ErrorToString(error)); } } diff --git a/src/core/utils/slaac_address.cpp b/src/core/utils/slaac_address.cpp index 08c080522..82cadfcba 100644 --- a/src/core/utils/slaac_address.cpp +++ b/src/core/utils/slaac_address.cpp @@ -39,7 +39,7 @@ #include "common/code_utils.hpp" #include "common/instance.hpp" #include "common/locator_getters.hpp" -#include "common/logging.hpp" +#include "common/log.hpp" #include "common/random.hpp" #include "common/settings.hpp" #include "crypto/sha256.hpp" @@ -48,6 +48,8 @@ namespace ot { namespace Utils { +RegisterLogModule("Slaac"); + Slaac::Slaac(Instance &aInstance) : InstanceLocator(aInstance) , mEnabled(true) @@ -60,7 +62,7 @@ void Slaac::Enable(void) { VerifyOrExit(!mEnabled); - otLogInfoUtil("SLAAC:: Enabling"); + LogInfo("Enabling"); mEnabled = true; Update(kModeAdd); @@ -72,7 +74,7 @@ void Slaac::Disable(void) { VerifyOrExit(mEnabled); - otLogInfoUtil("SLAAC:: Disabling"); + LogInfo("Disabling"); mEnabled = false; Update(kModeRemove); @@ -85,7 +87,7 @@ void Slaac::SetFilter(otIp6SlaacPrefixFilter aFilter) VerifyOrExit(aFilter != mFilter); mFilter = aFilter; - otLogInfoUtil("SLAAC: Filter %s", (mFilter != nullptr) ? "updated" : "disabled"); + LogInfo("Filter %s", (mFilter != nullptr) ? "updated" : "disabled"); VerifyOrExit(mEnabled); Update(kModeAdd | kModeRemove); @@ -184,7 +186,7 @@ void Slaac::Update(UpdateMode aMode) if (!found) { - otLogInfoUtil("SLAAC: Removing address %s", slaacAddr.GetAddress().ToString().AsCString()); + LogInfo("Removing address %s", slaacAddr.GetAddress().ToString().AsCString()); Get().RemoveUnicastAddress(slaacAddr); slaacAddr.mValid = false; @@ -234,7 +236,7 @@ void Slaac::Update(UpdateMode aMode) IgnoreError(GenerateIid(slaacAddr)); - otLogInfoUtil("SLAAC: Adding address %s", slaacAddr.GetAddress().ToString().AsCString()); + LogInfo("Adding address %s", slaacAddr.GetAddress().ToString().AsCString()); Get().AddUnicastAddress(slaacAddr); @@ -244,8 +246,8 @@ void Slaac::Update(UpdateMode aMode) if (!added) { - otLogWarnUtil("SLAAC: Failed to add - max %d addresses supported and already in use", - GetArrayLength(mAddresses)); + LogWarn("Failed to add - max %d addresses supported and already in use", + GetArrayLength(mAddresses)); } } } @@ -316,7 +318,7 @@ Error Slaac::GenerateIid(Ip6::Netif::UnicastAddress &aAddress, ExitNow(error = kErrorNone); } - otLogWarnUtil("SLAAC: Failed to generate a non-reserved IID after %d attempts", kMaxIidCreationAttempts); + LogWarn("Failed to generate a non-reserved IID after %d attempts", kMaxIidCreationAttempts); exit: return error; @@ -341,7 +343,7 @@ void Slaac::GetIidSecretKey(IidSecretKey &aKey) const IgnoreError(Get().Save(aKey)); - otLogInfoUtil("SLAAC: Generated and saved secret key"); + LogInfo("Generated and saved secret key"); exit: return; diff --git a/src/lib/spinel/radio_spinel_impl.hpp b/src/lib/spinel/radio_spinel_impl.hpp index 9faf91548..b96d531d9 100644 --- a/src/lib/spinel/radio_spinel_impl.hpp +++ b/src/lib/spinel/radio_spinel_impl.hpp @@ -37,13 +37,13 @@ #include #include +#include #include #include #include "common/code_utils.hpp" #include "common/encoding.hpp" #include "common/instance.hpp" -#include "common/logging.hpp" #include "common/new.hpp" #include "common/settings.hpp" #include "lib/platform/exit_code.h" diff --git a/src/ncp/ncp_base.cpp b/src/ncp/ncp_base.cpp index 1b710c658..1c35701f0 100644 --- a/src/ncp/ncp_base.cpp +++ b/src/ncp/ncp_base.cpp @@ -2630,14 +2630,4 @@ extern "C" void otPlatLog(otLogLevel aLogLevel, otLogRegion aLogRegion, const ch va_end(args); } -extern "C" void otPlatLogLine(otLogLevel aLogLevel, otLogRegion aLogRegion, const char *aLogLine) -{ - ot::Ncp::NcpBase *ncp = ot::Ncp::NcpBase::GetNcpInstance(); - - if (ncp != nullptr) - { - ncp->Log(aLogLevel, aLogRegion, aLogLine); - } -} - #endif // (OPENTHREAD_CONFIG_LOG_OUTPUT == OPENTHREAD_CONFIG_LOG_OUTPUT_APP) diff --git a/src/posix/main.c b/src/posix/main.c index ebecb4777..74b85f2f3 100644 --- a/src/posix/main.c +++ b/src/posix/main.c @@ -64,7 +64,6 @@ #include "cli/cli_config.h" #endif #include -#include #include #include #include diff --git a/src/posix/platform/firewall.cpp b/src/posix/platform/firewall.cpp index 671dff7ca..19ad8c519 100644 --- a/src/posix/platform/firewall.cpp +++ b/src/posix/platform/firewall.cpp @@ -36,8 +36,10 @@ #include +#include +#include + #include "common/code_utils.hpp" -#include "openthread/netdata.h" #include "posix/platform/utils.hpp" namespace ot { diff --git a/src/posix/platform/firewall.hpp b/src/posix/platform/firewall.hpp index 8c4378a6a..a564c567e 100644 --- a/src/posix/platform/firewall.hpp +++ b/src/posix/platform/firewall.hpp @@ -33,7 +33,6 @@ #if OPENTHREAD_POSIX_CONFIG_FIREWALL_ENABLE -#include "common/logging.hpp" #include "openthread/thread.h" namespace ot { diff --git a/src/posix/platform/hdlc_interface.cpp b/src/posix/platform/hdlc_interface.cpp index 264a12392..391fdacd5 100644 --- a/src/posix/platform/hdlc_interface.cpp +++ b/src/posix/platform/hdlc_interface.cpp @@ -57,8 +57,9 @@ #include #include +#include + #include "common/code_utils.hpp" -#include "common/logging.hpp" #ifdef __APPLE__ diff --git a/src/posix/platform/misc.cpp b/src/posix/platform/misc.cpp index 5de8b9dd6..77ef07a90 100644 --- a/src/posix/platform/misc.cpp +++ b/src/posix/platform/misc.cpp @@ -35,10 +35,10 @@ #include #include +#include #include #include "common/code_utils.hpp" -#include "common/logging.hpp" otPlatResetReason gPlatResetReason = OT_PLAT_RESET_REASON_POWER_ON; static otPlatMcuPowerState gPlatMcuPowerState = OT_PLAT_MCU_POWER_STATE_ON; diff --git a/src/posix/platform/multicast_routing.cpp b/src/posix/platform/multicast_routing.cpp index ab35d03ab..a548feaa9 100644 --- a/src/posix/platform/multicast_routing.cpp +++ b/src/posix/platform/multicast_routing.cpp @@ -46,9 +46,10 @@ #endif #include +#include +#include "core/common/arg_macros.hpp" #include "core/common/debug.hpp" -#include "core/common/logging.hpp" namespace ot { namespace Posix { diff --git a/src/posix/platform/netif.cpp b/src/posix/platform/netif.cpp index d47210eb7..06bf55c99 100644 --- a/src/posix/platform/netif.cpp +++ b/src/posix/platform/netif.cpp @@ -140,13 +140,13 @@ extern int #include #include #include +#include #include #include #include #include "common/code_utils.hpp" #include "common/debug.hpp" -#include "common/logging.hpp" #include "net/ip6_address.hpp" unsigned int gNetifIndex = 0; @@ -776,7 +776,7 @@ static void processReceive(otMessage *aMessage, void *aContext) #if OPENTHREAD_POSIX_LOG_TUN_PACKETS otLogInfoPlat("[netif] Packet from NCP (%u bytes)", static_cast(length)); - otDumpInfo(OT_LOG_REGION_PLATFORM, "", &packet[offset], length); + otDumpInfoPlat("", &packet[offset], length); #endif #if defined(__APPLE__) || defined(__NetBSD__) || defined(__FreeBSD__) @@ -831,7 +831,7 @@ static void processTransmit(otInstance *aInstance) #if OPENTHREAD_POSIX_LOG_TUN_PACKETS otLogInfoPlat("[netif] Packet to NCP (%hu bytes)", static_cast(rval)); - otDumpInfo(OT_LOG_REGION_PLATFORM, "", &packet[offset], static_cast(rval)); + otDumpInfoPlat("", &packet[offset], static_cast(rval)); #endif SuccessOrExit(error = otMessageAppend(message, &packet[offset], static_cast(rval))); diff --git a/src/posix/platform/platform-posix.h b/src/posix/platform/platform-posix.h index 6ecbc503d..0f9793b7a 100644 --- a/src/posix/platform/platform-posix.h +++ b/src/posix/platform/platform-posix.h @@ -48,11 +48,10 @@ #include #include #include +#include #include #include -#include "common/logging.hpp" - #include "lib/platform/exit_code.h" #include "lib/url/url.hpp" diff --git a/src/posix/platform/settings.cpp b/src/posix/platform/settings.cpp index b4892873e..140d762a3 100644 --- a/src/posix/platform/settings.cpp +++ b/src/posix/platform/settings.cpp @@ -44,6 +44,7 @@ #include #include +#include #include #include #include @@ -496,6 +497,17 @@ void otPlatSettingsWipe(otInstance *aInstance) #if SELF_TEST +void otLogCritPlat(const char *aFormat, ...) +{ + OT_UNUSED_VARIABLE(aFormat); +} + +const char *otExitCodeToString(uint8_t aExitCode) +{ + OT_UNUSED_VARIABLE(aExitCode); + return ""; +} + void otPlatRadioGetIeeeEui64(otInstance *aInstance, uint8_t *aIeeeEui64) { OT_UNUSED_VARIABLE(aInstance); diff --git a/src/posix/platform/spi_interface.cpp b/src/posix/platform/spi_interface.cpp index 3d58202b5..96dbcb89d 100644 --- a/src/posix/platform/spi_interface.cpp +++ b/src/posix/platform/spi_interface.cpp @@ -398,8 +398,8 @@ otError SpiInterface::DoSpiTransfer(uint8_t *aSpiRxFrameBuffer, uint32_t aTransf if (ret != -1) { - otDumpDebg(OT_LOG_REGION_PLATFORM, "SPI-TX", mSpiTxFrameBuffer, transfer[1].len); - otDumpDebg(OT_LOG_REGION_PLATFORM, "SPI-RX", aSpiRxFrameBuffer, transfer[1].len); + otDumpDebgPlat("SPI-TX", mSpiTxFrameBuffer, static_cast(transfer[1].len)); + otDumpDebgPlat("SPI-RX", aSpiRxFrameBuffer, static_cast(transfer[1].len)); mSpiFrameCount++; } @@ -528,8 +528,8 @@ otError SpiInterface::PushPullSpi(void) otLogWarnPlat("Garbage in header : %02X %02X %02X %02X %02X", spiRxFrame[0], spiRxFrame[1], spiRxFrame[2], spiRxFrame[3], spiRxFrame[4]); - otDumpDebg(OT_LOG_REGION_PLATFORM, "SPI-TX", mSpiTxFrameBuffer, spiTransferBytes); - otDumpDebg(OT_LOG_REGION_PLATFORM, "SPI-RX", spiRxFrameBuffer, spiTransferBytes); + otDumpDebgPlat("SPI-TX", mSpiTxFrameBuffer, spiTransferBytes); + otDumpDebgPlat("SPI-RX", spiRxFrameBuffer, spiTransferBytes); } mSpiTxRefusedCount++; @@ -547,8 +547,8 @@ otError SpiInterface::PushPullSpi(void) otLogWarnPlat("Garbage in header : %02X %02X %02X %02X %02X", spiRxFrame[0], spiRxFrame[1], spiRxFrame[2], spiRxFrame[3], spiRxFrame[4]); - otDumpDebg(OT_LOG_REGION_PLATFORM, "SPI-TX", mSpiTxFrameBuffer, spiTransferBytes); - otDumpDebg(OT_LOG_REGION_PLATFORM, "SPI-RX", spiRxFrameBuffer, spiTransferBytes); + otDumpDebgPlat("SPI-TX", mSpiTxFrameBuffer, spiTransferBytes); + otDumpDebgPlat("SPI-RX", spiRxFrameBuffer, spiTransferBytes); ExitNow(); } diff --git a/src/posix/platform/system.cpp b/src/posix/platform/system.cpp index b029373c2..d3d4c2237 100644 --- a/src/posix/platform/system.cpp +++ b/src/posix/platform/system.cpp @@ -379,15 +379,6 @@ void otSysMainloopProcess(otInstance *aInstance, const otSysMainloopContext *aMa #endif } -#if OPENTHREAD_CONFIG_OTNS_ENABLE - -void otPlatOtnsStatus(const char *aStatus) -{ - otLogOtns("[OTNS] %s", aStatus); -} - -#endif - bool IsSystemDryRun(void) { return gDryRun; diff --git a/src/posix/platform/trel.cpp b/src/posix/platform/trel.cpp index 91758755e..b3d9c3681 100644 --- a/src/posix/platform/trel.cpp +++ b/src/posix/platform/trel.cpp @@ -42,12 +42,12 @@ #include #include +#include #include #include "radio_url.hpp" #include "system.hpp" #include "common/code_utils.hpp" -#include "common/logging.hpp" #if OPENTHREAD_CONFIG_RADIO_LINK_TREL_ENABLE @@ -73,8 +73,6 @@ static bool sInitialized = false; static bool sEnabled = false; static int sSocket = -1; -#if OPENTHREAD_CONFIG_LOG_PLATFORM && (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_DEBG) - static const char *Ip6AddrToString(const void *aAddress) { static char string[INET6_ADDRSTRLEN]; @@ -117,8 +115,6 @@ exit: return string; } -#endif // #if OPENTHREAD_CONFIG_LOG_PLATFORM && (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_DEBG) - static void PrepareSocket(uint16_t &aUdpPort) { int val; diff --git a/src/posix/platform/utils.cpp b/src/posix/platform/utils.cpp index 5218841e9..e49740429 100644 --- a/src/posix/platform/utils.cpp +++ b/src/posix/platform/utils.cpp @@ -37,8 +37,9 @@ #include #include +#include + #include "common/code_utils.hpp" -#include "common/logging.hpp" namespace ot { namespace Posix { diff --git a/tests/scripts/thread-cert/node.py b/tests/scripts/thread-cert/node.py index 5f2b445ca..95454aa65 100755 --- a/tests/scripts/thread-cert/node.py +++ b/tests/scripts/thread-cert/node.py @@ -678,7 +678,7 @@ class NodeImpl: return lines def __is_logging_line(self, line: str) -> bool: - return len(line) >= 6 and line[:6] in {'[DEBG]', '[INFO]', '[NOTE]', '[WARN]', '[CRIT]', '[NONE]'} + return len(line) >= 3 and line[:3] in {'[D]', '[I]', '[N]', '[W]', '[C]', '[-]'} def read_cert_messages_in_commissioning_log(self, timeout=-1): """Get the log of the traffic after DTLS handshake. diff --git a/tests/toranj/openthread-core-toranj-config.h b/tests/toranj/openthread-core-toranj-config.h index d2d7ca3b6..c04317d7f 100644 --- a/tests/toranj/openthread-core-toranj-config.h +++ b/tests/toranj/openthread-core-toranj-config.h @@ -316,14 +316,6 @@ */ #define OPENTHREAD_CONFIG_LOG_PREPEND_LEVEL 1 -/** - * @def OPENTHREAD_CONFIG_LOG_PREPEND_REGION - * - * Define to prepend the log region to all log messages - * - */ -#define OPENTHREAD_CONFIG_LOG_PREPEND_REGION 1 - /** * @def OPENTHREAD_CONFIG_LOG_SUFFIX * diff --git a/tests/unit/test_pskc.cpp b/tests/unit/test_pskc.cpp index 19dbed642..d7121f2ff 100644 --- a/tests/unit/test_pskc.cpp +++ b/tests/unit/test_pskc.cpp @@ -27,7 +27,6 @@ */ #include -#include "common/logging.hpp" #include "meshcop/commissioner.hpp" #include "meshcop/meshcop.hpp" diff --git a/tools/harness-thci/OpenThread.py b/tools/harness-thci/OpenThread.py index 32f6f32e3..29b63bdeb 100644 --- a/tools/harness-thci/OpenThread.py +++ b/tools/harness-thci/OpenThread.py @@ -84,23 +84,19 @@ ZEPHYR_PREFIX = 'ot ' LINESEPX = re.compile(r'\r\n|\n') """regex: used to split lines""" -LOGX = re.compile(r'((\[(NONE|CRIT|WARN|NOTE|INFO|DEBG)\])' - r'|(-(CLI|MLR|API|MLE|BBR|DUA|ARP|N-DATA|ICMP|IP6|MAC|MEM|NCP|MESH-CP|DIAG|PLAT|COAP|CORE|UTIL)-+: )' +LOGX = re.compile(r'((\[(-|C|W|N|I|D)\])' r'|(-+$)' # e.x. ------------------------------------------------------------------------ r'|(=+\[.*\]=+$)' # e.x. ==============================[TX len=108]=============================== r'|(\|.+\|.+\|.+)' # e.x. | 61 DC D2 CE FA 04 00 00 | 00 00 0A 6E 16 01 00 00 | aRNz......n.... r')') """regex used to filter logs""" -assert LOGX.match('[NONE]') -assert LOGX.match('[CRIT]') -assert LOGX.match('[WARN]') -assert LOGX.match('[NOTE]') -assert LOGX.match('[INFO]') -assert LOGX.match('[DEBG]') -assert LOGX.match('-CLI-----: ') -assert LOGX.match('-N-DATA--: ') -assert LOGX.match('-MESH-CP-: ') +assert LOGX.match('[-]') +assert LOGX.match('[C]') +assert LOGX.match('[W]') +assert LOGX.match('[N]') +assert LOGX.match('[I]') +assert LOGX.match('[D]') assert LOGX.match('------------------------------------------------------------------------') assert LOGX.match('==============================[TX len=108]===============================') assert LOGX.match('| 61 DC D2 CE FA 04 00 00 | 00 00 0A 6E 16 01 00 00 | aRNz......n....')