Logging
Logs are managed through the darra::ethercat::LogManager singleton (logging/logging.hpp). Register a callback with LogManager::Instance().SetLogCallback(...).
MasterEvents has no LogEvent event field. The log callback, the levels and the buffer queries are all provided by the darra::ethercat::LogManager singleton. The events on master.Events() are business events such as OnError() / OnWarning(), a different concept from the general log stream.
Quick start
using namespace darra;
using namespace darra::ethercat;
EtherCATMaster master(dll);
master.SetNetwork("\\Device\\NPF_{...}");
master.Build();
// Log callback (simple form: category + message string)
LogManager::Instance().SetLogCallback([](int category, const char* msg) {
printf("[%d] %s\n", category, msg);
});
// Enable debug logging (off by default)
LogManager::Instance().SetDebugLogging(true);
// Record the minimum log level preference (GetLogLevel can read it back)
LogManager::Instance().SetLogLevel(LogCategory::Warning);
Log categories
LogCategory is an enum class defined in data/types.hpp:
enum class LogCategory : int {
Error = 0, // System errors and exceptions
Warning = 1, // Potential problem
Message = 2, // General information (state transitions and the like)
Mailbox = 3, // CoE/SoE/FoE/EoE mailbox communication (off by default)
PDO = 4, // PDO data change log (off by default)
Debug = 5, // Verbose debug information (off by default)
Local = 6 // Console output capture
};
| Value | Enumerator | Description | Default state |
|---|---|---|---|
| 0 | LogCategory::Error | System errors and exceptions | Enabled |
| 1 | LogCategory::Warning | Potential problems | Enabled |
| 2 | LogCategory::Message | General information (state changes and so on) | Enabled |
| 3 | LogCategory::Mailbox | CoE/SoE/FoE/EoE mailbox communication | Disabled (SetMailboxLogging) |
| 4 | LogCategory::PDO | PDO data change log | Disabled (SetPDOLogging) |
| 5 | LogCategory::Debug | Detailed debug information | Disabled (SetDebugLogging) |
| 6 | LogCategory::Local | Console output capture | Enabled |
PDO logging is emitted only when the PDO data changes, not on every cycle. It suits debugging PDO mapping problems.
The log list has an upper bound (10000 entries by default, adjustable with SetMaxLogCount()); when it is exceeded the oldest entries are removed automatically. Apart from an explicit call to ClearLogs(), LogManager has no other clearing entry point.
Log switches
PDO, Debug and Mailbox logging are all off by default; turn them on explicitly with the switch methods on the LogManager singleton when needed.
auto& mgr = LogManager::Instance();
// Enable PDO logging (only outputs when PDO data changes; affects real-time performance, use with care)
mgr.SetPDOLogging(true);
// Enable/disable mailbox logging (CoE/SoE/FoE/EoE mailbox communication log, off by default)
mgr.SetMailboxLogging(true);
// Enable debug logging (verbose debug information)
mgr.SetDebugLogging(true);
// Query the switch state
bool pdoOn = mgr.IsPDOLoggingEnabled();
Level filtering
SetLogLevel()
void LogManager::SetLogLevel(LogCategory level);
LogCategory LogManager::GetLogLevel() const;
Sets the minimum log level preference, which can be read back with GetLogLevel(). The 2.11.0 LogManager only selects logs by the PDO / Mailbox / Debug category switches; AddLog does not drop entries automatically by that level; to filter by level use GetLogsByCategory() below.
Example:
// Log level preference (store/read-back only)
LogManager::Instance().SetLogLevel(LogCategory::Warning);
Log query
// Get the last N entries (count=0 returns everything)
std::vector<LogEntry> GetRecentLogs(size_t count = 0) const;
// Filter by category
std::vector<LogEntry> GetLogsByCategory(const std::vector<LogCategory>& categories) const;
// Total log count / clear / capacity limit
size_t GetLogCount() const;
void ClearLogs();
void SetMaxLogCount(size_t count);
Example:
auto& mgr = LogManager::Instance();
// Take the last 100 entries
auto recent = mgr.GetRecentLogs(100);
// Errors and warnings only
auto errs = mgr.GetLogsByCategory({LogCategory::Error, LogCategory::Warning});
for (auto& e : errs)
printf("[%s] %s\n", e.category_str(), e.message.c_str());
LogEntry structure:
struct LogEntry {
int64_t timestamp_ms; // Timestamp (milliseconds since program start)
LogCategory category; // Log category
std::string message; // Log message content
int slave_index; // Associated slave index (-1 means a master-level log)
const char* category_str() const; // Category string
};
Thread safety
The log callback is fired on a non-UI thread. To access shared resources inside the callback, use a mutex:
#include <mutex>
#include <fstream>
std::ofstream log_file("ethercat.log");
std::mutex log_mutex;
LogManager::Instance().SetLogCallback([&](int category, const char* msg) {
std::lock_guard<std::mutex> lock(log_mutex);
log_file << "[" << category << "] " << msg << std::endl;
});
Full example
#include "ethercat.hpp"
#include <cstdio>
#include <mutex>
#include <fstream>
using namespace darra;
int main() {
using namespace darra::ethercat;
// 1. Enable debug and mailbox logging (LogManager singleton)
LogManager::Instance().SetDebugLogging(true);
LogManager::Instance().SetMailboxLogging(true);
try {
EtherCATMaster master(dll);
master.SetNetwork("\\Device\\NPF_{...}");
master.Build();
// 2. Log callback (streams all logs in real time)
LogManager::Instance().SetLogCallback([](int category, const char* msg) {
const char* labels[] = {"ERROR", "WARN", "MSG", "MBOX", "PDO", "DBG", "LOCAL"};
const char* label = (category >= 0 && category <= 6) ? labels[category] : "?";
printf("[%s] %s\n", label, msg);
});
// 3. Event-driven state monitoring (register with On*())
master.Events().OnSlaveStateChanged([](uint16_t mi, uint16_t si,
EcState o, EcState n) {
printf("[状态] 从站 %d: %s -> %s\n", si, // [State] slave %d: %s -> %s\n
EcStateFormat::Format(o).c_str(),
EcStateFormat::Format(n).c_str());
});
master.Events().OnEmergency([](uint16_t mi, uint16_t si,
uint16_t code, uint16_t reg,
uint8_t b1, uint16_t w1, uint16_t w2) {
printf("[紧急] 从站 %d: 0x%04X\n", si, code); // [Emergency] slave %d: 0x%04X\n
});
master.SetState(EcState::OP);
master.Start();
printf("运行中... 按 Enter 停止\n"); // Running... press Enter to stop
getchar();
} catch (const ethercat::DarraException& e) {
printf("错误: %s\n", e.what()); // Error: %s
return -1;
}
return 0;
}
The log callback is fired on a non-UI thread. When updating controls in UI frameworks such as Qt or MFC, synchronize to the UI thread through a message queue or signal-slot:
// Qt example
LogManager::Instance().SetLogCallback([this](int cat, const char* msg) {
QString text = QString("[%1] %2").arg(cat).arg(msg);
QMetaObject::invokeMethod(this, [=]() {
ui->logList->addItem(text);
}, Qt::QueuedConnection);
});