|
| 1 | +# Copyright 2025 The Kubeflow Authors. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +"""Custom log formatters for Kubeflow SDK.""" |
| 16 | + |
| 17 | +from datetime import datetime, timezone |
| 18 | +import json |
| 19 | +import logging |
| 20 | +from typing import Optional |
| 21 | + |
| 22 | + |
| 23 | +class StructuredFormatter(logging.Formatter): |
| 24 | + """JSON structured formatter for Kubeflow SDK logs. |
| 25 | +
|
| 26 | + This formatter outputs logs in JSON format, making them suitable for |
| 27 | + log aggregation systems like ELK stack, Fluentd, etc. |
| 28 | + """ |
| 29 | + |
| 30 | + def format(self, record: logging.LogRecord) -> str: |
| 31 | + """Format log record as JSON. |
| 32 | +
|
| 33 | + Args: |
| 34 | + record: Log record to format |
| 35 | +
|
| 36 | + Returns: |
| 37 | + JSON formatted log string |
| 38 | + """ |
| 39 | + log_entry = { |
| 40 | + "timestamp": datetime.now(timezone.utc).isoformat(), |
| 41 | + "level": record.levelname, |
| 42 | + "logger": record.name, |
| 43 | + "message": record.getMessage(), |
| 44 | + "module": record.module, |
| 45 | + "function": record.funcName, |
| 46 | + "line": record.lineno, |
| 47 | + } |
| 48 | + |
| 49 | + # Add exception info if present |
| 50 | + if record.exc_info: |
| 51 | + log_entry["exception"] = self.formatException(record.exc_info) |
| 52 | + |
| 53 | + # Add extra fields from record |
| 54 | + for key, value in record.__dict__.items(): |
| 55 | + if key not in { |
| 56 | + "name", |
| 57 | + "msg", |
| 58 | + "args", |
| 59 | + "levelname", |
| 60 | + "levelno", |
| 61 | + "pathname", |
| 62 | + "filename", |
| 63 | + "module", |
| 64 | + "lineno", |
| 65 | + "funcName", |
| 66 | + "created", |
| 67 | + "msecs", |
| 68 | + "relativeCreated", |
| 69 | + "thread", |
| 70 | + "threadName", |
| 71 | + "processName", |
| 72 | + "process", |
| 73 | + "getMessage", |
| 74 | + "exc_info", |
| 75 | + "exc_text", |
| 76 | + "stack_info", |
| 77 | + }: |
| 78 | + log_entry[key] = value |
| 79 | + |
| 80 | + return json.dumps(log_entry, ensure_ascii=False) |
| 81 | + |
| 82 | + |
| 83 | +class ContextFormatter(logging.Formatter): |
| 84 | + """Context-aware formatter that includes operation context in logs. |
| 85 | +
|
| 86 | + This formatter adds contextual information like job_id, operation_type, |
| 87 | + and other relevant metadata to log messages. |
| 88 | + """ |
| 89 | + |
| 90 | + def __init__( |
| 91 | + self, |
| 92 | + fmt: Optional[str] = None, |
| 93 | + datefmt: Optional[str] = None, |
| 94 | + include_context: bool = True, |
| 95 | + ): |
| 96 | + """Initialize context formatter. |
| 97 | +
|
| 98 | + Args: |
| 99 | + fmt: Log format string |
| 100 | + datefmt: Date format string |
| 101 | + include_context: Whether to include context information |
| 102 | + """ |
| 103 | + if fmt is None: |
| 104 | + fmt = "%(asctime)s - %(name)s - %(levelname)s - %(context)s - %(message)s" |
| 105 | + |
| 106 | + super().__init__(fmt, datefmt) |
| 107 | + self.include_context = include_context |
| 108 | + |
| 109 | + def format(self, record: logging.LogRecord) -> str: |
| 110 | + """Format log record with context information. |
| 111 | +
|
| 112 | + Args: |
| 113 | + record: Log record to format |
| 114 | +
|
| 115 | + Returns: |
| 116 | + Formatted log string with context |
| 117 | + """ |
| 118 | + # Add context information |
| 119 | + context_parts = [] |
| 120 | + |
| 121 | + # Add job_id if available |
| 122 | + if hasattr(record, "job_id"): |
| 123 | + context_parts.append(f"job_id={record.job_id}") |
| 124 | + |
| 125 | + # Add operation type if available |
| 126 | + if hasattr(record, "operation"): |
| 127 | + context_parts.append(f"operation={record.operation}") |
| 128 | + |
| 129 | + # Add backend type if available |
| 130 | + if hasattr(record, "backend"): |
| 131 | + context_parts.append(f"backend={record.backend}") |
| 132 | + |
| 133 | + # Set context string |
| 134 | + if context_parts and self.include_context: |
| 135 | + record.context = " | ".join(context_parts) |
| 136 | + else: |
| 137 | + record.context = "general" |
| 138 | + |
| 139 | + return super().format(record) |
0 commit comments