Skip to content

Commit e21f2b5

Browse files
Switch from py2 type comments to py3 type hint
Resolves elastic#79
1 parent 366064d commit e21f2b5

File tree

3 files changed

+39
-67
lines changed

3 files changed

+39
-67
lines changed

ecs_logging/_stdlib.py

Lines changed: 27 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,6 @@
2222

2323
from ._meta import ECS_VERSION
2424
from ._utils import (
25-
TYPE_CHECKING,
2625
collections_abc,
2726
de_dot,
2827
flatten_dict,
@@ -31,13 +30,12 @@
3130
merge_dicts,
3231
)
3332

34-
if TYPE_CHECKING:
35-
from typing import Any, Callable, Dict, Optional, Sequence
33+
from typing import Any, Callable, Dict, Optional, Sequence
3634

37-
try:
38-
from typing import Literal, Union # type: ignore
39-
except ImportError:
40-
from typing_extensions import Literal, Union # type: ignore
35+
try:
36+
from typing import Literal, Union # type: ignore
37+
except ImportError:
38+
from typing_extensions import Literal, Union # type: ignore
4139

4240

4341
# Load the attributes of a LogRecord so if some are
@@ -78,16 +76,15 @@ class StdlibFormatter(logging.Formatter):
7876
converter = time.gmtime
7977

8078
def __init__(
81-
self, # type: Any
82-
fmt=None, # type: Optional[str]
83-
datefmt=None, # type: Optional[str]
84-
style="%", # type: Union[Literal["%"], Literal["{"], Literal["$"]]
85-
validate=None, # type: Optional[bool]
86-
stack_trace_limit=None, # type: Optional[int]
87-
extra=None, # type: Optional[Dict[str, Any]]
88-
exclude_fields=(), # type: Sequence[str]
89-
):
90-
# type: (...) -> None
79+
self,
80+
fmt: Optional[str] = None,
81+
datefmt: Optional[str] = None,
82+
style: Union[Literal["%"], Literal["{"], Literal["$"]] = "%",
83+
validate: Optional[bool] = None,
84+
stack_trace_limit: Optional[int] = None,
85+
extra: Optional[Dict[str, Any]] = None,
86+
exclude_fields: Sequence[str] = (),
87+
) -> None:
9188
"""Initialize the ECS formatter.
9289
9390
:param int stack_trace_limit:
@@ -137,8 +134,7 @@ def __init__(
137134
self._exclude_fields = frozenset(exclude_fields)
138135
self._stack_trace_limit = stack_trace_limit
139136

140-
def _record_error_type(self, record):
141-
# type: (logging.LogRecord) -> Optional[str]
137+
def _record_error_type(self, record: logging.LogRecord) -> Optional[str]:
142138
exc_info = record.exc_info
143139
if not exc_info:
144140
# exc_info is either an iterable or bool. If it doesn't
@@ -151,8 +147,7 @@ def _record_error_type(self, record):
151147
return exc_info[0].__name__
152148
return None
153149

154-
def _record_error_message(self, record):
155-
# type: (logging.LogRecord) -> Optional[str]
150+
def _record_error_message(self, record: logging.LogRecord) -> Optional[str]:
156151
exc_info = record.exc_info
157152
if not exc_info:
158153
# exc_info is either an iterable or bool. If it doesn't
@@ -165,13 +160,11 @@ def _record_error_message(self, record):
165160
return str(exc_info[1])
166161
return None
167162

168-
def format(self, record):
169-
# type: (logging.LogRecord) -> str
163+
def format(self, record: logging.LogRecord) -> str:
170164
result = self.format_to_ecs(record)
171165
return json_dumps(result)
172166

173-
def format_to_ecs(self, record):
174-
# type: (logging.LogRecord) -> Dict[str, Any]
167+
def format_to_ecs(self, record: logging.LogRecord) -> Dict[str, Any]:
175168
"""Function that can be overridden to add additional fields to
176169
(or remove fields from) the JSON before being dumped into a string.
177170
@@ -185,7 +178,7 @@ def format_to_ecs(self, record):
185178
return result
186179
"""
187180

188-
extractors = {
181+
extractors: Dict[str, Callable[[logging.LogRecord], Any]] = {
189182
"@timestamp": self._record_timestamp,
190183
"ecs.version": lambda _: ECS_VERSION,
191184
"log.level": lambda r: (r.levelname.lower() if r.levelname else None),
@@ -201,9 +194,9 @@ def format_to_ecs(self, record):
201194
"error.type": self._record_error_type,
202195
"error.message": self._record_error_message,
203196
"error.stack_trace": self._record_error_stack_trace,
204-
} # type: Dict[str, Callable[[logging.LogRecord],Any]]
197+
}
205198

206-
result = {} # type: Dict[str, Any]
199+
result: Dict[str, Any] = {}
207200
for field in set(extractors.keys()).difference(self._exclude_fields):
208201
if self._is_field_excluded(field):
209202
continue
@@ -257,28 +250,26 @@ def format_to_ecs(self, record):
257250
return result
258251

259252
@lru_cache()
260-
def _is_field_excluded(self, field):
261-
# type: (str) -> bool
253+
def _is_field_excluded(self, field: str) -> bool:
262254
field_path = []
263255
for path in field.split("."):
264256
field_path.append(path)
265257
if ".".join(field_path) in self._exclude_fields:
266258
return True
267259
return False
268260

269-
def _record_timestamp(self, record):
270-
# type: (logging.LogRecord) -> str
261+
def _record_timestamp(self, record: logging.LogRecord) -> str:
271262
return "%s.%03dZ" % (
272263
self.formatTime(record, datefmt="%Y-%m-%dT%H:%M:%S"),
273264
record.msecs,
274265
)
275266

276-
def _record_attribute(self, attribute):
277-
# type: (str) -> Callable[[logging.LogRecord], Optional[Any]]
267+
def _record_attribute(
268+
self, attribute: str
269+
) -> Callable[[logging.LogRecord], Optional[Any]]:
278270
return lambda r: getattr(r, attribute, None)
279271

280-
def _record_error_stack_trace(self, record):
281-
# type: (logging.LogRecord) -> Optional[str]
272+
def _record_error_stack_trace(self, record: logging.LogRecord) -> Optional[str]:
282273
# Using stack_info=True will add 'error.stack_trace' even
283274
# if the type is not 'error', exc_info=True only gathers
284275
# when there's an active exception.

ecs_logging/_structlog.py

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -18,17 +18,15 @@
1818
import time
1919
import datetime
2020
from ._meta import ECS_VERSION
21-
from ._utils import json_dumps, normalize_dict, TYPE_CHECKING
21+
from ._utils import json_dumps, normalize_dict
2222

23-
if TYPE_CHECKING:
24-
from typing import Any, Dict
23+
from typing import Any, Dict
2524

2625

2726
class StructlogFormatter:
2827
"""ECS formatter for the ``structlog`` module"""
2928

30-
def __call__(self, _, name, event_dict):
31-
# type: (Any, str, Dict[str, Any]) -> str
29+
def __call__(self, _: Any, name: str, event_dict: Dict[str, Any]) -> str:
3230

3331
# Handle event -> message now so that stuff like `event.dataset` doesn't
3432
# cause problems down the line
@@ -38,8 +36,7 @@ def __call__(self, _, name, event_dict):
3836
event_dict = self.format_to_ecs(event_dict)
3937
return json_dumps(event_dict)
4038

41-
def format_to_ecs(self, event_dict):
42-
# type: (Dict[str, Any]) -> Dict[str, Any]
39+
def format_to_ecs(self, event_dict: Dict[str, Any]) -> Dict[str, Any]:
4340
if "@timestamp" not in event_dict:
4441
event_dict["@timestamp"] = (
4542
datetime.datetime.utcfromtimestamp(time.time()).strftime(

ecs_logging/_utils.py

Lines changed: 8 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -17,17 +17,9 @@
1717

1818
import json
1919
import functools
20+
import typing
2021

21-
try:
22-
import typing
23-
24-
TYPE_CHECKING = typing.TYPE_CHECKING
25-
except ImportError:
26-
typing = None # type: ignore
27-
TYPE_CHECKING = False
28-
29-
if TYPE_CHECKING:
30-
from typing import Any, Dict
22+
from typing import Any, Dict
3123

3224
try:
3325
import collections.abc as collections_abc
@@ -46,14 +38,12 @@
4638
"de_dot",
4739
"merge_dicts",
4840
"json_dumps",
49-
"TYPE_CHECKING",
5041
"typing",
5142
"lru_cache",
5243
]
5344

5445

55-
def flatten_dict(value):
56-
# type: (typing.Mapping[str, Any]) -> Dict[str, Any]
46+
def flatten_dict(value: typing.Mapping[str, Any]) -> Dict[str, Any]:
5747
"""Adds dots to all nested fields in dictionaries.
5848
Raises an error if there are entries which are represented
5949
with different forms of nesting. (ie {"a": {"b": 1}, "a.b": 2})
@@ -77,8 +67,7 @@ def flatten_dict(value):
7767
return top_level
7868

