Custom log formatter for console output. Supports field expansion and adds thread, timestamp and other information.
| 69 | |
| 70 | |
| 71 | class CustomFormatter(logging.Formatter): |
| 72 | """ |
| 73 | Custom log formatter for console output. |
| 74 | Supports field expansion and adds thread, timestamp and other information. |
| 75 | """ |
| 76 | |
| 77 | def _format_attributes(self, record): |
| 78 | """ |
| 79 | Expand attributes in record to [attr=value] format |
| 80 | """ |
| 81 | if hasattr(record, "attributes"): |
| 82 | if isinstance(record.attributes, dict): |
| 83 | return " ".join(f"[{k}={v}]" for k, v in record.attributes.items()) |
| 84 | return "" |
| 85 | |
| 86 | def _camel_to_snake(self, name: str) -> str: |
| 87 | """Convert camel case to snake case""" |
| 88 | s1 = re.sub("([a-z0-9])([A-Z])", r"\1_\2", name) |
| 89 | return s1.lower() |
| 90 | |
| 91 | def format(self, record): |
| 92 | """ |
| 93 | Format log record, with new support for attributes expansion and otelSpanID/otelTraceID fields. |
| 94 | Supports field expansion and adds thread, timestamp and other information. |
| 95 | Args: |
| 96 | record (LogRecord): Log record object. |
| 97 | Returns: |
| 98 | str: Log message string. |
| 99 | """ |
| 100 | |
| 101 | try: |
| 102 | log_fields = { |
| 103 | "thread": record.thread, |
| 104 | "thread_name": record.threadName, |
| 105 | "timestamp": int(time.time() * 1000), |
| 106 | } |
| 107 | |
| 108 | if hasattr(record, "attributes") and isinstance(record.attributes, dict): |
| 109 | for k, v in record.attributes.items(): |
| 110 | log_fields[self._camel_to_snake(k)] = v |
| 111 | |
| 112 | # filter out null values. |
| 113 | log_fields = {k: v for k, v in log_fields.items() if not (isinstance(v, str) and v == "")} |
| 114 | |
| 115 | log_str = " ".join(f"[{k}={v}]" for k, v in log_fields.items()) |
| 116 | if log_str: |
| 117 | record.msg = f"{log_str} {record.msg}" |
| 118 | |
| 119 | # Add OpenTelemetry-related fields. |
| 120 | if hasattr(record, "otelSpanID") and record.otelSpanID is not None: |
| 121 | record.msg = f"[otel_span_id={record.otelSpanID}] {record.msg}" |
| 122 | if hasattr(record, "otelTraceID") and record.otelTraceID is not None: |
| 123 | record.msg = f"[otel_trace_id={record.otelTraceID}] {record.msg}" |
| 124 | |
| 125 | except: |
| 126 | pass |
| 127 | |
| 128 | return super().format(record) |
no outgoing calls