Repository navigation
Expand file tree
/
Copy path_log.py
More file actions
267 lines (216 loc) · 7.69 KB
/
Copy path_log.py
File metadata and controls
267 lines (216 loc) · 7.69 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
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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
# Tencent is pleased to support the open source community by making tRPC-Python available.
#
# Copyright (C) 2026 Tencent. All rights reserved.
#
# tRPC-Python is licensed under Apache-2.0.
"""Logging extension interfaces and shared configuration models.
This module defines severity levels, output configuration dataclasses, and the
abstract logger contract used by pluggable logging backends.
"""
from __future__ import annotations
import logging
from abc import abstractmethod
from dataclasses import dataclass
from enum import IntEnum
from enum import unique
from typing import Any
from typing import Optional
from ._plugin import BasePlugin
from ._plugin import PluginType
@unique
class LogLevelType(IntEnum):
"""Define supported log severity levels."""
NIL = 0
TRACE = 1
DEBUG = 2
INFO = 3
WARNING = 4
ERROR = 5
FATAL = 6
LOG_LEVEL_NAMES = {
"trace": LogLevelType.TRACE,
"debug": LogLevelType.DEBUG,
"info": LogLevelType.INFO,
"warning": LogLevelType.WARNING,
"error": LogLevelType.ERROR,
"fatal": LogLevelType.FATAL,
}
"""Map lowercase severity names to ``LogLevelType`` values."""
@dataclass
class WriterConfig:
"""Describe file-backed log writer options.
Attributes:
filename: Base log file name.
log_path: Directory that stores rolled log files.
max_size: Maximum size of one log file in megabytes.
max_backups: Maximum number of retained backup files.
max_age: Maximum age of retained files in days.
compress: Whether rotated files should be compressed.
roll_type: Rolling strategy identifier.
time_unit: Time unit used by time-based rolling.
"""
filename: str = ""
log_path: str = ""
max_size: int = 0
max_backups: int = 0
max_age: int = 0
compress: bool = False
roll_type: str = ""
time_unit: str = ""
@dataclass
class FormatConfig:
"""Describe structured log field formatting options.
Attributes:
time_fmt: Timestamp format string.
time_key: Field name used for the timestamp.
level_key: Field name used for the severity level.
name_key: Field name used for the logger name.
caller_key: Field name used for the caller location.
message_key: Field name used for the log message.
stacktrace_key: Field name used for stack traces.
fmt: Complete format template string.
"""
time_fmt: str = ""
time_key: str = ""
level_key: str = ""
name_key: str = ""
caller_key: str = ""
message_key: str = ""
stacktrace_key: str = ""
fmt: str = ""
@dataclass
class OutputConfig:
"""Describe one logger output destination.
Attributes:
writer: Writer backend name.
level: Minimum severity accepted by this output.
formatter: Formatter backend name.
caller_skip: Number of stack frames to skip when recording callers.
writer_config: Writer-specific options.
format_config: Formatter-specific options.
"""
writer: str = ""
level: str = ""
formatter: str = ""
caller_skip: int = 2
writer_config: WriterConfig = None
format_config: FormatConfig = None
capture_third_party: bool = False
third_party_level: str = ""
def effective_third_party_level(self) -> str:
"""Return the level name third-party logs must reach on this output.
Each backend maps the name onto its own level table, but the fallback
chain is the same everywhere.
"""
return (self.third_party_level or self.level or "debug").lower()
class BaseWriter(BasePlugin):
"""Hold runtime state for one concrete log writer.
Attributes:
output_config: Output configuration that created this writer.
fmt: Message format template.
time_fmt: Timestamp format string.
handler: Backend-specific handler instance.
level: Effective severity threshold for this writer.
"""
def __init__(self):
"""Initialize the writer plugin."""
super().__init__()
self._type = PluginType.LOG_WRITER
self._name = ""
self._version = ""
self._output_config: OutputConfig = None
self._fmt: str = (
"[%(asctime)s][%(levelname)s][%(filename)s:%(lineno)s]"
"[%(process)d][%(message)s]"
)
self._time_fmt: str = "%Y-%m-%d %H:%M:%S"
self._handler: Optional[logging.Handler] = None
self._level: Optional[int] = None
@property
def output_config(self) -> OutputConfig:
"""Get the output configuration."""
return self._output_config
@property
def fmt(self) -> str:
"""Get the message format template."""
return self._fmt
@property
def time_fmt(self) -> str:
"""Get the timestamp format string."""
return self._time_fmt
@property
def handler(self) -> Optional[logging.Handler]:
"""Get the backend-specific handler instance."""
return self._handler
@property
def level(self) -> Optional[int]:
"""Get the effective severity threshold for this writer."""
return self._level
class BaseLogger(BasePlugin):
"""Define the pluggable logger API used by the framework."""
def __init__(self):
"""Initialize the logger plugin."""
super().__init__()
self._type = PluginType.LOG_COMPONENT
self._name = "default"
@abstractmethod
def debug(self, format_str: str, *args, **kwargs):
"""Log a debug-severity message.
Args:
format_str: printf-style or backend-specific format string.
*args: Positional values interpolated into ``format_str``.
**kwargs: Backend-specific structured fields or options.
"""
...
@abstractmethod
def info(self, format_str: str, *args, **kwargs):
"""Log an info-severity message.
Args:
format_str: printf-style or backend-specific format string.
*args: Positional values interpolated into ``format_str``.
**kwargs: Backend-specific structured fields or options.
"""
...
@abstractmethod
def warning(self, format_str: str, *args, **kwargs):
"""Log a warning-severity message.
Args:
format_str: printf-style or backend-specific format string.
*args: Positional values interpolated into ``format_str``.
**kwargs: Backend-specific structured fields or options.
"""
...
@abstractmethod
def error(self, format_str: str, *args, **kwargs):
"""Log an error-severity message.
Args:
format_str: printf-style or backend-specific format string.
*args: Positional values interpolated into ``format_str``.
**kwargs: Backend-specific structured fields or options.
"""
...
@abstractmethod
def fatal(self, format_str: str, *args, **kwargs):
"""Log a fatal-severity message.
Args:
format_str: printf-style or backend-specific format string.
*args: Positional values interpolated into ``format_str``.
**kwargs: Backend-specific structured fields or options.
"""
...
@abstractmethod
def set_level(self, level: LogLevelType):
"""Update the minimum severity accepted by this logger.
Args:
level: New severity threshold.
"""
...
@abstractmethod
def with_fields(self, **kwargs: Any):
"""Return a logger enriched with structured fields.
Args:
**kwargs: Field names and values attached to subsequent log lines.
Returns:
Logger instance that includes the supplied fields.
"""
...