- Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcalculator.py
232 lines (198 loc) · 8.02 KB
/
calculator.py
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
from __future__ importannotations
importlogging
fromannotated_loggerimportAnnotatedAdapter, AnnotatedLogger
fromannotated_logger.pluginsimport (
NameAdjusterPlugin,
NestedRemoverPlugin,
RemoverPlugin,
RuntimeAnnotationsPlugin,
)
classBoomError(Exception):
"""Boom."""
defruntime(_record: logging.LogRecord) ->str:
"""Return the string every time."""
return"this function is called every time"
annotated_logger=AnnotatedLogger(
annotations={
"extra": "new data",
"nested_extra": {"nested_key": {"double_nested_key": "value"}},
},
log_level=logging.DEBUG,
plugins=[
NameAdjusterPlugin(names=["joke"], prefix="cheezy_"),
NameAdjusterPlugin(names=["power"], postfix="_overwhelming"),
RemoverPlugin("taskName"),
NestedRemoverPlugin(["double_nested_key"]),
RuntimeAnnotationsPlugin({"runtime": runtime}),
],
name="annotated_logger.calculator",
)
annotate_logs=annotated_logger.annotate_logs
Number=int|float
classCalculator:
"""Calculator application with very limited (and weird) functionality.
This application is meant to highlight how to use the annotated-logger
package. It also serves as a way to test it.
"""
def__init__(self, first: Number, second: Number) ->None:
"""Create instance of example Calculator application.
The Calculator is very simple and has only two attributes
that serve as two operands in a calculation.
"""
self.first=first
self.second=second
self.boom: bool=False
defcheck_zero_division(self, annotated_logger: AnnotatedAdapter) ->None:
"""Annotate if divide will crash."""
will_crash=False
ifself.second==0:
will_crash=True
annotated_logger.annotate(will_crash=will_crash)
defwill_pass(
self,
annotated_logger: AnnotatedAdapter,
*args: ..., # noqa: ARG002
**kwargs: ..., # noqa: ARG002
) ->None:
"""Predict that the method will not crash."""
annotated_logger.annotate(will_crash=False)
defcheck_prediction_crashed_correctly(
self,
annotated_logger: AnnotatedAdapter,
*args: ..., # noqa: ARG002
**kwargs: ..., # noqa: ARG002
) ->None:
"""Check if the prediction was correct."""
ifself.boom:
annotated_logger.warning("boom")
raiseBoomError
annotated_logger.annotate(first_again=self.first)
prediction=annotated_logger.filter.annotations.get("will_crash")
success=annotated_logger.filter.annotations["success"]
annotated_logger.info(
"Prediction result", extra={"result": success!=prediction}
)
@annotated_logger.annotate_logs(
success_info=False,
pre_call=check_zero_division,
_typing_requested=True,
post_call=check_prediction_crashed_correctly,
)
defdivide(self, annotated_logger: AnnotatedAdapter) ->Number:
"""Divide self.first by self.second."""
annotated_logger.warning(
"If you divide by zero you'll create a singularity in the fabric of space-time!", # noqa: E501
extra={"joke": True},
)
try:
returnself.first/self.second
exceptZeroDivisionError:
# This tests that calls to `logger.exception` work with sentry
# Normally you would only use `logger` outside of a logged function
annotated_logger.exception("This will get sent to sentry if enabled.")
raise
@annotate_logs(
success_info=False,
_typing_requested=True,
pre_call=will_pass,
post_call=check_prediction_crashed_correctly,
)
defmultiply(
self, annotated_logger: AnnotatedAdapter, first: Number, second: Number
) ->Number:
"""Multiple the first parameter by the second parameter."""
annotated_logger.annotate(first=first, second=second)
returnfirst*second
@annotate_logs(success_info=False, provided=True, _typing_requested=True)
defmultiply2(
self, annotated_logger: AnnotatedAdapter, first: Number, second: Number
) ->Number:
"""Multiple the first parameter by the second parameter."""
annotated_logger.annotate(first=first)
annotated_logger.annotate(second=second)
returnfirst*second
@annotate_logs(_typing_requested=True)
defpower(
self, annotated_logger: AnnotatedAdapter, num: Number, power: int
) ->Number:
"""Raise num to the power power."""
annotated_logger.annotate(power=True)
base: Number=num
for_inrange(1, power):
base=self.multiply2(annotated_logger, base, num)
returnbase
@annotate_logs(success_info=False, _typing_requested=True)
defadd(self, annotated_logger: AnnotatedAdapter) ->Number:
# def add(self, *args, annotated_logger: AnnotatedAdapter) -> Number:
"""Add self.first and self.second."""
annotated_logger.annotate(first=self.first, second=self.second, foo="bar")
annotated_logger.info(
"This message will have 'other' as well as 'first' from the annotation above.", # noqa: E501
extra={"other": "value"},
)
annotated_logger.info(
"This message will have the 'first' annotation and the defaults, but not the 'other'"# noqa: E501
)
ifself.firstisNone:
annotated_logger.error("Must have a first value!")
self.first=0
returnself.first+self.second
@annotate_logs(_typing_requested=True)
defsubtract(self, annotated_logger: AnnotatedAdapter) ->Number:
"""Subtract the saved first from the saved second."""
annotated_logger.debug("Order does matter when subtracting")
returnself.first-self.second
@annotate_logs(_typing_requested=True)
definverse(self, annotated_logger: AnnotatedAdapter, num: Number) ->Number|bool:
"""Divide 1 by num."""
try:
return1/num
exceptZeroDivisionError:
annotated_logger.exception("Cannot divide by zero!")
returnFalse
@annotate_logs()
defpemdas_example(self) ->list[int]:
"""Check order of operations."""
return [2*3+4, 2* (3+4)]
@annotate_logs(_typing_requested=False)
defis_odd(self, number: Number) ->bool:
"""Check if number is odd."""
returnnumber%2==0
@annotate_logs(_typing_requested=True)
deffactorial(self, annotated_logger: AnnotatedAdapter, num: int) ->int:
"""Perform the factiorial function."""
annotated_logger.annotate(temp=True)
numbers=annotated_logger.iterator(
"factorial numbers", iter(range(1, num+1))
)
total=1
forninnumbers:
total=total*n
returntotal
@annotate_logs(_typing_requested=True)
defsensitive_factorial(
self, annotated_logger: AnnotatedAdapter, num: int, level: str="info"
) ->int:
"""Perform the factorial function, but don't log the value."""
numbers=annotated_logger.iterator(
"factorial numbers", iter(range(1, num+1)), value=False, level=level
)
total=1
forninnumbers:
total=total*n
returntotal
@classmethod
@annotate_logs(_typing_requested=True)
defis_math_cool(cls: type[Calculator], annotated_logger: AnnotatedAdapter) ->bool:
"""Answer the obvious question."""
cls.sanity_check(annotated_logger, "is_math_cool")
annotated_logger.info("What a silly question!")
returnTrue
@classmethod
@annotate_logs(_typing_requested=True, provided=True)
defsanity_check(
cls: type[Calculator], annotated_logger: AnnotatedAdapter, source: str
) ->None:
"""Reassures the caller they are sane."""
annotated_logger.annotate(sane=True)
annotated_logger.info("Checking sanity", extra={"source": source})