[logging] introduce LogWarnOnError() for standardized error logging (#9996)

This commit adds `LogWarnOnError()` to emit warning-level logs on
errors. The emitted log includes the error code. This replaces custom
`LogError()` across modules, simplifying the code.
This commit is contained in:
Abtin Keshavarzian
2024-04-05 09:07:19 -07:00
committed by GitHub
parent 65bc830edb
commit 223935bf0c
27 changed files with 95 additions and 158 deletions
+10
View File
@@ -136,6 +136,16 @@ exit:
return;
}
#if OT_SHOULD_LOG_AT(OT_LOG_LEVEL_WARN)
void Logger::LogOnError(const char *aModuleName, Error aError, const char *aText)
{
if (aError != kErrorNone)
{
LogAtLevel<kLogLevelWarn>(aModuleName, "Failed to %s: %s", aText, ErrorToString(aError));
}
}
#endif
#if OPENTHREAD_CONFIG_LOG_PKT_DUMP
template <LogLevel kLogLevel>
+20
View File
@@ -162,6 +162,22 @@ constexpr uint8_t kMaxLogModuleNameLength = 14; ///< Maximum module name length
#define LogDebg(...)
#endif
#if OT_SHOULD_LOG_AT(OT_LOG_LEVEL_WARN)
/**
* Emits an error log message at warning log level if there is an error.
*
* The emitted log will use the the following format "Failed to {aText}: {ErrorToString(aError)}", and will be emitted
* only if there is an error, i.e., @p aError is not `kErrorNone`.
*
* @param[in] aError The error to check and log.
* @param[in] aText The text to include in the log.
*
*/
#define LogWarnOnError(aError, aText) Logger::LogOnError(kLogModuleName, aError, aText)
#else
#define LogWarnOnError(aError, aText)
#endif
#if OT_SHOULD_LOG
/**
* Emits a log message at a given log level.
@@ -316,6 +332,10 @@ public:
static void LogVarArgs(const char *aModuleName, LogLevel aLogLevel, const char *aFormat, va_list aArgs);
#if OT_SHOULD_LOG_AT(OT_LOG_LEVEL_WARN)
static void LogOnError(const char *aModuleName, Error aError, const char *aText);
#endif
#if OPENTHREAD_CONFIG_LOG_PKT_DUMP
static constexpr uint8_t kStringLineLength = 80;
static constexpr uint8_t kDumpBytesPerLine = 16;
+8 -18
View File
@@ -128,7 +128,7 @@ void BorderAgent::SendErrorMessage(const ForwardContext &aForwardContext, Error
exit:
FreeMessageOnError(message, error);
LogError("send error CoAP message", error);
LogWarnOnError(error, "send error CoAP message");
}
void BorderAgent::SendErrorMessage(const Coap::Message &aRequest, bool aSeparate, Error aError)
@@ -158,7 +158,7 @@ void BorderAgent::SendErrorMessage(const Coap::Message &aRequest, bool aSeparate
exit:
FreeMessageOnError(message, error);
LogError("send error CoAP message", error);
LogWarnOnError(error, "send error CoAP message");
}
Error BorderAgent::SendMessage(Coap::Message &aMessage)
@@ -347,7 +347,7 @@ template <> void BorderAgent::HandleTmf<kUriProxyTx>(Coap::Message &aMessage, co
exit:
FreeMessageOnError(message, error);
LogError("send proxy stream", error);
LogWarnOnError(error, "send proxy stream");
}
bool BorderAgent::HandleUdpReceive(void *aContext, const otMessage *aMessage, const otMessageInfo *aMessageInfo)
@@ -398,7 +398,7 @@ exit:
FreeMessageOnError(message, error);
if (error != kErrorDestinationAddressFiltered)
{
LogError("notify commissioner on ProxyRx (c/ur)", error);
LogWarnOnError(error, "notify commissioner on ProxyRx (c/ur)");
}
return error != kErrorDestinationAddressFiltered;
@@ -436,7 +436,7 @@ Error BorderAgent::ForwardToCommissioner(Coap::Message &aForwardMessage, const M
LogInfo("Sent to commissioner");
exit:
LogError("send to commissioner", error);
LogWarnOnError(error, "send to commissioner");
return error;
}
@@ -520,7 +520,7 @@ template <> void BorderAgent::HandleTmf<kUriRelayTx>(Coap::Message &aMessage, co
exit:
FreeMessageOnError(message, error);
LogError("send to joiner router request RelayTx (c/tx)", error);
LogWarnOnError(error, "send to joiner router request RelayTx (c/tx)");
}
Error BorderAgent::ForwardToLeader(const Coap::Message &aMessage, const Ip6::MessageInfo &aMessageInfo, Uri aUri)
@@ -576,7 +576,7 @@ Error BorderAgent::ForwardToLeader(const Coap::Message &aMessage, const Ip6::Mes
LogInfo("Forwarded request to leader on %s", PathForUri(aUri));
exit:
LogError("forward to leader", error);
LogWarnOnError(error, "forward to leader");
if (error != kErrorNone)
{
@@ -662,7 +662,7 @@ Error BorderAgent::Start(uint16_t aUdpPort, const uint8_t *aPsk, uint8_t aPskLen
LogInfo("Border Agent start listening on port %u", GetUdpPort());
exit:
LogError("start agent", error);
LogWarnOnError(error, "start agent");
return error;
}
@@ -802,16 +802,6 @@ void BorderAgent::HandleSecureAgentStopped(void)
#endif // OPENTHREAD_CONFIG_BORDER_AGENT_EPHEMERAL_KEY_ENABLE
#if OT_SHOULD_LOG_AT(OT_LOG_LEVEL_WARN)
void BorderAgent::LogError(const char *aActionText, Error aError)
{
if (aError != kErrorNone)
{
LogWarn("Failed to %s: %s", aActionText, ErrorToString(aError));
}
}
#endif
} // namespace MeshCoP
} // namespace ot
-6
View File
@@ -308,12 +308,6 @@ private:
static bool HandleUdpReceive(void *aContext, const otMessage *aMessage, const otMessageInfo *aMessageInfo);
bool HandleUdpReceive(const Message &aMessage, const Ip6::MessageInfo &aMessageInfo);
#if OT_SHOULD_LOG_AT(OT_LOG_LEVEL_WARN)
void LogError(const char *aActionText, Error aError);
#else
void LogError(const char *, Error) {}
#endif
using TimeoutTimer = TimerMilliIn<BorderAgent, &BorderAgent::HandleTimeout>;
#if OPENTHREAD_CONFIG_BORDER_AGENT_EPHEMERAL_KEY_ENABLE
using EphemeralKeyTimer = TimerMilliIn<BorderAgent, &BorderAgent::HandleEphemeralKeyTimeout>;
+9 -4
View File
@@ -302,9 +302,9 @@ exit:
if ((error != kErrorNone) && (error != kErrorAlready))
{
Get<Tmf::SecureAgent>().Stop();
LogWarnOnError(error, "start commissioner");
}
LogError("start commissioner", error);
return error;
}
@@ -343,7 +343,11 @@ Error Commissioner::Stop(ResignMode aResignMode)
#endif
exit:
LogError("stop commissioner", error);
if (error != kErrorAlready)
{
LogWarnOnError(error, "stop commissioner");
}
return error;
}
@@ -405,7 +409,8 @@ void Commissioner::SendCommissionerSet(void)
error = SendMgmtCommissionerSetRequest(dataset, nullptr, 0);
exit:
LogError("send MGMT_COMMISSIONER_SET.req", error);
LogWarnOnError(error, "send MGMT_COMMISSIONER_SET.req");
OT_UNUSED_VARIABLE(error);
}
void Commissioner::ClearJoiners(void)
@@ -857,7 +862,7 @@ void Commissioner::SendKeepAlive(uint16_t aSessionId)
exit:
FreeMessageOnError(message, error);
LogError("send keep alive", error);
LogWarnOnError(error, "send keep alive");
}
void Commissioner::HandleLeaderKeepAliveResponse(void *aContext,
+5 -1
View File
@@ -292,7 +292,11 @@ exit:
OT_FALL_THROUGH;
default:
LogError("send Dataset set to leader", error);
if (error != kErrorAlready)
{
LogWarnOnError(error, "send Dataset set to leader");
}
FreeMessage(message);
break;
}
+3 -3
View File
@@ -185,7 +185,7 @@ exit:
FreeJoinerFinalizeMessage();
}
LogError("start joiner", error);
LogWarnOnError(error, "start joiner");
return error;
}
@@ -378,7 +378,7 @@ Error Joiner::Connect(JoinerRouter &aRouter)
SetState(kStateConnect);
exit:
LogError("start secure joiner connection", error);
LogWarnOnError(error, "start secure joiner connection");
return error;
}
@@ -543,7 +543,7 @@ template <> void Joiner::HandleTmf<kUriJoinerEntrust>(Coap::Message &aMessage, c
mTimer.Start(kConfigExtAddressDelay);
exit:
LogError("process joiner entrust", error);
LogWarnOnError(error, "process joiner entrust");
}
void Joiner::SendJoinerEntrustResponse(const Coap::Message &aRequest, const Ip6::MessageInfo &aRequestInfo)
+1 -1
View File
@@ -232,7 +232,7 @@ void JoinerRouter::DelaySendingJoinerEntrust(const Ip6::MessageInfo &aMessageInf
exit:
FreeMessageOnError(message, error);
LogError("schedule joiner entrust", error);
LogWarnOnError(error, "schedule joiner entrust");
}
void JoinerRouter::HandleTimer(void) { SendDelayedJoinerEntrust(); }
-10
View File
@@ -343,15 +343,5 @@ exit:
}
#endif // OPENTHREAD_FTD
#if OT_SHOULD_LOG_AT(OT_LOG_LEVEL_WARN)
void LogError(const char *aActionText, Error aError)
{
if (aError != kErrorNone && aError != kErrorAlready)
{
LogWarn("Failed to %s: %s", aActionText, ErrorToString(aError));
}
}
#endif
} // namespace MeshCoP
} // namespace ot
-16
View File
@@ -561,22 +561,6 @@ Error GeneratePskc(const char *aPassPhrase,
*/
void ComputeJoinerId(const Mac::ExtAddress &aEui64, Mac::ExtAddress &aJoinerId);
#if OT_SHOULD_LOG_AT(OT_LOG_LEVEL_WARN)
/**
* Emits a log message indicating an error during a MeshCoP action.
*
* Note that log message is emitted only if there is an error, i.e. @p aError is not `kErrorNone`. The log
* message will have the format "Failed to {aActionText} : {ErrorString}".
*
* @param[in] aActionText A string representing the failed action.
* @param[in] aError The error in sending the message.
*
*/
void LogError(const char *aActionText, Error aError);
#else
inline void LogError(const char *, Error) {}
#endif
} // namespace MeshCoP
DefineCoreType(otJoinerPskd, MeshCoP::JoinerPskd);
+3 -3
View File
@@ -125,7 +125,7 @@ void Leader::SendPetitionResponse(const Coap::Message &aRequest,
exit:
FreeMessageOnError(message, error);
LogError("send petition response", error);
LogWarnOnError(error, "send petition response");
}
template <> void Leader::HandleTmf<kUriLeaderKeepAlive>(Coap::Message &aMessage, const Ip6::MessageInfo &aMessageInfo)
@@ -192,7 +192,7 @@ void Leader::SendKeepAliveResponse(const Coap::Message &aRequest,
exit:
FreeMessageOnError(message, error);
LogError("send keep alive response", error);
LogWarnOnError(error, "send keep alive response");
}
void Leader::SendDatasetChanged(const Ip6::Address &aAddress)
@@ -211,7 +211,7 @@ void Leader::SendDatasetChanged(const Ip6::Address &aAddress)
exit:
FreeMessageOnError(message, error);
LogError("send dataset changed", error);
LogWarnOnError(error, "send dataset changed");
}
Error Leader::SetDelayTimerMinimal(uint32_t aDelayTimerMinimal)
+1 -11
View File
@@ -94,7 +94,7 @@ Error TcatAgent::Start(const TcatAgent::VendorInfo &aVendorInfo,
mAlreadyCommissioned = false;
exit:
LogError("start TCAT agent", error);
LogWarnOnError(error, "start TCAT agent");
return error;
}
@@ -500,16 +500,6 @@ exit:
return error;
}
#if OT_SHOULD_LOG_AT(OT_LOG_LEVEL_WARN)
void TcatAgent::LogError(const char *aActionText, Error aError)
{
if (aError != kErrorNone)
{
LogWarn("Failed to %s: %s", aActionText, ErrorToString(aError));
}
}
#endif
} // namespace MeshCoP
} // namespace ot
-6
View File
@@ -325,12 +325,6 @@ private:
Error HandleSetActiveOperationalDataset(const Message &aIncommingMessage, uint16_t aOffset, uint16_t aLength);
Error HandleStartThreadInterface(void);
#if OT_SHOULD_LOG_AT(OT_LOG_LEVEL_WARN)
void LogError(const char *aActionText, Error aError);
#else
void LogError(const char *, Error) {}
#endif
bool CheckCommandClassAuthorizationFlags(CommandClassFlags aCommissionerCommandClassFlags,
CommandClassFlags aDeviceCommandClassFlags,
Dataset *aDataset) const;
+1 -1
View File
@@ -288,7 +288,7 @@ exit:
if (error != kErrorNone)
{
FreeMessage(message);
LogWarn("Failed to send DHCPv6 Solicit: %s", ErrorToString(error));
LogWarnOnError(error, "send DHCPv6 Solicit");
}
}
+2 -5
View File
@@ -172,11 +172,8 @@ void Server::AddPrefixAgent(const Ip6::Prefix &aIp6Prefix, const Lowpan::Context
mPrefixAgentsCount++;
exit:
if (error != kErrorNone)
{
LogNote("Failed to add DHCPv6 prefix agent: %s", ErrorToString(error));
}
LogWarnOnError(error, "add DHCPv6 prefix agent");
OT_UNUSED_VARIABLE(error);
}
void Server::HandleUdpReceive(void *aContext, otMessage *aMessage, const otMessageInfo *aMessageInfo)
+1 -1
View File
@@ -170,7 +170,7 @@ void Server::ProcessQuery(Request &aRequest)
ExitNow();
}
LogWarn("Error forwarding to upstream: %s", ErrorToString(error));
LogWarnOnError(error, "forwarding to upstream");
rcode = Header::kResponseServerFailure;
+4 -11
View File
@@ -714,7 +714,7 @@ exit:
mReassemblyList.DequeueAndFree(*message);
}
LogWarn("Reassembly failed: %s", ErrorToString(error));
LogWarnOnError(error, "reassemble");
}
if (isFragmented)
@@ -769,11 +769,8 @@ void Ip6::SendIcmpError(Message &aMessage, Icmp::Header::Type aIcmpType, Icmp::H
error = mIcmp.SendError(aIcmpType, aIcmpCode, messageInfo, aMessage);
exit:
if (error != kErrorNone)
{
LogWarn("Failed to send ICMP error: %s", ErrorToString(error));
}
LogWarnOnError(error, "send ICMP");
OT_UNUSED_VARIABLE(error);
}
#else
@@ -916,11 +913,7 @@ Error Ip6::HandlePayload(Header &aIp6Header,
}
exit:
if (error != kErrorNone)
{
LogNote("Failed to handle payload: %s", ErrorToString(error));
}
LogWarnOnError(error, "handle payload");
return error;
}
+1 -1
View File
@@ -193,7 +193,7 @@ exit:
if (error != kErrorNone)
{
FreeMessage(messageCopy);
LogWarn("Failed to send SNTP request: %s", ErrorToString(error));
LogWarnOnError(error, "send SNTP request");
}
}
+12 -21
View File
@@ -674,7 +674,7 @@ Error Server::PrepareSocket(void)
exit:
if (error != kErrorNone)
{
LogError("prepare socket", error);
LogWarnOnError(error, "prepare socket");
IgnoreError(mSocket.Close());
Stop();
}
@@ -872,7 +872,7 @@ Error Server::ProcessZoneSection(const Message &aMessage, MessageMetadata &aMeta
aMetadata.mOffset = offset;
exit:
LogError("process DNS Zone section", error);
LogWarnOnError(error, "process DNS Zone section");
return error;
}
@@ -898,7 +898,7 @@ Error Server::ProcessUpdateSection(Host &aHost, const Message &aMessage, Message
VerifyOrExit(!HasNameConflictsWith(aHost), error = kErrorDuplicated);
exit:
LogError("Process DNS Update section", error);
LogWarnOnError(error, "Process DNS Update section");
return error;
}
@@ -987,7 +987,7 @@ Error Server::ProcessHostDescriptionInstruction(Host &aHost,
// the host is being removed or registered.
exit:
LogError("process Host Description instructions", error);
LogWarnOnError(error, "process Host Description instructions");
return error;
}
@@ -1106,7 +1106,7 @@ Error Server::ProcessServiceDiscoveryInstructions(Host &aHost,
}
exit:
LogError("process Service Discovery instructions", error);
LogWarnOnError(error, "process Service Discovery instructions");
return error;
}
@@ -1205,7 +1205,7 @@ Error Server::ProcessServiceDescriptionInstructions(Host &aHost,
aMetadata.mOffset = offset;
exit:
LogError("process Service Description instructions", error);
LogWarnOnError(error, "process Service Description instructions");
return error;
}
@@ -1294,7 +1294,7 @@ Error Server::ProcessAdditionalSection(Host *aHost, const Message &aMessage, Mes
aMetadata.mOffset = offset;
exit:
LogError("process DNS Additional section", error);
LogWarnOnError(error, "process DNS Additional section");
return error;
}
@@ -1341,7 +1341,7 @@ Error Server::VerifySignature(const Host::Key &aKey,
error = aKey.Verify(hash, signature);
exit:
LogError("verify message signature", error);
LogWarnOnError(error, "verify message signature");
FreeMessage(signerNameMessage);
return error;
}
@@ -1501,7 +1501,7 @@ void Server::SendResponse(const Dns::UpdateHeader &aHeader,
UpdateResponseCounters(aResponseCode);
exit:
LogError("send response", error);
LogWarnOnError(error, "send response");
FreeMessageOnError(response, error);
}
@@ -1557,7 +1557,7 @@ void Server::SendResponse(const Dns::UpdateHeader &aHeader,
UpdateResponseCounters(Dns::UpdateHeader::kResponseSuccess);
exit:
LogError("send response", error);
LogWarnOnError(error, "send response");
FreeMessageOnError(response, error);
}
@@ -1570,7 +1570,8 @@ void Server::HandleUdpReceive(Message &aMessage, const Ip6::MessageInfo &aMessag
{
Error error = ProcessMessage(aMessage, aMessageInfo);
LogError("handle DNS message", error);
LogWarnOnError(error, "handle DNS message");
OT_UNUSED_VARIABLE(error);
}
Error Server::ProcessMessage(Message &aMessage, const Ip6::MessageInfo &aMessageInfo)
@@ -1813,16 +1814,6 @@ exit:
}
#endif
#if OT_SHOULD_LOG_AT(OT_LOG_LEVEL_WARN)
void Server::LogError(const char *aActionText, Error aError)
{
if (aError != kErrorNone)
{
LogWarn("Failed to %s: %s", aActionText, ErrorToString(aError));
}
}
#endif
//---------------------------------------------------------------------------------------------------------------------
// Server::Service
-6
View File
@@ -1047,12 +1047,6 @@ private:
void UpdateResponseCounters(Dns::Header::Response aResponseCode);
void UpdateAddrResolverCacheTable(const Ip6::MessageInfo &aMessageInfo, const Host &aHost);
#if OT_SHOULD_LOG_AT(OT_LOG_LEVEL_WARN)
static void LogError(const char *aActionText, Error aError);
#else
static void LogError(const char *, Error) {}
#endif
using LeaseTimer = TimerMilliIn<Server, &Server::HandleLeaseTimer>;
using UpdateTimer = TimerMilliIn<Server, &Server::HandleOutstandingUpdatesTimer>;
using CompletedUpdatesTask = TaskletIn<Server, &Server::ProcessCompletedUpdates>;
+2 -2
View File
@@ -158,7 +158,7 @@ Error DuaManager::GenerateDomainUnicastAddressIid(void)
}
else
{
LogWarn("Generate DUA: %s", ErrorToString(error));
LogWarnOnError(error, "generate DUA");
}
return error;
@@ -548,7 +548,7 @@ exit:
UpdateCheckDelay(kNoBufDelay);
}
LogInfo("PerformNextRegistration: %s", ErrorToString(error));
LogWarnOnError(error, "perform next registration");
FreeMessageOnError(message, error);
}
+1 -1
View File
@@ -198,7 +198,7 @@ void EnergyScanServer::SendReport(void)
exit:
FreeMessageOnError(mReportMessage, error);
MeshCoP::LogError("send scan results", error);
LogWarnOnError(error, "send scan results");
mReportMessage = nullptr;
}
+2 -7
View File
@@ -3908,13 +3908,8 @@ void Mle::InformPreviousParent(void)
LogNote("Sending message to inform previous parent 0x%04x", mPreviousParentRloc);
exit:
if (error != kErrorNone)
{
LogWarn("Failed to inform previous parent: %s", ErrorToString(error));
FreeMessage(message);
}
LogWarnOnError(error, "inform previous parent");
FreeMessageOnError(message, error);
}
#endif // OPENTHREAD_CONFIG_MLE_INFORM_PREVIOUS_PARENT_ON_REATTACH
+1 -4
View File
@@ -680,10 +680,7 @@ exit:
if (!mIsClone)
#endif
{
if (error != kErrorNone)
{
LogNote("Failed to register network data: %s", ErrorToString(error));
}
LogWarnOnError(error, "register network data");
}
}
+1 -1
View File
@@ -124,7 +124,7 @@ void PanIdQueryServer::SendConflict(void)
exit:
FreeMessageOnError(message, error);
MeshCoP::LogError("send panid conflict", error);
LogWarnOnError(error, "send panid conflict");
}
void PanIdQueryServer::HandleTimer(void)
+3 -6
View File
@@ -387,14 +387,11 @@ Error ChannelManager::RequestChannelSelect(bool aSkipQualityCheck)
LogInfo("Occupancy rate diff too small to change channel");
ExitNow(error = kErrorAbort);
}
mChannelSelected = newChannel;
exit:
if (error != kErrorNone)
{
LogInfo("Request to select better channel failed, error: %s", ErrorToString(error));
}
LogWarnOnError(error, "select better channel");
return error;
}
#endif // OPENTHREAD_CONFIG_CHANNEL_MONITOR_ENABLE
+4 -12
View File
@@ -166,11 +166,9 @@ void Otns::EmitCoapSend(const Coap::Message &aMessage, const Ip6::MessageInfo &a
EmitStatus("coap=send,%d,%d,%d,%s,%s,%d", aMessage.GetMessageId(), aMessage.GetType(), aMessage.GetCode(), uriPath,
aMessageInfo.GetPeerAddr().ToString().AsCString(), aMessageInfo.GetPeerPort());
exit:
if (error != kErrorNone)
{
LogWarn("EmitCoapSend failed: %s", ErrorToString(error));
}
LogWarnOnError(error, "EmitCoapSend");
}
void Otns::EmitCoapReceive(const Coap::Message &aMessage, const Ip6::MessageInfo &aMessageInfo)
@@ -183,10 +181,7 @@ void Otns::EmitCoapReceive(const Coap::Message &aMessage, const Ip6::MessageInfo
EmitStatus("coap=recv,%d,%d,%d,%s,%s,%d", aMessage.GetMessageId(), aMessage.GetType(), aMessage.GetCode(), uriPath,
aMessageInfo.GetPeerAddr().ToString().AsCString(), aMessageInfo.GetPeerPort());
exit:
if (error != kErrorNone)
{
LogWarn("EmitCoapReceive failed: %s", ErrorToString(error));
}
LogWarnOnError(error, "EmitCoapReceive");
}
void Otns::EmitCoapSendFailure(Error aError, Coap::Message &aMessage, const Ip6::MessageInfo &aMessageInfo)
@@ -200,10 +195,7 @@ void Otns::EmitCoapSendFailure(Error aError, Coap::Message &aMessage, const Ip6:
uriPath, aMessageInfo.GetPeerAddr().ToString().AsCString(), aMessageInfo.GetPeerPort(),
ErrorToString(aError));
exit:
if (error != kErrorNone)
{
LogWarn("EmitCoapSendFailure failed: %s", ErrorToString(error));
}
LogWarnOnError(error, "EmitCoapSendFailure");
}
} // namespace Utils