Skip to content

Commit 443ffba

Browse files
author
Artem Krivonos
committed
Refactor LambdaLogFormat
1 parent 9b62086 commit 443ffba

File tree

3 files changed

+29
-22
lines changed

3 files changed

+29
-22
lines changed

awslambdaric/bootstrap.py

Lines changed: 10 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
INVOCATION_LOGGING_CONTEXT,
1818
JsonFormatter,
1919
DATETIME_FORMAT,
20+
LambdaLogFormat,
2021
)
2122
from .lambda_runtime_marshaller import to_json
2223

@@ -106,7 +107,7 @@ def replace_line_indentation(line, indent_char, new_indent_char):
106107

107108

108109
def log_error(error_result, log_sink):
109-
if AWS_LAMBDA_LOG_FORMAT == "JSON":
110+
if AWS_LAMBDA_LOG_FORMAT == LambdaLogFormat.JSON:
110111
log_error_json(error_result, log_sink)
111112
else:
112113
log_error_text(error_result, log_sink)
@@ -294,7 +295,7 @@ def emit(self, record: logging.LogRecord):
294295
self.log_sink.log(
295296
msg,
296297
log_level=record.levelno,
297-
log_format=getattr(record, "log_format", "TEXT"),
298+
log_format=getattr(record, "log_format", LambdaLogFormat.TEXT),
298299
)
299300

300301

@@ -336,7 +337,7 @@ def __enter__(self):
336337
def __exit__(self, exc_type, exc_value, exc_tb):
337338
pass
338339

339-
def log(self, msg, log_level=logging.NOTSET, log_format="TEXT"):
340+
def log(self, msg, log_level=logging.NOTSET, log_format=LambdaLogFormat.TEXT):
340341
sys.stdout.write(msg)
341342

342343
def log_error(self, message_lines, log_level=logging.ERROR):
@@ -383,21 +384,11 @@ def __exit__(self, exc_type, exc_value, exc_tb):
383384

384385
def set_log_level(self, frame_type, log_level):
385386
mask = self.LEVEL_TO_MASK.get(log_level, self.DEFAULT_LEVEL_MASK)
386-
frame_type |= mask
387-
388-
return frame_type
389-
390-
@staticmethod
391-
def set_log_format(frame_type, log_format):
392-
if log_format == "JSON":
393-
mask = 0b00
394-
else:
395-
mask = 0b01
396387
return frame_type | mask
397388

398-
def log(self, msg, log_level=logging.NOTSET, log_format="TEXT"):
389+
def log(self, msg, log_level=logging.NOTSET, log_format=LambdaLogFormat.TEXT):
399390
frame_type = self.set_log_level(self.frame_type, log_level)
400-
frame_type = self.set_log_format(frame_type, log_format)
391+
frame_type = frame_type | log_format
401392

402393
encoded_msg = msg.encode("utf8")
403394
timestamp = int(time.time_ns() / 1000) # UNIX timestamp in microseconds
@@ -432,7 +423,9 @@ def create_log_sink():
432423
return StandardLogSink()
433424

434425

435-
AWS_LAMBDA_LOG_FORMAT = os.environ.get("AWS_LAMBDA_LOG_FORMAT", "TEXT")
426+
AWS_LAMBDA_LOG_FORMAT = LambdaLogFormat.from_str(
427+
os.environ.get("AWS_LAMBDA_LOG_FORMAT", "TEXT")
428+
)
436429
AWS_LAMBDA_LOG_LEVEL = os.environ.get("AWS_LAMBDA_LOG_LEVEL")
437430
_GLOBAL_AWS_REQUEST_ID = None
438431

@@ -442,7 +435,7 @@ def setup_logging(log_format, log_level, log_sink):
442435
logging.Formatter.converter = time.gmtime
443436
logger = logging.getLogger()
444437
logger_handler = LambdaLoggerHandler(log_sink)
445-
if log_format == "JSON":
438+
if log_format == LambdaLogFormat.JSON:
446439
logger_handler.setFormatter(JsonFormatter())
447440
else:
448441
logger_handler.setFormatter(

awslambdaric/lambda_runtime_log_utils.py

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
import logging
66
import traceback
7+
from enum import IntFlag
78

89
from .lambda_runtime_marshaller import to_json
910

@@ -34,6 +35,17 @@
3435
}
3536

3637

38+
class LambdaLogFormat(IntFlag):
39+
JSON = 0b0
40+
TEXT = 0b1
41+
42+
@classmethod
43+
def from_str(cls, value):
44+
if value == "JSON":
45+
return cls.JSON
46+
return cls.TEXT
47+
48+
3749
class JsonFormatter(logging.Formatter):
3850
def __init__(self):
3951
super().__init__(datefmt=DATETIME_FORMAT, validate=False)
@@ -66,7 +78,7 @@ def format_location(record: logging.LogRecord):
6678
return f"{record.pathname}:{record.funcName}:{record.lineno}"
6779

6880
def format(self, record: logging.LogRecord) -> str:
69-
record.log_format = "JSON"
81+
record.log_format = LambdaLogFormat.JSON
7082

7183
result = {
7284
"timestamp": self.formatTime(record, self.datefmt),

tests/test_bootstrap.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323
lambda_invocation_logs_update,
2424
INVOCATION_LOGGING_CONTEXT,
2525
INSTANCE_LOGGING_CONTEXT,
26+
LambdaLogFormat,
2627
)
2728

2829

@@ -1146,9 +1147,8 @@ def test_log_level_frame_type(self):
11461147

11471148
def test_log_format_frame_type(self):
11481149
test_cases = [
1149-
("TEXT", 0xA55A0003),
1150-
("WRONG_FORMAT", 0xA55A0003),
1151-
("JSON", 0xA55A0002),
1150+
(LambdaLogFormat.TEXT, 0xA55A0003),
1151+
(LambdaLogFormat.JSON, 0xA55A0002),
11521152
]
11531153

11541154
for fmt, expected_frame_type in test_cases:
@@ -1228,7 +1228,9 @@ def test_multiple_frame(self):
12281228
class TestLogging(unittest.TestCase):
12291229
@classmethod
12301230
def setUpClass(cls) -> None:
1231-
bootstrap.setup_logging("JSON", "INFO", bootstrap.StandardLogSink())
1231+
bootstrap.setup_logging(
1232+
LambdaLogFormat.from_str("JSON"), "INFO", bootstrap.StandardLogSink()
1233+
)
12321234

12331235
def tearDown(self) -> None:
12341236
INVOCATION_LOGGING_CONTEXT.clear()

0 commit comments

Comments
 (0)