Skip to content

Commit c4135cb

Browse files
committed
chore: remove Logger deprecated code
1 parent 1b9c3e6 commit c4135cb

File tree

3 files changed

+3
-239
lines changed

3 files changed

+3
-239
lines changed
+2-2
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
"""Logging utility
22
"""
33
from ..helper.models import MetricUnit
4-
from .logger import Logger, log_metric, logger_inject_lambda_context, logger_setup
4+
from .logger import Logger
55

6-
__all__ = ["logger_setup", "logger_inject_lambda_context", "log_metric", "MetricUnit", "Logger"]
6+
__all__ = ["MetricUnit", "Logger"]

aws_lambda_powertools/logging/logger.py

+1-148
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,14 @@
11
import copy
22
import functools
3-
import itertools
43
import json
54
import logging
65
import os
76
import random
87
import sys
9-
import warnings
108
from distutils.util import strtobool
119
from typing import Any, Callable, Dict, Union
1210

13-
from ..helper.models import MetricUnit, build_lambda_context_model, build_metric_unit_from_str
11+
from ..helper.models import build_lambda_context_model
1412
from .exceptions import InvalidLoggerSamplingRateError
1513

1614
logger = logging.getLogger(__name__)
@@ -114,44 +112,6 @@ def format(self, record): # noqa: A003
114112
return json_record
115113

116114

