Merge Sorted Python Log Streams with heapq.merge

Two workers write separate logs in timestamp order. A report needs one chronological timeline, but loading and sorting every record would hold the entire report in memory. Python’s heapq.merge() combines already sorted iterables and returns an iterator that the report can consume incrementally.

The examples use integer timestamps in the same units and dictionaries for records. They run on Python 3.10 or later using only the standard library.

Merge Records by Timestamp

Save this helper as merge_logs.py.

1
2
3
4
5
6
from heapq import merge
from operator import itemgetter


def merge_logs(*streams):
    return merge(*streams, key=itemgetter("timestamp_ms"))

Every input must already be sorted in nondecreasing order by timestamp_ms. The key selects the numeric timestamp so Python does not need to compare the dictionaries themselves. The merge keeps duplicate records; it does not deduplicate log entries. Python heapq.merge documentation

Save this as show_merge.py beside the helper and run python show_merge.py.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
from merge_logs import merge_logs

worker_a = [
    {"timestamp_ms": 100, "message": "a opened"},
    {"timestamp_ms": 300, "message": "a closed"},
]
worker_b = [
    {"timestamp_ms": 200, "message": "b opened"},
    {"timestamp_ms": 300, "message": "b closed"},
]

print([record["timestamp_ms"] for record in merge_logs(worker_a, worker_b)])
# [100, 200, 300, 300]

Equal timestamps remain in the result. This report only requires timestamp ordering. If records need a unique order across machines, define a shared secondary key such as (timestamp_ms, worker_id, sequence) and sort every source by that same complete key before merging.

Read JSON Lines While Files Stay Open

For UTF-8 JSON Lines logs, decode one record per line and consume the merged iterator inside the file contexts. Save this as merge_files.py beside the helper. Each nonblank line must contain an object with an integer timestamp_ms field, and each file must already satisfy the sorting contract.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
import json

from merge_logs import merge_logs


def read_records(file):
    for line in file:
        if line.strip():
            yield json.loads(line)


with open("worker-a.jsonl", encoding="utf-8") as a, open(
    "worker-b.jsonl", encoding="utf-8"
) as b:
    for record in merge_logs(read_records(a), read_records(b)):
        print(json.dumps(record, ensure_ascii=False))

Returning the iterator from inside with and consuming it afterward would attempt reads on closed files. Keep ownership of the files around the entire iteration. Invalid JSON, missing keys, and incompatible timestamp types raise exceptions during consumption; this helper assumes trusted, consistently shaped logs and does not validate them in advance.

Consume Only the Prefix You Need

Use islice() for a report that needs only the earliest few records. This standalone example shows that constructing the merge does not read either source.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
from itertools import islice

from merge_logs import merge_logs

reads = []


def source(name, times):
    for timestamp in times:
        reads.append((name, timestamp))
        yield {"timestamp_ms": timestamp, "message": name}


timeline = merge_logs(source("a", [100, 300]), source("b", [200, 400]))
print(reads)  # []
print([record["timestamp_ms"] for record in islice(timeline, 2)])
# [100, 200]
print(reads)  # [('a', 100), ('b', 200), ('a', 300)]

The merge reads an initial candidate from each source to find the earliest record. It then advances sources as needed. A small output limit can therefore read records beyond the last returned timestamp. Do not treat the iterator as an exact read limit for the underlying files. This is also a synchronous merge: fetching a candidate can block on its source. It does not coordinate live asynchronous log feeds or correct clock differences between workers.

Keep the Ordering Contract Explicit

heapq.merge() does not sort or check each input. A stream containing timestamps [300, 100] can produce an out-of-order timeline. If the files are unsorted, sort them first or use sorted() on all records when they fit in memory. For descending output, use reverse=True and supply inputs already sorted from largest to smallest.

For multiple active streams, the merge maintains a candidate per stream and uses a heap to select the next record. Its working storage scales with the number of streams rather than the total record count, excluding input buffers and records retained by the caller. Calling list() on the merged iterator still stores the complete output. A merge iterator and its generator inputs are consumed as you read them; create fresh inputs to run the report again.

Test Against a Full Sort

Save this as test_merge_logs.py beside the helper and run python test_merge_logs.py.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
from merge_logs import merge_logs


def records(times, worker):
    return [
        {"timestamp_ms": timestamp, "message": worker, "sequence": index}
        for index, timestamp in enumerate(times)
    ]


cases = [
    ([], []),
    ([100], []),
    ([], [200, 200]),
    ([100, 300], [200, 400]),
    ([100, 100, 300], [100, 200, 300]),
]
for left, right in cases:
    a, b = records(left, "a"), records(right, "b")
    result = list(merge_logs(iter(a), iter(b)))
    expected_times = sorted(left + right)
    assert [record["timestamp_ms"] for record in result] == expected_times
    identity = lambda record: (record["message"], record["sequence"])
    assert sorted(map(identity, result)) == sorted(map(identity, a + b))

assert list(merge_logs()) == []
print("Log merge checks passed.")

The timestamp comparison checks ordering independently of how equal timestamps are arranged. The identity comparison verifies that every source record survives exactly once, including records that share timestamps. Empty sources and a merge with no sources produce an empty result.