Skip to main content

Logging

Access the log view through master.logs, or globally through LogManager.instance().default_view.​

Runtime logs are written to the log view (a read-only list) by the SDK modules; lower-level logs are pushed to the caller through the set_log_callback callback. The two channels are independent. Logs that the SDK event side produces on its own go through standard Python logging (logger darra.ethercat.events); whether they are output depends on the logging configuration of the host application, and they do not come from the same source as master.logs.

Quick start​

from darra_ethercat import EtherCATMaster, LogCategory

# bind to console output
master.logs.on_updated = lambda: print(master.logs[-1]) if master.logs.count > 0 else None

# show errors and warnings only
master.logs.set_filter(LogCategory.ERROR, LogCategory.WARNING)

# enable debug logging (off by default)
EtherCATMaster.set_debug_logging(True)

Log categories​

from enum import IntEnum

class LogCategory(IntEnum):
ERROR = 0 # system errors and exceptions
WARNING = 1 # potential problems
MESSAGE = 2 # general information (state transitions and so on)
MAILBOX = 3 # CoE/SoE/FoE/EoE mailbox communication (off by default)
PDO = 4 # PDO data change log (off by default)
DEBUG = 5 # detailed debug information (off by default)
LOCAL = 6 # console output capture

The view filters to ERROR, WARNING and MESSAGE by default; MAILBOX, PDO, DEBUG and LOCAL appear only when explicitly added to the filter.

Properties​

CategoryProperty/MethodTypeR/WDescription
Viewmaster.logsLogViewread-onlyReal-time log view (equivalent to LogManager.instance().default_view)
on_updatedOptional[Callable[[], None]]read-writeData change callback (a function with no arguments); fires on add / clear / filter change
countintread-onlyNumber of log entries after filtering
retainboolread-writeWhether to keep all logs (default False)
set_filter(*categories)Nonewrite-onlySet the category filter; only the given categories are shown
get_all()List[LogEntry]read-onlyGet every log entry (ignores the filter)
logs[i] / iterationLogEntryread-onlyIndex access / iteration (both on the filtered view)
Callbackmaster.set_log_callback(callback)Nonewrite-onlyRegister the lower-level log callback (category, message); pass None to clear
master.set_crash_callback(callback)Nonewrite-onlyRegister the crash notification callback (severity, message); pass None to clear

master.logs​

@property
def logs(self) -> LogView

Real-time log view (a read-only list).

LogEntry data class:

@dataclass
class LogEntry:
timestamp: datetime # log timestamp
category: LogCategory # log category
message: str # log message text

on_updated​

master.logs.on_updated = callback   # callback() takes no arguments and returns None

Fires when the log data changes (add / clear / filter change).

Capacity and retention policy

The log list holds at most 10000 entries; beyond that the 2000 oldest entries are removed automatically.

Retention policy: master.logs.retain defaults to False — when LogManager.instance().begin_operation() enters the outermost operation the old logs are cleared automatically and only the logs of the current operation are kept; with retain = True they accumulate and are not cleared at operation boundaries. Mark the boundaries with begin_operation() / end_operation().

PDO logging

PDO logs are emitted only when the PDO data changes, so not every cycle produces a log entry. Useful for debugging PDO mapping problems.

Filtering​

set_filter()​

def set_filter(self, *categories: LogCategory) -> None

Set the filter so that only logs of the given categories are shown.

Example:

# show errors and warnings only
master.logs.set_filter(LogCategory.ERROR, LogCategory.WARNING)

# switch to mailbox communication only
master.logs.set_filter(LogCategory.MAILBOX)

get_all()​

def get_all(self) -> List[LogEntry]

Get every log entry (ignores the filter).

Log callbacks​

set_log_callback()​

def set_log_callback(self, callback: Optional[Callable[[int, str], None]]) -> None

Register the lower-level log callback (process-wide). The callback receives (category, message) — category is a LogCategory value (int) and message is the log text. Multiple masters do not overwrite each other: calling it again replaces only the callback this instance registered last time, and passing None clears it.

set_crash_callback()​

def set_crash_callback(self, callback: Optional[Callable[[int, str], None]]) -> None

Register the crash notification callback (process-wide). The callback receives (severity, message); pass None to clear this instance's registration.

Log switches​

The Mailbox, PDO and Debug log categories are off by default; enable them manually when needed.

EtherCATMaster.set_pdo_logging(True)
EtherCATMaster.set_mailbox_logging(True)
EtherCATMaster.set_debug_logging(True)

Log switch details​

set_pdo_logging()​

EtherCATMaster.set_pdo_logging(enable: bool) -> None

Enable PDO logging. Output only when the PDO data changes; it affects real-time performance, so use it with care.

