Skip to content

Commit 9bf502a

Browse files
authored
log_exception context manager avoids spamming by not logging every exception (#126)
1 parent 8dbb794 commit 9bf502a

File tree

1 file changed

+22
-6
lines changed

1 file changed

+22
-6
lines changed

rendercanvas/_coreutils.py

Lines changed: 22 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
import os
66
import re
77
import sys
8+
import time
89
import weakref
910
import logging
1011
import ctypes.util
@@ -18,7 +19,7 @@
1819
logger.setLevel(logging.WARNING)
1920

2021

21-
err_hashes = {}
22+
err_hashes = {} # hash -> [short-message, count, next-time]
2223

2324
_re_wgpu_ob = re.compile(r"`<[a-z|A-Z]+-\([0-9]+, [0-9]+, [a-z|A-Z]+\)>`")
2425

@@ -47,16 +48,31 @@ def log_exception(kind):
4748
msg = str(err)
4849
msgh = error_message_hash(msg)
4950
if msgh not in err_hashes:
51+
# Prepare a short variant of the message for later use
52+
short_msg = kind + ": " + msg.split("\n")[0].strip()
53+
short_msg = short_msg if len(short_msg) <= 70 else short_msg[:69] + "…"
54+
err_hashes[msgh] = [short_msg, 1, 0]
5055
# Provide the exception, so the default logger prints a stacktrace.
5156
# IDE's can get the exception from the root logger for PM debugging.
52-
err_hashes[msgh] = 1
5357
logger.error(kind, exc_info=err)
5458
else:
5559
# We've seen this message before, return a one-liner instead.
56-
err_hashes[msgh] = count = err_hashes[msgh] + 1
57-
msg = kind + ": " + msg.split("\n")[0].strip()
58-
msg = msg if len(msg) <= 70 else msg[:69] + "…"
59-
logger.error(msg + f" ({count})")
60+
short_count_tm = err_hashes[msgh]
61+
short, count, tm = short_count_tm
62+
short_count_tm[1] = count = count + 1
63+
# Show the message now?
64+
show_message = False
65+
cur_time = time.perf_counter()
66+
if count <= 5:
67+
show_message = True
68+
else:
69+
if cur_time > tm:
70+
show_message = True
71+
# Log the messages and schedule when to show it next.
72+
# Next message is after 1-3 seconds (3 when count reaches 300).
73+
if show_message:
74+
short_count_tm[2] = cur_time + min(max(count / 100, 1), 3)
75+
logger.error(f"{short} ({count})")
6076

6177

6278
# %% Weak bindings

0 commit comments

Comments
 (0)