-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimple_watcher_example.py
More file actions
140 lines (104 loc) · 4.64 KB
/
Copy pathsimple_watcher_example.py
File metadata and controls
140 lines (104 loc) · 4.64 KB
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
#!/usr/bin/env python3
"""
Simple watcher example demonstrating default handlers.
This example shows how to use the built-in default handlers provided
by SimpleBroker for common use cases like debugging and monitoring.
"""
import time
from pathlib import Path
from tempfile import TemporaryDirectory
from simplebroker import Queue, QueueWatcher
from simplebroker.watcher import (
default_error_handler,
json_print_handler,
logger_handler,
simple_print_handler,
)
def main() -> None:
"""Demonstrate different default handlers."""
with TemporaryDirectory() as tmpdir:
run_examples(Path(tmpdir) / "watcher_demo.db")
def run_examples(db_path: Path) -> None:
"""Run the examples against an isolated database."""
# Create a persistent queue for the watcher
with Queue("demo", db_path=str(db_path), persistent=True) as queue:
# Add some test messages
queue.write("Hello World!")
queue.write("Message with\nnewlines")
queue.write("Special chars: <>&'\"")
print("=== Example 1: Simple Print Handler ===")
print("Basic handler that prints [timestamp] message format")
# Use simple_print_handler - good for debugging
watcher1 = QueueWatcher("demo", simple_print_handler, db=str(db_path))
# Add a message and process it
with Queue("demo", db_path=str(db_path), persistent=True) as queue:
queue.write("Debug message 1")
# Run watcher briefly to show output
with watcher1:
time.sleep(0.5) # Let it process messages
print("\n=== Example 2: JSON Print Handler ===")
print("Structured JSON output - safe for shell processing")
# Use json_print_handler - good for shell pipelines
watcher2 = QueueWatcher("demo", json_print_handler, db=str(db_path))
# Add messages with special characters
with Queue("demo", db_path=str(db_path), persistent=True) as queue:
queue.write('JSON safe: newlines\nand quotes"')
queue.write("Another message")
with watcher2:
time.sleep(0.5)
print("\n=== Example 3: Logger Handler ===")
print("Uses Python logging system - integrates with your app logging")
# Configure logging to see the output
import logging
logging.basicConfig(level=logging.INFO, format="%(name)s: %(message)s")
# Use logger_handler - good for production apps
watcher3 = QueueWatcher("demo", logger_handler, db=str(db_path))
with Queue("demo", db_path=str(db_path), persistent=True) as queue:
queue.write("Logged message 1")
queue.write("Logged message 2")
with watcher3:
time.sleep(0.5)
print("\n=== Example 4: Custom Handler Using Default as Base ===")
print("You can easily build on the defaults")
def custom_handler(msg: str, ts: int) -> None:
"""Custom handler that adds context before using default."""
print(f"[CUSTOM] Processing at {time.strftime('%H:%M:%S')}")
simple_print_handler(msg, ts) # Use default as building block
print("[CUSTOM] Completed processing")
watcher4 = QueueWatcher("demo", custom_handler, db=str(db_path))
with Queue("demo", db_path=str(db_path), persistent=True) as queue:
queue.write("Custom handled message")
with watcher4:
time.sleep(0.5)
# Clean up - read remaining messages to clear queue
with Queue("demo", db_path=str(db_path), persistent=True) as queue:
while queue.read() is not None:
pass # Clear any remaining messages
print("\n=== Example 5: Error Handler Demonstration ===")
print("Shows how to use the default error handler")
def failing_handler(msg: str, ts: int) -> None:
"""Handler that fails on certain messages."""
if "error" in msg.lower():
raise ValueError(f"Simulated error processing: {msg}")
print(f"Successfully processed: {msg}")
# Use default_error_handler explicitly
watcher5 = QueueWatcher(
"demo",
failing_handler,
db=str(db_path),
error_handler=default_error_handler,
)
with Queue("demo", db_path=str(db_path), persistent=True) as queue:
queue.write("Good message")
queue.write("This will cause an ERROR")
queue.write("Another good message")
with watcher5:
time.sleep(0.5)
print("\nDemo complete! The default handlers provide:")
print("• simple_print_handler: Basic [timestamp] message output")
print("• json_print_handler: Safe structured JSON output")
print("• logger_handler: Integration with Python logging")
print("• default_error_handler: Error logging and continuation")
print("All are importable from simplebroker.watcher")
if __name__ == "__main__":
main()