Skip to content

Commit bbfaffe

Browse files
test multithreaded logging
(cherry picked from commit 349709a)
1 parent 76a3b18 commit bbfaffe

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed

stdlib/Logging/test/runtests.jl

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -306,4 +306,47 @@ end
306306
@test isempty(undoc)
307307
end
308308

309+
@testset "Logging when multithreaded" begin
310+
n = 10000
311+
cmd = `$(Base.julia_cmd()) -t4 --color=no $(joinpath(@__DIR__, "threads_exec.jl")) $n`
312+
fname = tempname()
313+
@testset "Thread safety" begin
314+
f = open(fname, "w")
315+
@test success(run(pipeline(cmd, stderr=f)))
316+
close(f)
317+
end
318+
319+
@testset "No tearing in log printing" begin
320+
# Check for print tearing by verifying that each log entry starts and ends correctly
321+
f = open(fname, "r")
322+
entry_start = r"┌ (Info|Warning|Error): iteration"
323+
entry_end = r""
324+
325+
open_entries = 0
326+
total_entries = 0
327+
for line in eachline(fname)
328+
starts = count(entry_start, line)
329+
starts > 1 && error("Interleaved logs: Multiple log entries started on one line")
330+
if starts == 1
331+
startswith(line, entry_start) || error("Interleaved logs: Log entry started in the middle of a line")
332+
open_entries += 1
333+
total_entries += 1
334+
end
335+
336+
ends = count(entry_end, line)
337+
starts == 1 && ends == 1 && error("Interleaved logs: Log entry started and and another ended on one line")
338+
ends > 1 && error("Interleaved logs: Multiple log entries ended on one line")
339+
if ends == 1
340+
startswith(line, entry_end) || error("Interleaved logs: Log entry ended in the middle of a line")
341+
open_entries -= 1
342+
end
343+
# Ensure no mismatched log entries
344+
open_entries >= 0 || error("Interleaved logs")
345+
end
346+
347+
@test open_entries == 0 # Ensure all entries closed properly
348+
@test total_entries == n * 3 # Ensure all logs were printed (3 because @debug is hidden)
349+
end
350+
end
351+
309352
end

stdlib/Logging/test/threads_exec.jl

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
using Logging
2+
3+
function test_threads_exec(n)
4+
Threads.@threads for i in 1:n
5+
@debug "iteration" maxlog=1 _id=Symbol("$(i)_debug") i Threads.threadid()
6+
@info "iteration" maxlog=1 _id=Symbol("$(i)_info") i Threads.threadid()
7+
@warn "iteration" maxlog=1 _id=Symbol("$(i)_warn") i Threads.threadid()
8+
@error "iteration" maxlog=1 _id=Symbol("$(i)_error") i Threads.threadid()
9+
end
10+
end
11+
12+
n = parse(Int, ARGS[1])
13+
test_threads_exec(n)

0 commit comments

Comments
 (0)