mqtt: log mosquitto_publish() failures with rate-limited cerr
Publish failures (invalid topic, offline broker, queue full) were silent because the rc was discarded. At production volume a naive log floods on any flap, so emit on first failure + error-code change, then suppress for 60s and include the suppressed count on the next line.
This commit is contained in:
1 parent
bd196d6365
commit
bc02c8c6d8
2 files changed
+35
-1
No files matched your search
@@ -197,9 +197,38 @@ void MqttPublisher::publish(const std::string& topic_suffix,
|
||||
return;
|
||||
}
|
||||
string topic = m_topic_prefix + "/" + topic_suffix;
|
||||
mosquitto_publish(m_mosq, nullptr, topic.c_str(),
|
||||
int rc = mosquitto_publish(m_mosq, nullptr, topic.c_str(),
|
||||
static_cast<int>(payload.size()), payload.c_str(),
|
||||
0, retain);
|
||||
if (rc == MOSQ_ERR_SUCCESS)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Rate-limit: log first failure, log on error-code change, otherwise
|
||||
// suppress for 60s. Include suppressed count when we do log.
|
||||
const time_t now = time(nullptr);
|
||||
const bool first = (m_last_pub_err_logged == 0);
|
||||
const bool code_changed = (rc != m_last_pub_err_code);
|
||||
const bool cooldown_ok = (now - m_last_pub_err_logged >= 60);
|
||||
|
||||
if (first || code_changed || cooldown_ok)
|
||||
{
|
||||
cerr << "*** WARNING: MQTT publish failed: topic=" << topic
|
||||
<< " rc=" << rc << " (" << mosquitto_strerror(rc) << ")";
|
||||
if (m_pub_err_suppressed > 0)
|
||||
{
|
||||
cerr << " [suppressed " << m_pub_err_suppressed << " prior]";
|
||||
}
|
||||
cerr << endl;
|
||||
m_last_pub_err_code = rc;
|
||||
m_last_pub_err_logged = now;
|
||||
m_pub_err_suppressed = 0;
|
||||
}
|
||||
else
|
||||
{
|
||||
++m_pub_err_suppressed;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
|
||||
#include <string>
|
||||
#include <cstdint>
|
||||
#include <ctime>
|
||||
#include <vector>
|
||||
#include <json/json.h>
|
||||
#include "ReflectorMsg.h"
|
||||
@@ -61,6 +62,10 @@ class MqttPublisher
|
||||
std::string m_tls_client_cert;
|
||||
std::string m_tls_client_key;
|
||||
|
||||
int m_last_pub_err_code = 0;
|
||||
time_t m_last_pub_err_logged = 0;
|
||||
uint64_t m_pub_err_suppressed = 0;
|
||||
|
||||
void publish(const std::string& topic_suffix, const std::string& payload,
|
||||
bool retain = false);
|
||||
|
||||
|
||||
Reference in new issue
Block a user