Skip to content

Commit 919afb0

Browse files
committed
Add non-blocking pod log streaming example
1 parent e81db31 commit 919afb0

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed

examples/README.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,11 @@ Please read the description at the top of each example for more information
55
about what the script does and any prerequisites. Most scripts also include
66
comments throughout the code.
77

8+
## Available Examples
9+
10+
- pod_logs.py — basic (blocking) pod log streaming example
11+
- pod_logs_non_blocking.py — non-blocking streaming of pod logs with graceful shutdown
12+
813
## Setup
914

1015
These scripts require Python 2.7 or 3.5+ and the Kubernetes client which can be

examples/pod_logs_non_blocking.py

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
"""
2+
Non-blocking pod log streaming example.
3+
4+
Demonstrates how to stream Kubernetes pod logs without blocking indefinitely
5+
by using socket timeouts and graceful shutdown.
6+
"""
7+
8+
import threading
9+
import time
10+
import socket
11+
from kubernetes import client, config
12+
from urllib3.exceptions import ReadTimeoutError
13+
14+
stop_event = threading.Event()
15+
16+
17+
def stream_logs():
18+
config.load_kube_config()
19+
v1 = client.CoreV1Api()
20+
21+
resp = v1.read_namespaced_pod_log(
22+
name="log-demo",
23+
namespace="default",
24+
follow=True,
25+
_preload_content=False
26+
)
27+
28+
# 👇 make socket non-blocking with timeout
29+
resp._fp.fp.raw._sock.settimeout(1)
30+
31+
try:
32+
while not stop_event.is_set():
33+
try:
34+
data = resp.read(1024)
35+
if data:
36+
print(data.decode(), end="")
37+
except (socket.timeout, ReadTimeoutError):
38+
continue
39+
finally:
40+
resp.close()
41+
print("\nLog streaming stopped cleanly.")
42+
43+
44+
t = threading.Thread(target=stream_logs)
45+
t.start()
46+
47+
try:
48+
time.sleep(15)
49+
finally:
50+
stop_event.set()
51+
t.join()

0 commit comments

Comments
 (0)