Encoding
encoding ¶
Cross-platform encoding support for structured logging.
This module provides the EncodingSafeProcessor, a structlog processor that sanitizes string values in event dictionaries to prevent UnicodeEncodeError exceptions on consoles with limited encoding support (e.g., Windows cp1252).
The processor uses a two-phase sanitization strategy: 1. Smart character replacements that preserve semantic meaning (e.g., smart quotes → regular quotes, em dash → double hyphen) 2. Fallback encode/decode with 'replace' error handler for any remaining unencodable characters
This approach ensures log output is always writable to the console without raising exceptions, while preserving as much of the original meaning as possible.
Example
Add to structlog processor chain before the renderer:
import structlog
from gepa_adk.utils.encoding import EncodingSafeProcessor
structlog.configure(
processors=[
structlog.contextvars.merge_contextvars,
structlog.stdlib.add_log_level,
structlog.processors.TimeStamper(fmt="iso"),
EncodingSafeProcessor(), # Before renderer
structlog.dev.ConsoleRenderer(),
],
wrapper_class=structlog.BoundLogger,
context_class=dict,
logger_factory=structlog.PrintLoggerFactory(),
)
See Also
- ADR-011: Cross-Platform Encoding for design decisions
- ADR-008: Structured Logging for processor chain patterns
Note
This processor is designed to be transparent on UTF-8 consoles (macOS, Linux) while preventing crashes on cp1252 consoles (Windows).
EncodingSafeProcessor ¶
Sanitize strings for console encoding compatibility.
A structlog processor that ensures all string values in the event dict can be safely written to the console regardless of its encoding (cp1252 on Windows, UTF-8 on macOS/Linux).
The sanitization strategy: 1. Apply smart character replacements (preserve meaning) 2. Encode to console encoding with 'replace' error handler 3. Decode back to string
This produces strings that are guaranteed to be writable to the console without raising UnicodeEncodeError.
| ATTRIBUTE | DESCRIPTION |
|---|---|
REPLACEMENTS | Class constant mapping Unicode characters to ASCII equivalents that preserve semantic meaning. TYPE: |
encoding | The target console encoding detected at initialization. TYPE: |
sanitize_string | Sanitize a single string for console encoding. TYPE: |
Examples:
Use as a structlog processor:
processor = EncodingSafeProcessor()
event = {"event": "User said \u2018hello\u2019"}
result = processor(None, "info", event)
# result["event"] == "User said 'hello'"
Note
All sanitization is idempotent - processing already-sanitized strings produces identical output.
Source code in src/gepa_adk/utils/encoding.py
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 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 | |
__init__ ¶
Initialize the processor with console encoding detection.
Detects the console encoding from sys.stdout.encoding, falling back to UTF-8 if detection fails (e.g., when stdout is redirected or unavailable).
Note
Console encoding is cached at initialization time to avoid repeated attribute lookups during log processing.
Source code in src/gepa_adk/utils/encoding.py
__call__ ¶
__call__(
logger: Any,
method_name: str,
event_dict: MutableMapping[str, Any],
) -> MutableMapping[str, Any]
Process event dictionary, sanitizing all string values.
Implements the structlog processor protocol. Recursively sanitizes all string values in the event dictionary, including nested dicts and lists.
| PARAMETER | DESCRIPTION |
|---|---|
logger | The wrapped logger instance (unused but required by protocol). TYPE: |
method_name | Name of the log method called (e.g., "info", "debug"). Unused but required by protocol. TYPE: |
event_dict | Mutable mapping of log event data to sanitize. TYPE: |
| RETURNS | DESCRIPTION |
|---|---|
MutableMapping[str, Any] | The event_dict with all string values sanitized for console |
MutableMapping[str, Any] | encoding compatibility. |
Note
Original event_dict is not modified; a new dict is returned with sanitized values.
Source code in src/gepa_adk/utils/encoding.py
sanitize_string ¶
Sanitize a single string for console encoding.
Applies smart character replacements first to preserve meaning, then uses encode/decode with 'replace' error handler for any remaining unencodable characters.
| PARAMETER | DESCRIPTION |
|---|---|
s | The string to sanitize. TYPE: |
| RETURNS | DESCRIPTION |
|---|---|
str | A string that is guaranteed to be encodable to the console |
str | encoding without raising UnicodeEncodeError. |
Examples:
Sanitize a string with smart quotes:
processor = EncodingSafeProcessor()
result = processor.sanitize_string("User said ‘hello’")
assert result == "User said 'hello'"
Note
Order of operations: smart replacements run first to preserve semantic meaning, then encode/decode handles remaining characters.