117-
def logger_setup(
118-
service: str = None, level: str = None, sampling_rate: float = 0.0, legacy: bool = False, **kwargs
119-
) -> DeprecationWarning:
120-
"""DEPRECATED
121-
122-
This will be removed when GA - Use `aws_lambda_powertools.logging.logger.Logger` instead
123-
124-
Example
125-
-------
126-
**Logger class - Same UX**
127-
128-
from aws_lambda_powertools import Logger
129-
logger = Logger(service="payment") # same env var still applies
130-
131-
"""
132-
raise DeprecationWarning("Use Logger instead - This method will be removed when GA")
133-
134-
135-
def logger_inject_lambda_context(
136-
lambda_handler: Callable[[Dict, Any], Any] = None, log_event: bool = False
137-
) -> DeprecationWarning:
138-
"""DEPRECATED
139-
140-
This will be removed when GA - Use `aws_lambda_powertools.logging.logger.Logger` instead
141-
142-
Example
143-
-------
144-
**Logger class - Same UX**
145-
146-
from aws_lambda_powertools import Logger
147-
logger = Logger(service="payment") # same env var still applies
148-
@logger.inject_lambda_context
149-
def handler(evt, ctx):
150-
pass
151-
"""
152-
raise DeprecationWarning("Use Logger instead - This method will be removed when GA")
153-
154-
155115
def _is_cold_start() -> bool:
156116
"""Verifies whether is cold start
157117
@@ -170,113 +130,6 @@ def _is_cold_start() -> bool:
170130
return cold_start
171131

172132

173-
def log_metric(
174-
name: str, namespace: str, unit: MetricUnit, value: float = 0, service: str = "service_undefined", **dimensions,
175-
):
176-
"""Logs a custom metric in a statsD-esque format to stdout.
177-
178-
**This will be removed when GA - Use `aws_lambda_powertools.metrics.metrics.Metrics` instead**
179-
180-
Creating Custom Metrics synchronously impact on performance/execution time.
181-
Instead, log_metric prints a metric to CloudWatch Logs.
182-
That allows us to pick them up asynchronously via another Lambda function and create them as a metric.
183-
184-
NOTE: It takes up to 9 dimensions by default, and Metric units are conveniently available via MetricUnit Enum.
185-
If service is not passed as arg or via env var, "service_undefined" will be used as dimension instead.
186-
187-
**Output in CloudWatch Logs**: `MONITORING|<metric_value>|<metric_unit>|<metric_name>|<namespace>|<dimensions>`
188-
189-
Serverless Application Repository App that creates custom metric from this log output:
190-
https://serverlessrepo.aws.amazon.com/applications/arn:aws:serverlessrepo:us-east-1:374852340823:applications~async-custom-metrics
191-
192-
Environment variables
193-
---------------------
194-
POWERTOOLS_SERVICE_NAME: str
195-
service name
196-
197-
Parameters
198-
----------
199-
name : str
200-
metric name, by default None
201-
namespace : str
202-
metric namespace (e.g. application name), by default None
203-
unit : MetricUnit, by default MetricUnit.Count
204-
metric unit enum value (e.g. MetricUnit.Seconds), by default None\n
205-
API Info: https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_MetricDatum.html
206-
value : float, optional
207-
metric value, by default 0
208-
service : str, optional
209-
service name used as dimension, by default "service_undefined"
210-
dimensions: dict, optional
211-
keyword arguments as additional dimensions (e.g. `customer=customerId`)
212-
213-
Example
214-
-------
215-
**Log metric to count number of successful payments; define service via env var**
216-
217-
$ export POWERTOOLS_SERVICE_NAME="payment"
218-
from aws_lambda_powertools.logging import MetricUnit, log_metric
219-
log_metric(
220-
name="SuccessfulPayments",
221-
unit=MetricUnit.Count,
222-
value=1,
223-
namespace="DemoApp"
224-
)
225-
226-
**Log metric to count number of successful payments per campaign & customer**
227-
228-
from aws_lambda_powertools.logging import MetricUnit, log_metric
229-
log_metric(
230-
name="SuccessfulPayments",
231-
service="payment",
232-
unit=MetricUnit.Count,
233-
value=1,
234-
namespace="DemoApp",
235-
campaign=campaign_id,
236-
customer=customer_id
237-
)
238-
"""
239-
240-
warnings.warn(message="This method will be removed in GA; use Metrics instead", category=DeprecationWarning)
241-
logger.debug(f"Building new custom metric. Name: {name}, Unit: {unit}, Value: {value}, Dimensions: {dimensions}")
242-
service = os.getenv("POWERTOOLS_SERVICE_NAME") or service
243-
dimensions = __build_dimensions(**dimensions)
244-
unit = build_metric_unit_from_str(unit)
245-
246-
metric = f"MONITORING|{value}|{unit.name}|{name}|{namespace}|service={service}"
247-
if dimensions:
248-
metric = f"MONITORING|{value}|{unit.name}|{name}|{namespace}|service={service},{dimensions}"
249-
250-
print(metric)
251-
252-
253-
def __build_dimensions(**dimensions) -> str:
254-
"""Builds correct format for custom metric dimensions from kwargs
255-
256-
Parameters
257-
----------
258-
dimensions: dict, optional
259-
additional dimensions
260-
261-
Returns
262-
-------
263-
str
264-
Dimensions in the form of "key=value,key2=value2"
265-
"""
266-
MAX_DIMENSIONS = 10
267-
dimension = ""
268-
269-
# CloudWatch accepts a max of 10 dimensions per metric
270-
# We include service name as a dimension
271-
# so we take up to 9 values as additional dimensions
272-
# before we convert everything to a string of key=value
273-
dimensions_partition = dict(itertools.islice(dimensions.items(), MAX_DIMENSIONS))
274-
dimensions_list = [dimension + "=" + value for dimension, value in dimensions_partition.items() if value]
275-
dimension = ",".join(dimensions_list)
276-
277-
return dimension
278-
279-
280133
class Logger(logging.Logger):
281134
"""Creates and setups a logger to format statements in JSON.
282135

tests/functional/test_logger.py

-89
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@
66
import pytest
77

88
from aws_lambda_powertools import Logger, Tracer
9-
from aws_lambda_powertools.logging import MetricUnit, log_metric, logger_inject_lambda_context, logger_setup
109
from aws_lambda_powertools.logging.exceptions import InvalidLoggerSamplingRateError
1110
from aws_lambda_powertools.logging.logger import JsonFormatter, set_package_logger
1211

@@ -236,68 +235,6 @@ def handler(event, context):
236235
assert fourth_log["cold_start"] is False
237236

238237

