logxpy 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- logxpy/__init__.py +126 -0
- logxpy/_action.py +958 -0
- logxpy/_async.py +186 -0
- logxpy/_base.py +80 -0
- logxpy/_compat.py +71 -0
- logxpy/_config.py +45 -0
- logxpy/_dest.py +88 -0
- logxpy/_errors.py +58 -0
- logxpy/_fmt.py +68 -0
- logxpy/_generators.py +136 -0
- logxpy/_mask.py +23 -0
- logxpy/_message.py +195 -0
- logxpy/_output.py +517 -0
- logxpy/_pool.py +93 -0
- logxpy/_traceback.py +126 -0
- logxpy/_types.py +71 -0
- logxpy/_util.py +56 -0
- logxpy/_validation.py +486 -0
- logxpy/_version.py +21 -0
- logxpy/cli.py +61 -0
- logxpy/dask.py +172 -0
- logxpy/decorators.py +268 -0
- logxpy/filter.py +124 -0
- logxpy/journald.py +88 -0
- logxpy/json.py +149 -0
- logxpy/loggerx.py +253 -0
- logxpy/logwriter.py +84 -0
- logxpy/parse.py +191 -0
- logxpy/prettyprint.py +173 -0
- logxpy/serializers.py +36 -0
- logxpy/stdlib.py +23 -0
- logxpy/tai64n.py +45 -0
- logxpy/testing.py +472 -0
- logxpy/tests/__init__.py +9 -0
- logxpy/tests/common.py +36 -0
- logxpy/tests/strategies.py +231 -0
- logxpy/tests/test_action.py +1751 -0
- logxpy/tests/test_api.py +86 -0
- logxpy/tests/test_async.py +67 -0
- logxpy/tests/test_compat.py +13 -0
- logxpy/tests/test_config.py +21 -0
- logxpy/tests/test_coroutines.py +105 -0
- logxpy/tests/test_dask.py +211 -0
- logxpy/tests/test_decorators.py +54 -0
- logxpy/tests/test_filter.py +122 -0
- logxpy/tests/test_fmt.py +42 -0
- logxpy/tests/test_generators.py +292 -0
- logxpy/tests/test_journald.py +246 -0
- logxpy/tests/test_json.py +208 -0
- logxpy/tests/test_loggerx.py +44 -0
- logxpy/tests/test_logwriter.py +262 -0
- logxpy/tests/test_message.py +334 -0
- logxpy/tests/test_output.py +921 -0
- logxpy/tests/test_parse.py +309 -0
- logxpy/tests/test_pool.py +55 -0
- logxpy/tests/test_prettyprint.py +303 -0
- logxpy/tests/test_pyinstaller.py +35 -0
- logxpy/tests/test_serializers.py +36 -0
- logxpy/tests/test_stdlib.py +73 -0
- logxpy/tests/test_tai64n.py +66 -0
- logxpy/tests/test_testing.py +1051 -0
- logxpy/tests/test_traceback.py +251 -0
- logxpy/tests/test_twisted.py +814 -0
- logxpy/tests/test_util.py +45 -0
- logxpy/tests/test_validation.py +989 -0
- logxpy/twisted.py +265 -0
- logxpy-0.1.0.dist-info/METADATA +100 -0
- logxpy-0.1.0.dist-info/RECORD +72 -0
- logxpy-0.1.0.dist-info/WHEEL +5 -0
- logxpy-0.1.0.dist-info/entry_points.txt +2 -0
- logxpy-0.1.0.dist-info/licenses/LICENSE +201 -0
- logxpy-0.1.0.dist-info/top_level.txt +1 -0
logxpy/_validation.py
ADDED
|
@@ -0,0 +1,486 @@
|
|
|
1
|
+
"""
|
|
2
|
+
A log message serialization and validation system for Eliot.
|
|
3
|
+
|
|
4
|
+
Validation is intended to be done by unit tests, not the production code path,
|
|
5
|
+
although in theory it could be done then as well.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from warnings import warn
|
|
9
|
+
|
|
10
|
+
from pyrsistent import PClass, field as pyrsistent_field
|
|
11
|
+
|
|
12
|
+
from ._message import (
|
|
13
|
+
Message,
|
|
14
|
+
REASON_FIELD,
|
|
15
|
+
MESSAGE_TYPE_FIELD,
|
|
16
|
+
TASK_LEVEL_FIELD,
|
|
17
|
+
TASK_UUID_FIELD,
|
|
18
|
+
TIMESTAMP_FIELD,
|
|
19
|
+
)
|
|
20
|
+
from ._action import (
|
|
21
|
+
start_action,
|
|
22
|
+
startTask,
|
|
23
|
+
ACTION_STATUS_FIELD,
|
|
24
|
+
ACTION_TYPE_FIELD,
|
|
25
|
+
STARTED_STATUS,
|
|
26
|
+
SUCCEEDED_STATUS,
|
|
27
|
+
FAILED_STATUS,
|
|
28
|
+
log_message,
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class ValidationError(Exception):
|
|
33
|
+
"""
|
|
34
|
+
A field value failed validation.
|
|
35
|
+
"""
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
# Types that can be encoded to JSON:
|
|
39
|
+
_JSON_TYPES = {type(None), int, float, str, list, dict, bytes, bool}
|
|
40
|
+
_JSON_TYPES |= set((int,))
|
|
41
|
+
|
|
42
|
+
RESERVED_FIELDS = (TASK_LEVEL_FIELD, TASK_UUID_FIELD, TIMESTAMP_FIELD)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class Field(object):
|
|
46
|
+
"""
|
|
47
|
+
A named field that can accept rich types and serialize them to the logging
|
|
48
|
+
system's basic types (currently, JSON types).
|
|
49
|
+
|
|
50
|
+
An optional extra validation function can be used to validate inputs when
|
|
51
|
+
unit testing.
|
|
52
|
+
|
|
53
|
+
@ivar key: The name of the field, the key which refers to it,
|
|
54
|
+
e.g. C{"path"}.
|
|
55
|
+
|
|
56
|
+
@ivar description: A description of what this field contains.
|
|
57
|
+
@type description: C{str}
|
|
58
|
+
"""
|
|
59
|
+
|
|
60
|
+
def __init__(self, key, serializer, description="", extraValidator=None):
|
|
61
|
+
"""
|
|
62
|
+
@param serializer: A function that takes a single rich input and
|
|
63
|
+
returns a serialized value that can be written out as JSON. May
|
|
64
|
+
raise L{ValidationError} to indicate bad inputs.
|
|
65
|
+
|
|
66
|
+
@param extraValidator: Allow additional validation of the field
|
|
67
|
+
value. A callable that takes a field value, and raises
|
|
68
|
+
L{ValidationError} if the value is a incorrect one for this
|
|
69
|
+
field. Alternatively can be set to C{None}, in which case no
|
|
70
|
+
additional validation is done.
|
|
71
|
+
"""
|
|
72
|
+
self.key = key
|
|
73
|
+
self.description = description
|
|
74
|
+
self._serializer = serializer
|
|
75
|
+
self._extraValidator = extraValidator
|
|
76
|
+
|
|
77
|
+
def validate(self, input):
|
|
78
|
+
"""
|
|
79
|
+
Validate the given input value against this L{Field} definition.
|
|
80
|
+
|
|
81
|
+
@param input: An input value supposedly serializable by this L{Field}.
|
|
82
|
+
|
|
83
|
+
@raises ValidationError: If the value is not serializable or fails to
|
|
84
|
+
be validated by the additional validator.
|
|
85
|
+
"""
|
|
86
|
+
# Make sure the input serializes:
|
|
87
|
+
self._serializer(input)
|
|
88
|
+
# Use extra validator, if given:
|
|
89
|
+
if self._extraValidator is not None:
|
|
90
|
+
self._extraValidator(input)
|
|
91
|
+
|
|
92
|
+
def serialize(self, input):
|
|
93
|
+
"""
|
|
94
|
+
Convert the given input to a value that can actually be logged.
|
|
95
|
+
|
|
96
|
+
@param input: An input value supposedly serializable by this L{Field}.
|
|
97
|
+
|
|
98
|
+
@return: A serialized value.
|
|
99
|
+
"""
|
|
100
|
+
return self._serializer(input)
|
|
101
|
+
|
|
102
|
+
@classmethod
|
|
103
|
+
def forValue(klass, key, value, description):
|
|
104
|
+
"""
|
|
105
|
+
Create a L{Field} that can only have a single value.
|
|
106
|
+
|
|
107
|
+
@param key: The name of the field, the key which refers to it,
|
|
108
|
+
e.g. C{"path"}.
|
|
109
|
+
|
|
110
|
+
@param value: The allowed value for the field.
|
|
111
|
+
|
|
112
|
+
@param description: A description of what this field contains.
|
|
113
|
+
@type description: C{str}
|
|
114
|
+
|
|
115
|
+
@return: A L{Field}.
|
|
116
|
+
"""
|
|
117
|
+
|
|
118
|
+
def validate(checked):
|
|
119
|
+
if checked != value:
|
|
120
|
+
raise ValidationError(checked, "Field %r must be %r" % (key, value))
|
|
121
|
+
|
|
122
|
+
return klass(key, lambda _: value, description, validate)
|
|
123
|
+
|
|
124
|
+
# PEP 8 variant:
|
|
125
|
+
for_value = forValue
|
|
126
|
+
|
|
127
|
+
@classmethod
|
|
128
|
+
def forTypes(klass, key, classes, description, extraValidator=None):
|
|
129
|
+
"""
|
|
130
|
+
Create a L{Field} that must be an instance of a given set of types.
|
|
131
|
+
|
|
132
|
+
@param key: The name of the field, the key which refers to it,
|
|
133
|
+
e.g. C{"path"}.
|
|
134
|
+
|
|
135
|
+
@ivar classes: A C{list} of allowed Python classes for this field's
|
|
136
|
+
values. Supported classes are C{str}, C{int}, C{float},
|
|
137
|
+
C{bool}, C{long}, C{list} and C{dict} and C{None} (the latter
|
|
138
|
+
isn't strictly a class, but will be converted appropriately).
|
|
139
|
+
|
|
140
|
+
@param description: A description of what this field contains.
|
|
141
|
+
@type description: C{str}
|
|
142
|
+
|
|
143
|
+
@param extraValidator: See description in L{Field.__init__}.
|
|
144
|
+
|
|
145
|
+
@return: A L{Field}.
|
|
146
|
+
"""
|
|
147
|
+
fixedClasses = []
|
|
148
|
+
for k in classes:
|
|
149
|
+
if k is None:
|
|
150
|
+
k = type(None)
|
|
151
|
+
if k not in _JSON_TYPES:
|
|
152
|
+
raise TypeError("%s is not JSON-encodeable" % (k,))
|
|
153
|
+
fixedClasses.append(k)
|
|
154
|
+
fixedClasses = tuple(fixedClasses)
|
|
155
|
+
|
|
156
|
+
def validate(value):
|
|
157
|
+
if not isinstance(value, fixedClasses):
|
|
158
|
+
raise ValidationError(
|
|
159
|
+
value, "Field %r requires type to be one of %s" % (key, classes)
|
|
160
|
+
)
|
|
161
|
+
if extraValidator is not None:
|
|
162
|
+
extraValidator(value)
|
|
163
|
+
|
|
164
|
+
return klass(key, lambda v: v, description, extraValidator=validate)
|
|
165
|
+
|
|
166
|
+
# PEP 8 variant:
|
|
167
|
+
for_types = forTypes
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def fields(*fields, **keys):
|
|
171
|
+
"""
|
|
172
|
+
Factory for for L{MessageType} and L{ActionType} field definitions.
|
|
173
|
+
|
|
174
|
+
@param *fields: A L{tuple} of L{Field} instances.
|
|
175
|
+
|
|
176
|
+
@param **keys: A L{dict} mapping key names to the expected type of the
|
|
177
|
+
field's values.
|
|
178
|
+
|
|
179
|
+
@return: A L{list} of L{Field} instances.
|
|
180
|
+
"""
|
|
181
|
+
return list(fields) + [
|
|
182
|
+
Field.forTypes(key, [value], "") for key, value in keys.items()
|
|
183
|
+
]
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
REASON = Field.forTypes(REASON_FIELD, [str], "The reason for an event.")
|
|
187
|
+
TRACEBACK = Field.forTypes("traceback", [str], "The traceback for an exception.")
|
|
188
|
+
EXCEPTION = Field.forTypes("exception", [str], "The FQPN of an exception class.")
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
class _MessageSerializer(object):
|
|
192
|
+
"""
|
|
193
|
+
A serializer and validator for messages.
|
|
194
|
+
|
|
195
|
+
@ivar fields: A C{dict} mapping a C{str} field name to the respective
|
|
196
|
+
L{Field}.
|
|
197
|
+
@ivar allow_additional_fields: If true, additional fields don't cause
|
|
198
|
+
validation failure.
|
|
199
|
+
"""
|
|
200
|
+
|
|
201
|
+
def __init__(self, fields, allow_additional_fields=False):
|
|
202
|
+
keys = []
|
|
203
|
+
for field in fields:
|
|
204
|
+
if not isinstance(field, Field):
|
|
205
|
+
raise TypeError("Expected a Field instance but got", field)
|
|
206
|
+
keys.append(field.key)
|
|
207
|
+
if len(set(keys)) != len(keys):
|
|
208
|
+
raise ValueError(keys, "Duplicate field name")
|
|
209
|
+
if ACTION_TYPE_FIELD in keys:
|
|
210
|
+
if MESSAGE_TYPE_FIELD in keys:
|
|
211
|
+
raise ValueError(
|
|
212
|
+
keys,
|
|
213
|
+
"Messages must have either "
|
|
214
|
+
"'action_type' or 'message_type', not both",
|
|
215
|
+
)
|
|
216
|
+
elif MESSAGE_TYPE_FIELD not in keys:
|
|
217
|
+
raise ValueError(
|
|
218
|
+
keys, "Messages must have either 'action_type' ", "or 'message_type'"
|
|
219
|
+
)
|
|
220
|
+
if any(key.startswith("_") for key in keys):
|
|
221
|
+
raise ValueError(keys, "Field names must not start with '_'")
|
|
222
|
+
for reserved in RESERVED_FIELDS:
|
|
223
|
+
if reserved in keys:
|
|
224
|
+
raise ValueError(
|
|
225
|
+
keys,
|
|
226
|
+
"The field name %r is reserved for use "
|
|
227
|
+
"by the logging framework" % (reserved,),
|
|
228
|
+
)
|
|
229
|
+
self.fields = dict((field.key, field) for field in fields)
|
|
230
|
+
self.allow_additional_fields = allow_additional_fields
|
|
231
|
+
|
|
232
|
+
def serialize(self, message):
|
|
233
|
+
"""
|
|
234
|
+
Serialize the given message in-place, converting inputs to outputs.
|
|
235
|
+
|
|
236
|
+
We do this in-place for performance reasons. There are more fields in
|
|
237
|
+
a message than there are L{Field} objects because of the timestamp,
|
|
238
|
+
task_level and task_uuid fields. By only iterating over our L{Fields}
|
|
239
|
+
we therefore reduce the number of function calls in a critical code
|
|
240
|
+
path.
|
|
241
|
+
|
|
242
|
+
@param message: A C{dict}.
|
|
243
|
+
"""
|
|
244
|
+
for key, field in self.fields.items():
|
|
245
|
+
message[key] = field.serialize(message[key])
|
|
246
|
+
|
|
247
|
+
def validate(self, message):
|
|
248
|
+
"""
|
|
249
|
+
Validate the given message.
|
|
250
|
+
|
|
251
|
+
@param message: A C{dict}.
|
|
252
|
+
|
|
253
|
+
@raises ValidationError: If the message has the wrong fields or one of
|
|
254
|
+
its field values fail validation.
|
|
255
|
+
"""
|
|
256
|
+
for key, field in self.fields.items():
|
|
257
|
+
if key not in message:
|
|
258
|
+
raise ValidationError(message, "Field %r is missing" % (key,))
|
|
259
|
+
field.validate(message[key])
|
|
260
|
+
|
|
261
|
+
if self.allow_additional_fields:
|
|
262
|
+
return
|
|
263
|
+
# Otherwise, additional fields are not allowed:
|
|
264
|
+
fieldSet = set(self.fields) | set(RESERVED_FIELDS)
|
|
265
|
+
for key in message:
|
|
266
|
+
if key not in fieldSet:
|
|
267
|
+
raise ValidationError(message, "Unexpected field %r" % (key,))
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
class MessageType(object):
|
|
271
|
+
"""
|
|
272
|
+
A specific type of non-action message.
|
|
273
|
+
|
|
274
|
+
Example usage:
|
|
275
|
+
|
|
276
|
+
# Schema definition:
|
|
277
|
+
KEY = Field("key", [int], u"The lookup key for things.")
|
|
278
|
+
STATUS = Field("status", [int], u"The status of a thing.")
|
|
279
|
+
LOG_STATUS = MessageType(
|
|
280
|
+
"yourapp:subsystem:status", [KEY, STATUS],
|
|
281
|
+
u"We just set the status of something.")
|
|
282
|
+
|
|
283
|
+
# Actual code, with logging added:
|
|
284
|
+
def setstatus(key, status):
|
|
285
|
+
doactualset(key, status)
|
|
286
|
+
LOG_STATUS(key=key, status=status).write()
|
|
287
|
+
|
|
288
|
+
You do not need to use the L{MessageType} to create the L{eliot.Message},
|
|
289
|
+
however; you could build it up using a series of L{eliot.Message.bind}
|
|
290
|
+
calls. Having a L{MessageType} is nonetheless still useful for validation
|
|
291
|
+
and documentation.
|
|
292
|
+
|
|
293
|
+
@ivar message_type: The name of the type,
|
|
294
|
+
e.g. C{"yourapp:subsystem:yourtype"}.
|
|
295
|
+
|
|
296
|
+
@ivar description: A description of what this message means.
|
|
297
|
+
@type description: C{str}
|
|
298
|
+
"""
|
|
299
|
+
|
|
300
|
+
def __init__(self, message_type, fields, description=""):
|
|
301
|
+
"""
|
|
302
|
+
@ivar type: The name of the type,
|
|
303
|
+
e.g. C{"yourapp:subsystem:yourtype"}.
|
|
304
|
+
|
|
305
|
+
@ivar fields: A C{list} of L{Field} instances which can appear in this
|
|
306
|
+
type.
|
|
307
|
+
|
|
308
|
+
@param description: A description of what this message means.
|
|
309
|
+
@type description: C{str}
|
|
310
|
+
"""
|
|
311
|
+
self.message_type = message_type
|
|
312
|
+
self.description = description
|
|
313
|
+
self._serializer = _MessageSerializer(
|
|
314
|
+
fields
|
|
315
|
+
+ [Field.forValue(MESSAGE_TYPE_FIELD, message_type, "The message type.")]
|
|
316
|
+
)
|
|
317
|
+
|
|
318
|
+
def __call__(self, **fields):
|
|
319
|
+
"""
|
|
320
|
+
Create a new L{eliot.Message} of this type with the given fields.
|
|
321
|
+
|
|
322
|
+
@param fields: Extra fields to add to the message.
|
|
323
|
+
|
|
324
|
+
@rtype: L{eliot.Message}
|
|
325
|
+
"""
|
|
326
|
+
warn(
|
|
327
|
+
"MessageType.__call__() is deprecated since 1.11.0, "
|
|
328
|
+
"use MessageType.log() instead.",
|
|
329
|
+
DeprecationWarning,
|
|
330
|
+
stacklevel=2,
|
|
331
|
+
)
|
|
332
|
+
fields[MESSAGE_TYPE_FIELD] = self.message_type
|
|
333
|
+
return Message(fields, self._serializer)
|
|
334
|
+
|
|
335
|
+
def log(self, **fields):
|
|
336
|
+
"""
|
|
337
|
+
Write a new L{Message} of this type to the default L{Logger}.
|
|
338
|
+
|
|
339
|
+
The keyword arguments will become contents of the L{Message}.
|
|
340
|
+
"""
|
|
341
|
+
fields["__eliot_serializer__"] = self._serializer
|
|
342
|
+
log_message(self.message_type, **fields)
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
class _ActionSerializers(PClass):
|
|
346
|
+
"""
|
|
347
|
+
Serializers for the three action messages: start, success and failure.
|
|
348
|
+
"""
|
|
349
|
+
|
|
350
|
+
start = pyrsistent_field(mandatory=True)
|
|
351
|
+
success = pyrsistent_field(mandatory=True)
|
|
352
|
+
failure = pyrsistent_field(mandatory=True)
|
|
353
|
+
|
|
354
|
+
|
|
355
|
+
class ActionType(object):
|
|
356
|
+
"""
|
|
357
|
+
A specific type of action.
|
|
358
|
+
|
|
359
|
+
Example usage:
|
|
360
|
+
|
|
361
|
+
# Schema definition:
|
|
362
|
+
KEY = Field("key", [int], u"The lookup key for things.")
|
|
363
|
+
RESULT = Field("result", [str], u"The result of lookups.")
|
|
364
|
+
LOG_DOSOMETHING = ActionType(
|
|
365
|
+
"yourapp:subsystem:youraction",
|
|
366
|
+
[KEY], [RESULT],
|
|
367
|
+
u"Do something with a key, resulting in a value.")
|
|
368
|
+
|
|
369
|
+
# Actual code, with logging added:
|
|
370
|
+
def dosomething(key):
|
|
371
|
+
with LOG_DOSOMETHING(logger, key=key) as action:
|
|
372
|
+
_dostuff(key)
|
|
373
|
+
_morestuff(key)
|
|
374
|
+
result = _theresult()
|
|
375
|
+
action.addSuccessFields(result=result)
|
|
376
|
+
return result
|
|
377
|
+
|
|
378
|
+
@ivar action_type: The name of the action,
|
|
379
|
+
e.g. C{"yourapp:subsystem:youraction"}.
|
|
380
|
+
|
|
381
|
+
@ivar startFields: A C{list} of L{Field} instances which can appear in
|
|
382
|
+
this action's start message.
|
|
383
|
+
|
|
384
|
+
@ivar successFields: A C{list} of L{Field} instances which can appear in
|
|
385
|
+
this action's successful finish message.
|
|
386
|
+
|
|
387
|
+
@ivar failureFields: A C{list} of L{Field} instances which can appear in
|
|
388
|
+
this action's failed finish message (in addition to the built-in
|
|
389
|
+
C{"exception"} and C{"reason"} fields).
|
|
390
|
+
|
|
391
|
+
@ivar description: A description of what this action's messages mean.
|
|
392
|
+
@type description: C{str}
|
|
393
|
+
"""
|
|
394
|
+
|
|
395
|
+
# Overrideable hook for testing; need staticmethod() so functions don't
|
|
396
|
+
# get turned into methods.
|
|
397
|
+
_start_action = staticmethod(start_action)
|
|
398
|
+
_startTask = staticmethod(startTask)
|
|
399
|
+
|
|
400
|
+
def __init__(self, action_type, startFields, successFields, description=""):
|
|
401
|
+
self.action_type = action_type
|
|
402
|
+
self.description = description
|
|
403
|
+
|
|
404
|
+
actionTypeField = Field.forValue(
|
|
405
|
+
ACTION_TYPE_FIELD, action_type, "The action type"
|
|
406
|
+
)
|
|
407
|
+
|
|
408
|
+
def makeActionStatusField(value):
|
|
409
|
+
return Field.forValue(ACTION_STATUS_FIELD, value, "The action status")
|
|
410
|
+
|
|
411
|
+
startFields = startFields + [
|
|
412
|
+
actionTypeField,
|
|
413
|
+
makeActionStatusField(STARTED_STATUS),
|
|
414
|
+
]
|
|
415
|
+
successFields = successFields + [
|
|
416
|
+
actionTypeField,
|
|
417
|
+
makeActionStatusField(SUCCEEDED_STATUS),
|
|
418
|
+
]
|
|
419
|
+
failureFields = [
|
|
420
|
+
actionTypeField,
|
|
421
|
+
makeActionStatusField(FAILED_STATUS),
|
|
422
|
+
REASON,
|
|
423
|
+
EXCEPTION,
|
|
424
|
+
]
|
|
425
|
+
|
|
426
|
+
self._serializers = _ActionSerializers(
|
|
427
|
+
start=_MessageSerializer(startFields),
|
|
428
|
+
success=_MessageSerializer(successFields),
|
|
429
|
+
# Failed action messages can have extra fields from exception
|
|
430
|
+
# extraction:
|
|
431
|
+
failure=_MessageSerializer(failureFields, allow_additional_fields=True),
|
|
432
|
+
)
|
|
433
|
+
|
|
434
|
+
def __call__(self, logger=None, **fields):
|
|
435
|
+
"""
|
|
436
|
+
Start a new L{eliot.Action} of this type with the given start fields.
|
|
437
|
+
|
|
438
|
+
You can use the result as a Python context manager, or use the
|
|
439
|
+
L{eliot.Action.finish} API.
|
|
440
|
+
|
|
441
|
+
LOG_DOSOMETHING = ActionType("yourapp:subsystem:dosomething",
|
|
442
|
+
[Field.forTypes("entry", [int], "")],
|
|
443
|
+
[Field.forTypes("result", [int], "")],
|
|
444
|
+
[],
|
|
445
|
+
"Do something with an entry.")
|
|
446
|
+
with LOG_DOSOMETHING(entry=x) as action:
|
|
447
|
+
do(x)
|
|
448
|
+
result = something(x * 2)
|
|
449
|
+
action.addSuccessFields(result=result)
|
|
450
|
+
|
|
451
|
+
Or perhaps:
|
|
452
|
+
|
|
453
|
+
action = LOG_DOSOMETHING(entry=x)
|
|
454
|
+
action.run(doSomething)
|
|
455
|
+
action.finish()
|
|
456
|
+
|
|
457
|
+
@param logger: A L{eliot.ILogger} provider to which the action's
|
|
458
|
+
messages will be written, or C{None} to use the default one.
|
|
459
|
+
|
|
460
|
+
@param fields: Extra fields to add to the message.
|
|
461
|
+
|
|
462
|
+
@rtype: L{eliot.Action}
|
|
463
|
+
"""
|
|
464
|
+
return self._start_action(logger, self.action_type, self._serializers, **fields)
|
|
465
|
+
|
|
466
|
+
def as_task(self, logger=None, **fields):
|
|
467
|
+
"""
|
|
468
|
+
Start a new L{eliot.Action} of this type as a task (i.e. top-level
|
|
469
|
+
action) with the given start fields.
|
|
470
|
+
|
|
471
|
+
See L{ActionType.__call__} for example of usage.
|
|
472
|
+
|
|
473
|
+
@param logger: A L{eliot.ILogger} provider to which the action's
|
|
474
|
+
messages will be written, or C{None} to use the default one.
|
|
475
|
+
|
|
476
|
+
@param fields: Extra fields to add to the message.
|
|
477
|
+
|
|
478
|
+
@rtype: L{eliot.Action}
|
|
479
|
+
"""
|
|
480
|
+
return self._startTask(logger, self.action_type, self._serializers, **fields)
|
|
481
|
+
|
|
482
|
+
# Backwards compatible variant:
|
|
483
|
+
asTask = as_task
|
|
484
|
+
|
|
485
|
+
|
|
486
|
+
__all__ = []
|
logxpy/_version.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
|
|
2
|
+
# This file was generated by 'versioneer.py' (0.29) from
|
|
3
|
+
# revision-control system data, or from the parent directory name of an
|
|
4
|
+
# unpacked source archive. Distribution tarballs contain a pre-generated copy
|
|
5
|
+
# of this file.
|
|
6
|
+
|
|
7
|
+
import json
|
|
8
|
+
|
|
9
|
+
version_json = '''
|
|
10
|
+
{
|
|
11
|
+
"date": "2026-02-05T18:23:29+0300",
|
|
12
|
+
"dirty": false,
|
|
13
|
+
"error": null,
|
|
14
|
+
"full-revisionid": "855e6b18d0ffbc4357e9a46d02e0f86a876b777c",
|
|
15
|
+
"version": "0.1.0"
|
|
16
|
+
}
|
|
17
|
+
''' # END VERSION_JSON
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def get_versions():
|
|
21
|
+
return json.loads(version_json)
|
logxpy/cli.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"""CLI commands."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
import asyncio
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
import typer
|
|
6
|
+
from rich.console import Console
|
|
7
|
+
|
|
8
|
+
app = typer.Typer(name="loggerx", help="Log viewer")
|
|
9
|
+
console = Console()
|
|
10
|
+
|
|
11
|
+
@app.command()
|
|
12
|
+
def tail(file: Path, follow: bool = True, level: str = "DEBUG"):
|
|
13
|
+
"""Tail log file."""
|
|
14
|
+
asyncio.run(_tail(file, follow, level))
|
|
15
|
+
|
|
16
|
+
@app.command()
|
|
17
|
+
def serve(file: Path, port: int = 8080, host: str = "localhost"):
|
|
18
|
+
"""Start WebSocket server."""
|
|
19
|
+
asyncio.run(_serve(file, host, port))
|
|
20
|
+
|
|
21
|
+
async def _tail(file: Path, follow: bool, level: str):
|
|
22
|
+
import orjson
|
|
23
|
+
from ._types import Level
|
|
24
|
+
min_level = Level[level.upper()]
|
|
25
|
+
|
|
26
|
+
async def read():
|
|
27
|
+
with open(file) as f:
|
|
28
|
+
if follow:
|
|
29
|
+
f.seek(0, 2) # End of file
|
|
30
|
+
while True:
|
|
31
|
+
line = f.readline()
|
|
32
|
+
if line:
|
|
33
|
+
yield orjson.loads(line)
|
|
34
|
+
elif follow:
|
|
35
|
+
await asyncio.sleep(0.1)
|
|
36
|
+
else:
|
|
37
|
+
break
|
|
38
|
+
|
|
39
|
+
async for record in read():
|
|
40
|
+
if Level[record.get('level', 'INFO')] >= min_level:
|
|
41
|
+
console.print(f"[{record['level']}] {record.get('message', '')} {record}")
|
|
42
|
+
|
|
43
|
+
async def _serve(file: Path, host: str, port: int):
|
|
44
|
+
from fastapi import FastAPI, WebSocket
|
|
45
|
+
import uvicorn
|
|
46
|
+
|
|
47
|
+
srv = FastAPI()
|
|
48
|
+
conns: list[WebSocket] = []
|
|
49
|
+
|
|
50
|
+
@srv.websocket("/ws")
|
|
51
|
+
async def ws(websocket: WebSocket):
|
|
52
|
+
await websocket.accept()
|
|
53
|
+
conns.append(websocket)
|
|
54
|
+
try:
|
|
55
|
+
while True: await websocket.receive_text()
|
|
56
|
+
except: conns.remove(websocket)
|
|
57
|
+
|
|
58
|
+
uvicorn.run(srv, host=host, port=port)
|
|
59
|
+
|
|
60
|
+
if __name__ == "__main__":
|
|
61
|
+
app()
|