7969

80-
def normalize_dict(value):
81-
# type: (Dict[str, Any]) -> Dict[str, Any]
70+
def normalize_dict(value: Dict[str, Any]) -> Dict[str, Any]:
8271
"""Expands all dotted names to nested dictionaries"""
8372
if not isinstance(value, dict):
8473
return value
@@ -94,8 +83,7 @@ def normalize_dict(value):
9483
return value
9584

9685

97-
def de_dot(dot_string, msg):
98-
# type: (str, Any) -> Dict[str, Any]
86+
def de_dot(dot_string: str, msg: Any) -> Dict[str, Any]:
9987
"""Turn value and dotted string key into a nested dictionary"""
10088
arr = dot_string.split(".")
10189
ret = {arr[-1]: msg}
@@ -104,8 +92,7 @@ def de_dot(dot_string, msg):
10492
return ret
10593

10694

107-
def merge_dicts(from_, into):
108-
# type: (Dict[Any, Any], Dict[Any, Any]) -> Dict[Any, Any]
95+
def merge_dicts(from_: Dict[Any, Any], into: Dict[Any, Any]) -> Dict[Any, Any]:
10996
"""Merge deeply nested dictionary structures.
11097
When called has side-effects within 'destination'.
11198
"""
@@ -125,9 +112,7 @@ def merge_dicts(from_, into):
125112
return into
126113

127114

128-
def json_dumps(value):
129-
# type: (Dict[str, Any]) -> str
130-
115+
def json_dumps(value: Dict[str, Any]) -> str:
131116
# Ensure that the first three fields are '@timestamp',
132117
# 'log.level', and 'message' per ECS spec
133118
ordered_fields = []
@@ -175,8 +160,7 @@ def json_dumps(value):
175160
return json_dumps(value)
176161

177162

178-
def _json_dumps_fallback(value):
179-
# type: (Any) -> Any
163+
def _json_dumps_fallback(value: Any) -> Any:
180164
"""
181165
Fallback handler for json.dumps to handle objects json doesn't know how to
182166
serialize.

0 commit comments

Comments
 (0)