CAN log analysis converts recorded frames into time-based engineering evidence. It helps engineers investigate message timing, identify unexpected traffic, compare ECU behavior across software versions and support repeatable test reporting.
Reliable conclusions depend on more than parsing a file. Timestamp semantics, channel mapping, frame format, DBC revision, signal scaling, logger behavior and capture completeness must all be understood. Preserve the original trace and record the analysis configuration so that results can be reproduced.
Scope: Identifiers, cycle times and payloads in this article are illustrative. Use approved network specifications and authorized test environments for real ECU or vehicle work.
1. What CAN log analysis should answer
A useful analysis pipeline should answer questions such as:
- Which frames were observed, on which channel and in what order?
- How frequently did each message appear?
- Were there unusually long inter-arrival gaps or bursts?
- Did payload values, counters or checksums behave as expected?
- Can raw bytes be decoded using the correct DBC revision?
- Does the evidence indicate a network issue, a logger issue or an application-level issue?
Keep raw observations separate from derived results. A decoded signal value is an interpretation based on a database; it should never replace the original frame data in the evidence archive.
2. Analysis architecture
A practical pipeline has the following stages:
- Input identification: Determine file format, logger, capture version and available metadata.
- Reader configuration: Select a reader that supports the actual format and installed library version.
- Normalization: Establish timestamp units, time origin, channel identity and ordering.
- Frame inspection: Separate standard and extended identifiers; inspect payload length and CAN FD/error-frame attributes.
- Timing analysis: Calculate inter-arrival intervals for a clearly defined message group.
- Signal decoding: Apply the matching DBC or approved database revision.
- Anomaly review: Compare observations with project-defined expectations and capture limitations.
- Reporting: Generate plots, summary statistics and trace references while retaining the raw source.
3. Reading CAN log files with python-can
The python-can package provides log readers for supported file formats. The exact supported formats and reader behavior depend on the installed version. BLF and ASC are common automotive trace formats; CSV files are not a single standardized CAN-log format, so their column layout and timestamp semantics must be defined by the producer.
Example using the generic LogReader interface:
import can
log_path = "capture.blf"
for message in can.LogReader(log_path):
print(
f"t={message.timestamp:.6f} "
f"channel={message.channel} "
f"id=0x{message.arbitration_id:X} "
f"extended={message.is_extended_id} "
f"dlc={message.dlc} "
f"data={bytes(message.data).hex(' ')}"
)
This example assumes the installed python-can version has a reader for the supplied file format. Check the reader documentation and handle exceptions for unsupported formats, corrupt files and incomplete captures.
Important fields to retain include:
| Field | Why it matters |
|---|---|
| Timestamp | Establishes event order and timing intervals |
| Channel | Distinguishes traffic from different buses or interfaces |
| Arbitration ID | Identifies the CAN message, interpreted with frame format |
| Extended-ID flag | Separates standard and extended identifier spaces |
| Data bytes | Preserves the raw payload |
| DLC / payload length | Helps validate frame structure and format |
| CAN FD attributes | Distinguishes FD traffic and bit-rate-switch settings where available |
| Error-frame attributes | Helps identify reported communication errors |
Do not assume that every file reader provides identical metadata. Some formats may omit a channel, use a different time origin or represent certain frame attributes differently.
4. Timestamp normalization and data quality
Before calculating timing, establish what each timestamp represents. Depending on the logger and format, timestamps may be absolute, relative to capture start, derived from a hardware clock or generated in software.
Check:
- Whether timestamps are in seconds, milliseconds or another unit.
- Whether the first timestamp is zero or an absolute time.
- Whether the clock is monotonic and whether clock corrections are possible.
- Whether multiple channels share a synchronized clock.
- Whether records are already sorted.
- Whether the logger reports dropped frames or buffer overruns.
- Whether the trace was filtered before it was saved.
A timestamp gap is not automatically proof of a missing CAN frame. It can also result from a capture filter, logger overload, disconnected interface, file segmentation or a legitimate event-triggered message pattern.
Keep the original timestamps and document any normalization transformation. Do not silently convert or round timestamps before the raw values have been archived.
5. Calculate inter-arrival timing
For consecutive observations of the same message group, calculate the time difference:
The message group should normally include at least the channel, arbitration ID and standard/extended frame format. If the analysis combines channels or identifier formats, unrelated messages can be grouped together and produce misleading timing results.
The following example uses python-can to collect timestamps and calculate basic statistics:
from collections import defaultdict
import can
import statistics
log_path = "capture.blf"
timestamps = defaultdict(list)
for message in can.LogReader(log_path):
key = (
message.channel,
message.arbitration_id,
message.is_extended_id,
)
timestamps[key].append(message.timestamp)
for key, values in sorted(timestamps.items(), key=lambda item: str(item[0])):
values.sort()
intervals_ms = [
(current - previous) * 1000.0
for previous, current in zip(values, values[1:])
]
if not intervals_ms:
continue
print(
f"channel/ID/extended={key}: "
f"frames={len(values)}, "
f"mean={statistics.mean(intervals_ms):.3f} ms, "
f"median={statistics.median(intervals_ms):.3f} ms, "
f"max_gap={max(intervals_ms):.3f} ms"
)
The example assumes timestamps are expressed in seconds, as exposed by the relevant python-can message reader. Verify this for the selected file reader and version before using the results in a formal report.
Mean and median alone are not enough for timing validation. Also inspect the distribution, maximum gap, percentiles and number of observations. A single large gap can be important even when the average interval appears normal.
Compare against an expected cycle
Do not invent a nominal cycle time from the trace. Obtain the expected cycle and allowed tolerance from the controlled network specification, ECU requirements or approved test configuration.
For a configured expected cycle (T_e), an engineering rule might flag an interval when:
The actual rule must account for message scheduling, event-triggered behavior, gateway forwarding, operating mode and the project's acceptance criteria. A timeout threshold is not necessarily identical to the nominal message cycle.
6. Understand CAN arbitration in a trace
CAN arbitration is bitwise and non-destructive. A dominant bit (logical 0) overwrites a recessive bit (logical 1). A node that transmits recessive but observes dominant during arbitration loses arbitration and stops transmitting; the winning frame continues.
The following simplified example compares two 11-bit standard identifiers:
Arbitration bit b10 b9 b8 b7 b6 b5 b4 ...
Node A, ID 0x100 0 0 1 0 0 0 0 ...
Node B, ID 0x180 0 0 1 1 0 0 0 ...
Observed bus 0 0 1 0 0 0 0 ...
^
Node B sends recessive 1,
observes dominant 0 and stops
This is a symbolic logic-level illustration, not an oscilloscope voltage trace. It assumes both nodes begin arbitration together and use standard-format identifiers. A complete arbitration comparison includes the relevant frame-format/control bits as well as the identifier bits.
When analyzing a trace, simultaneous-looking timestamps may be affected by timestamp resolution. Do not conclude that two frames physically started at precisely the same instant unless the capture hardware and timestamp resolution support that conclusion.
7. Decode signals using the correct DBC
A CAN frame contains an identifier and payload bytes. It does not inherently contain signal names, engineering units or scaling. A DBC describes how signals are packed into messages, including properties such as start bit, length, byte order, signedness, scale, offset and value choices.
A common Python option for DBC decoding is cantools. Install it separately:
python -m pip install cantools
Example:
import can
import cantools
database = cantools.database.load_file("network.dbc")
for message in can.LogReader("capture.blf"):
try:
decoded = database.decode_message(
message.arbitration_id,
bytes(message.data),
decode_choices=False,
)
except (KeyError, ValueError):
# Message may not exist in this DBC or payload may not match.
continue
print(
f"ID=0x{message.arbitration_id:X}: "
f"{decoded}"
)
This is a basic illustration. For a production analysis tool, account for standard versus extended frame identity, message/channel mapping, multiplexed signals, CAN FD payloads and decoder exceptions. Confirm the API behavior against the installed cantools version.
A decoded value is only as reliable as the DBC revision and configuration used. Record the database filename, version or revision identifier and checksum with the report. If the DBC does not match the ECU software baseline, signal names or engineering values may be misleading.
8. Detect anomalies without overclaiming
Useful analysis checks include:
| Check | What it can reveal | Important caveat |
|---|---|---|
| Long inter-arrival gap | Delayed or absent observations | Logger drops and filters can create apparent gaps |
| Unexpected identifier | New or misconfigured traffic | Confirm channel and operating mode |
| Payload length mismatch | Format/configuration issue | Interpret according to Classical CAN or CAN FD |
| Counter discontinuity | Possible missed, duplicated or reordered observations | Counter behavior is message-specific |
| Checksum/CRC signal mismatch | Possible data-integrity issue | Use the exact OEM/project algorithm and coverage |
| Signal outside expected range | Possible sensor, decoding or state issue | Validate scaling, signedness and operating mode |
| Sudden traffic-rate change | State transition, fault or bus-load change | Compare with expected vehicle/bench activity |
A trace-analysis script should label observations as findings for investigation, not automatically as ECU defects. Correlate anomalies with ECU state, test steps, bus state, logger health and independent measurement evidence.
9. Visualize timing and traffic patterns
Plots make periodicity, bursts and outliers easier to inspect. For example, a histogram of inter-arrival intervals can show whether a message is tightly periodic or has a broad distribution.
import matplotlib.pyplot as plt
# Example values only; replace with intervals calculated from a trace.
intervals_ms = [9.9, 10.0, 10.1, 10.0, 10.2, 9.8, 10.0]
plt.hist(intervals_ms, bins=10)
plt.xlabel("Inter-arrival interval (ms)")
plt.ylabel("Number of intervals")
plt.title("CAN message timing distribution")
plt.tight_layout()
plt.show()
For larger studies, useful views include:
- Message count by arbitration ID and channel.
- Inter-arrival interval versus time.
- Histogram or percentile plot of message timing.
- Bus traffic rate over time.
- Signal values with test-step markers.
- A timeline of errors, state transitions and diagnostic events.
Always label units, message identity, channel, time window and data filters. A plot without this context can be difficult to reproduce or interpret.
10. Common implementation traps
- Mixing channels: Identical IDs on different CAN buses are not necessarily the same message stream.
- Mixing identifier formats: A standard ID and an extended ID must not be treated as identical solely because their numeric values match.
- Using the wrong DBC: Incorrect byte order, signedness, scaling or multiplexing can produce plausible but false signal values.
- Ignoring logger limitations: Capture filters, buffer overflow and dropped frames can mimic network faults.
- Relying on rounded timestamps: Low-resolution exports can hide jitter or distort short intervals.
- Discarding raw data: A filtered or decoded export is not a substitute for the original trace.
- Treating every message as periodic: Event-triggered and state-dependent messages need different expectations.
- Conflating infrastructure and ECU failures: A disconnected adapter or corrupt log is not an ECU functional failure.
11. Verification matrix
| Test area | Stimulus or condition | Evidence to capture |
|---|---|---|
| File integrity | Valid, truncated and corrupt trace files | Reader result, exceptions and file checksum |
| Timestamp handling | Relative, absolute and multi-channel timestamps | Time origin, units and ordering |
| Frame identity | Standard and extended frames, repeated IDs across channels | Correct grouping keys |
| Timing | Nominal traffic and controlled delayed/missing observations | Inter-arrival distribution and configured threshold |
| DBC decoding | Known payloads and boundary signal values | Database revision and expected decoded values |
| CAN FD | FD frames and supported payload lengths | Frame attributes and reader compatibility |
| Logger health | High traffic load or capture filter changes | Drop counters and capture configuration |
| Regression | Same trace and analysis configuration across versions | Reproducible metrics and report comparison |
12. Engineering checklist
- Original trace files are retained unchanged and checksummed.
- File format, reader version and capture tool are recorded.
- Timestamp units, origin, clock source and resolution are understood.
- Channel, arbitration ID and frame format are part of message grouping.
- Logger filters and dropped-record information are reviewed.
- Expected cycle times and tolerances come from approved project sources.
- DBC revision and decoding configuration are recorded.
- Classical CAN and CAN FD frames are handled correctly.
- Derived plots and statistics include units and analysis parameters.
- Infrastructure issues are distinguished from ECU/product failures.
13. Check your understanding
- Why should channel and standard/extended frame format be included when grouping frames for timing analysis?
- What can cause an apparent inter-arrival gap even when the ECU transmitted correctly?
- Why must the DBC revision be recorded with decoded signal results?
- What is the difference between a nominal message cycle and a project-defined timeout threshold?
- Why should the original raw trace be retained after filtering and decoding?
Related articles
- Python-CAN: A Practical Automotive Engineering Guide
- Python for CAN Communication
- Python ECU Test Automation
- CAPL Test Automation