set_mailbox_logging()​

EtherCATMaster.set_mailbox_logging(enable: bool) -> None

Enable mailbox logging (CoE/SoE/FoE/EoE mailbox communication logs).

set_debug_logging()​

EtherCATMaster.set_debug_logging(enable: bool) -> None

Enable debug logging (detailed debug information).

events.log persistence​

A persistent copy beyond the in-memory log view: once enabled, the logs that pass the filter are appended to events.log by a background thread. All four entry points are module-level functions.

Persistence behaviour
  • The caller (including the log callback thread) only enqueues; all disk I/O happens on a background thread and does not slow down the real-time path.
  • The queue is bounded (20000 entries); when the enqueue rate exceeds the write rate for a long time (for example when the file is not writable), the oldest entries are dropped and one line with the accumulated drop count is written to the file.
  • A write failure does not stop the background thread: the bad handle is closed and the next batch is retried; the first failure prints a warning on standard error and raises no exception.
  • The file is append-only; the line format is [时:分:秒.毫秒] [类别] 内容, and each initialization writes an extra session separator line.
  • Persistence does not change the semantics of the in-memory view: entries are kept in memory as usual, and the file is only a side copy.

init_events_log()​

from darra_ethercat import init_events_log

def init_events_log(path: Optional[str] = None) -> Optional[str]

Initializes events.log persistence (idempotent).

Parameters:

  • path (str, optional) — target file path; when omitted, events.log in the current working directory of the process is used

Returns:

  • Optional[str] — the absolute path of the file on success; None on failure (the reason is available from events_log_init_error()); a failure only warns and raises no exception
Constraints
  • When already open, repeated calls return the current path and the new path is ignored; to change the target, call close_events_log() first and initialize again.
  • Initialization writes the session separator line synchronously, so the file exists by the time the call returns.
  • On normal process exit the queue is drained and the file is closed automatically.
  • The content written passes the same filter as the in-memory view: DEBUG is not persisted in optimized runs (python -O), and PDO / MAILBOX require the corresponding log switch to be enabled first.

Example:

from darra_ethercat import init_events_log, events_log_path

path = init_events_log()
if path is None:
print("events.log 打开失败") # Failed to open events.log
else:
print(f"日志落点: {events_log_path()}") # Log location: {events_log_path()}

close_events_log()​

from darra_ethercat import close_events_log

def close_events_log() -> None

Drains the queue, closes the file and stops the background thread (idempotent). Waiting for the background thread to converge takes at most about 5 seconds. After closing, logs are no longer written to the file and the in-memory view is unaffected; call init_events_log() again to resume persistence.

Example:

from darra_ethercat import close_events_log

close_events_log() # safe to call repeatedly

events_log_path()​

from darra_ethercat import events_log_path

def events_log_path() -> Optional[str]

The absolute path of the current target file.

Returns:

  • Optional[str] — the absolute path when initialized; None when not initialized

Example:

from darra_ethercat import events_log_path

print(events_log_path() or "未开启 events.log 落盘") # events.log write-to-disk is not enabled

events_log_init_error()​

from darra_ethercat import events_log_init_error

def events_log_init_error() -> Optional[str]

The failure reason of the most recent init_events_log() (exception type + message).

Returns:

  • Optional[str] — the reason text when the most recent initialization failed; None on success or when it has not been called yet

Example:

from darra_ethercat import init_events_log, events_log_init_error

if init_events_log("D:/logs/events.log") is None:
print(f"落盘不可用: {events_log_init_error()}") # Write-to-disk unavailable: {events_log_init_error()}

Full example​

from darra_ethercat import EtherCATMaster, LogCategory

# 1. bind the console output
master.logs.on_updated = lambda: print(master.logs[-1]) if master.logs.count > 0 else None

# 2. enable debug logging
EtherCATMaster.set_debug_logging(True)
EtherCATMaster.set_mailbox_logging(True)

# 3. filter the logs
master.logs.set_filter(LogCategory.ERROR, LogCategory.DEBUG)

# 4. export all logs (ignores the filter)
all_logs = master.logs.get_all()
with open("debug.log", "w", encoding="utf-8") as f:
for entry in all_logs:
f.write(f"{entry}\n")
tkinter / PyQt binding

on_updated fires on a non-UI thread, so updating the UI needs synchronization:

# tkinter
master.logs.on_updated = lambda: root.after(0, lambda: listbox.insert("end", str(master.logs[-1])))

# PyQt
from PyQt5.QtCore import QMetaObject, Qt, Q_ARG
master.logs.on_updated = lambda: QMetaObject.invokeMethod(
widget, "append_log", Qt.QueuedConnection, Q_ARG(str, str(master.logs[-1])))