239-
def test_log_metric(capsys):
240-
# GIVEN a service, unit and value have been provided
241-
# WHEN log_metric is called
242-
# THEN custom metric line should be match given values
243-
log_metric(
244-
service="payment", name="test_metric", unit=MetricUnit.Seconds, value=60, namespace="DemoApp",
245-
)
246-
expected = "MONITORING|60|Seconds|test_metric|DemoApp|service=payment\n"
247-
captured = capsys.readouterr()
248-
249-
assert captured.out == expected
250-
251-
252-
def test_log_metric_env_var(monkeypatch, capsys):
253-
# GIVEN a service, unit and value have been provided
254-
# WHEN log_metric is called
255-
# THEN custom metric line should be match given values
256-
service_name = "payment"
257-
monkeypatch.setenv("POWERTOOLS_SERVICE_NAME", service_name)
258-
259-
log_metric(name="test_metric", unit=MetricUnit.Seconds, value=60, namespace="DemoApp")
260-
expected = "MONITORING|60|Seconds|test_metric|DemoApp|service=payment\n"
261-
captured = capsys.readouterr()
262-
263-
assert captured.out == expected
264-
265-
266-
def test_log_metric_multiple_dimensions(capsys):
267-
# GIVEN multiple optional dimensions are provided
268-
# WHEN log_metric is called
269-
# THEN dimensions should appear as dimenion=value
270-
log_metric(
271-
name="test_metric", unit=MetricUnit.Seconds, value=60, customer="abc", charge_id="123", namespace="DemoApp",
272-
)
273-
expected = "MONITORING|60|Seconds|test_metric|DemoApp|service=service_undefined,customer=abc,charge_id=123\n"
274-
captured = capsys.readouterr()
275-
276-
assert captured.out == expected
277-
278-
279-
@pytest.mark.parametrize(
280-
"invalid_input,expected",
281-
[
282-
({"unit": "seconds"}, "MONITORING|0|Seconds|test_metric|DemoApp|service=service_undefined\n",),
283-
(
284-
{"unit": "Seconds", "customer": None, "charge_id": "123", "payment_status": ""},
285-
"MONITORING|0|Seconds|test_metric|DemoApp|service=service_undefined,charge_id=123\n",
286-
),
287-
],
288-
ids=["metric unit as string lower case", "empty dimension value"],
289-
)
290-
def test_log_metric_partially_correct_args(capsys, invalid_input, expected):
291-
# GIVEN invalid arguments are provided such as empty dimension values and metric units in strings
292-
# WHEN log_metric is called
293-
# THEN default values should be used such as "Count" as a unit, invalid dimensions not included
294-
# and no exception raised
295-
log_metric(name="test_metric", namespace="DemoApp", **invalid_input)
296-
captured = capsys.readouterr()
297-
298-
assert captured.out == expected
299-
300-
301238
def test_package_logger(capsys):
302239

303240
set_package_logger()
@@ -315,32 +252,6 @@ def test_package_logger_format(stdout, capsys):
315252
assert "test" in output["formatter"]
316253

317254

318-
@pytest.mark.parametrize(
319-
"invalid_input,expected",
320-
[({"unit": "Blah"}, ValueError), ({"unit": None}, ValueError), ({}, TypeError)],
321-
ids=["invalid metric unit as str", "unit as None", "missing required unit"],
322-
)
323-
def test_log_metric_invalid_unit(capsys, invalid_input, expected):
324-
# GIVEN invalid units are provided
325-
# WHEN log_metric is called
326-
# THEN ValueError exception should be raised
327-
328-
with pytest.raises(expected):
329-
log_metric(name="test_metric", namespace="DemoApp", **invalid_input)
330-
331-
332-
def test_logger_setup_deprecated():
333-
# Should be removed when GA
334-
with pytest.raises(DeprecationWarning):
335-
logger_setup()
336-
337-
338-
def test_logger_inject_lambda_context_deprecated():
339-
# Should be removed when GA
340-
with pytest.raises(DeprecationWarning):
341-
logger_inject_lambda_context()
342-
343-
344255
def test_logger_append_duplicated(stdout):
345256
logger = Logger(stream=stdout, request_id="value")
346257
logger.structure_logs(append=True, request_id="new_value")

0 commit comments

Comments
 (0)