From 995bb59cccb1e6eb19965776bf13c75bb84b76c6 Mon Sep 17 00:00:00 2001 From: Alex Boten Date: Tue, 21 Sep 2021 11:24:20 -0700 Subject: [PATCH] use f-strings instead of format --- .../exporter/datadog/exporter.py | 4 +-- .../aiohttp_client/__init__.py | 2 +- .../tests/test_aiohttp_client_integration.py | 28 ++++++--------- .../instrumentation/asgi/__init__.py | 5 +-- .../instrumentation/boto/__init__.py | 2 +- .../tests/test_boto_instrumentation.py | 2 +- .../instrumentation/botocore/__init__.py | 2 +- .../instrumentation/celery/__init__.py | 4 +-- .../instrumentation/celery/utils.py | 2 +- .../tests/test_utils.py | 2 +- .../instrumentation/django/middleware.py | 4 +-- .../tests/test_middleware.py | 5 +-- .../instrumentation/elasticsearch/__init__.py | 3 +- .../tests/test_elasticsearch.py | 2 +- .../instrumentation/falcon/__init__.py | 5 ++- .../tests/test_falcon.py | 9 ++--- .../tests/test_programmatic.py | 5 +-- .../instrumentation/grpc/_client.py | 2 +- .../instrumentation/grpc/_server.py | 7 ++-- .../tests/_server.py | 2 +- .../tests/test_server_interceptor.py | 24 ++++++------- .../instrumentation/httpx/__init__.py | 2 +- .../instrumentation/logging/__init__.py | 8 ++--- .../instrumentation/pymemcache/__init__.py | 6 ++-- .../tests/test_pymemcache.py | 2 +- .../tests/test_programmatic.py | 5 +-- .../instrumentation/redis/util.py | 2 +- .../instrumentation/requests/__init__.py | 2 +- .../instrumentation/sklearn/__init__.py | 2 +- .../instrumentation/tornado/__init__.py | 2 +- .../instrumentation/tornado/client.py | 2 +- .../tests/test_instrumentation.py | 5 +-- .../instrumentation/urllib/__init__.py | 8 ++--- .../instrumentation/urllib3/__init__.py | 2 +- .../instrumentation/wsgi/__init__.py | 2 +- scripts/eachdist.py | 35 ++++++++----------- scripts/generate_instrumentation_readme.py | 4 +-- .../aws/trace/propagation/aws_xray_format.py | 4 +-- .../src/opentelemetry/util/http/__init__.py | 4 +-- 39 files changed, 90 insertions(+), 128 deletions(-) diff --git a/exporter/opentelemetry-exporter-datadog/src/opentelemetry/exporter/datadog/exporter.py b/exporter/opentelemetry-exporter-datadog/src/opentelemetry/exporter/datadog/exporter.py index f0fcbcf2c8..c530f86e63 100644 --- a/exporter/opentelemetry-exporter-datadog/src/opentelemetry/exporter/datadog/exporter.py +++ b/exporter/opentelemetry-exporter-datadog/src/opentelemetry/exporter/datadog/exporter.py @@ -102,7 +102,7 @@ def agent_writer(self): self._agent_writer = AgentWriter(uds_path=url_parsed.path) else: raise ValueError( - "Unknown scheme `%s` for agent URL" % url_parsed.scheme + f"Unknown scheme `{url_parsed.scheme}` for agent URL" ) return self._agent_writer @@ -225,7 +225,7 @@ def _get_span_name(span): ) span_kind_name = span.kind.name if span.kind else None name = ( - "{}.{}".format(instrumentation_name, span_kind_name) + f"{instrumentation_name}.{span_kind_name}" if instrumentation_name and span_kind_name else span.name ) diff --git a/instrumentation/opentelemetry-instrumentation-aiohttp-client/src/opentelemetry/instrumentation/aiohttp_client/__init__.py b/instrumentation/opentelemetry-instrumentation-aiohttp-client/src/opentelemetry/instrumentation/aiohttp_client/__init__.py index 92af87f77a..eba8a41501 100644 --- a/instrumentation/opentelemetry-instrumentation-aiohttp-client/src/opentelemetry/instrumentation/aiohttp_client/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-aiohttp-client/src/opentelemetry/instrumentation/aiohttp_client/__init__.py @@ -175,7 +175,7 @@ async def on_request_start( return http_method = params.method.upper() - request_span_name = "HTTP {}".format(http_method) + request_span_name = f"HTTP {http_method}" trace_config_ctx.span = trace_config_ctx.tracer.start_span( request_span_name, kind=SpanKind.CLIENT, diff --git a/instrumentation/opentelemetry-instrumentation-aiohttp-client/tests/test_aiohttp_client_integration.py b/instrumentation/opentelemetry-instrumentation-aiohttp-client/tests/test_aiohttp_client_integration.py index 44a5ee0f43..aede6228b6 100644 --- a/instrumentation/opentelemetry-instrumentation-aiohttp-client/tests/test_aiohttp_client_integration.py +++ b/instrumentation/opentelemetry-instrumentation-aiohttp-client/tests/test_aiohttp_client_integration.py @@ -92,7 +92,7 @@ def _http_request( method: str = "GET", status_code: int = HTTPStatus.OK, request_handler: typing.Callable = None, - **kwargs + **kwargs, ) -> typing.Tuple[str, int]: """Helper to start an aiohttp test server and send an actual HTTP request to it.""" @@ -132,9 +132,7 @@ def test_status_codes(self): (span_status, None), { SpanAttributes.HTTP_METHOD: "GET", - SpanAttributes.HTTP_URL: "http://{}:{}/test-path?query=param#foobar".format( - host, port - ), + SpanAttributes.HTTP_URL: f"http://{host}:{port}/test-path?query=param#foobar", SpanAttributes.HTTP_STATUS_CODE: int( status_code ), @@ -167,7 +165,7 @@ def test_hooks(self): expected = "PATCH - /some/path" def request_hook(span: Span, params: aiohttp.TraceRequestStartParams): - span.update_name("{} - {}".format(params.method, params.url.path)) + span.update_name(f"{params.method} - {params.url.path}") def response_hook( span: Span, @@ -198,7 +196,7 @@ def response_hook( ) self.assertEqual( span.attributes[SpanAttributes.HTTP_URL], - "http://{}:{}{}".format(host, port, path), + f"http://{host}:{port}{path}", ) self.assertEqual( span.attributes[SpanAttributes.HTTP_STATUS_CODE], HTTPStatus.OK @@ -227,9 +225,7 @@ def strip_query_params(url: yarl.URL) -> str: (StatusCode.UNSET, None), { SpanAttributes.HTTP_METHOD: "GET", - SpanAttributes.HTTP_URL: "http://{}:{}/some/path".format( - host, port - ), + SpanAttributes.HTTP_URL: f"http://{host}:{port}/some/path", SpanAttributes.HTTP_STATUS_CODE: int(HTTPStatus.OK), }, ) @@ -290,9 +286,7 @@ async def request_handler(request): (StatusCode.ERROR, None), { SpanAttributes.HTTP_METHOD: "GET", - SpanAttributes.HTTP_URL: "http://{}:{}/test_timeout".format( - host, port - ), + SpanAttributes.HTTP_URL: f"http://{host}:{port}/test_timeout", }, ) ] @@ -319,9 +313,7 @@ async def request_handler(request): (StatusCode.ERROR, None), { SpanAttributes.HTTP_METHOD: "GET", - SpanAttributes.HTTP_URL: "http://{}:{}/test_too_many_redirects".format( - host, port - ), + SpanAttributes.HTTP_URL: f"http://{host}:{port}/test_too_many_redirects", }, ) ] @@ -399,7 +391,7 @@ def test_instrument(self): span = self.assert_spans(1) self.assertEqual("GET", span.attributes[SpanAttributes.HTTP_METHOD]) self.assertEqual( - "http://{}:{}/test-path".format(host, port), + f"http://{host}:{port}/test-path", span.attributes[SpanAttributes.HTTP_URL], ) self.assertEqual(200, span.attributes[SpanAttributes.HTTP_STATUS_CODE]) @@ -502,13 +494,13 @@ def strip_query_params(url: yarl.URL) -> str: ) span = self.assert_spans(1) self.assertEqual( - "http://{}:{}/test-path".format(host, port), + f"http://{host}:{port}/test-path", span.attributes[SpanAttributes.HTTP_URL], ) def test_hooks(self): def request_hook(span: Span, params: aiohttp.TraceRequestStartParams): - span.update_name("{} - {}".format(params.method, params.url.path)) + span.update_name(f"{params.method} - {params.url.path}") def response_hook( span: Span, diff --git a/instrumentation/opentelemetry-instrumentation-asgi/src/opentelemetry/instrumentation/asgi/__init__.py b/instrumentation/opentelemetry-instrumentation-asgi/src/opentelemetry/instrumentation/asgi/__init__.py index fe829945e7..83bfc42f11 100644 --- a/instrumentation/opentelemetry-instrumentation-asgi/src/opentelemetry/instrumentation/asgi/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-asgi/src/opentelemetry/instrumentation/asgi/__init__.py @@ -152,8 +152,9 @@ def get_default_span_details(scope: dict) -> Tuple[str, dict]: Returns: a tuple of the span name, and any attributes to attach to the span. """ - span_name = scope.get("path", "").strip() or "HTTP {}".format( - scope.get("method", "").strip() + span_name = ( + scope.get("path", "").strip() + or f"HTTP {scope.get('method', '').strip()}" ) return span_name, {} diff --git a/instrumentation/opentelemetry-instrumentation-boto/src/opentelemetry/instrumentation/boto/__init__.py b/instrumentation/opentelemetry-instrumentation-boto/src/opentelemetry/instrumentation/boto/__init__.py index 02e04ffa80..fcad7f635c 100644 --- a/instrumentation/opentelemetry-instrumentation-boto/src/opentelemetry/instrumentation/boto/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-boto/src/opentelemetry/instrumentation/boto/__init__.py @@ -123,7 +123,7 @@ def _common_request( # pylint: disable=too-many-locals endpoint_name = getattr(instance, "host").split(".")[0] with self._tracer.start_as_current_span( - "{}.command".format(endpoint_name), kind=SpanKind.CONSUMER, + f"{endpoint_name}.command", kind=SpanKind.CONSUMER, ) as span: span.set_attribute("endpoint", endpoint_name) if args: diff --git a/instrumentation/opentelemetry-instrumentation-boto/tests/test_boto_instrumentation.py b/instrumentation/opentelemetry-instrumentation-boto/tests/test_boto_instrumentation.py index dda22ba448..32347e5693 100644 --- a/instrumentation/opentelemetry-instrumentation-boto/tests/test_boto_instrumentation.py +++ b/instrumentation/opentelemetry-instrumentation-boto/tests/test_boto_instrumentation.py @@ -35,7 +35,7 @@ def assert_span_http_status_code(span, code): """Assert on the span's 'http.status_code' tag""" tag = span.attributes[SpanAttributes.HTTP_STATUS_CODE] - assert tag == code, "%r != %r" % (tag, code) + assert tag == code, f"{tag} != {code}" class TestBotoInstrumentor(TestBase): diff --git a/instrumentation/opentelemetry-instrumentation-botocore/src/opentelemetry/instrumentation/botocore/__init__.py b/instrumentation/opentelemetry-instrumentation-botocore/src/opentelemetry/instrumentation/botocore/__init__.py index 3212866b2e..1dca0689fa 100644 --- a/instrumentation/opentelemetry-instrumentation-botocore/src/opentelemetry/instrumentation/botocore/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-botocore/src/opentelemetry/instrumentation/botocore/__init__.py @@ -151,7 +151,7 @@ def _patched_api_call(self, original_func, instance, args, kwargs): result = None with self._tracer.start_as_current_span( - "{}".format(service_name), kind=SpanKind.CLIENT, + f"{service_name}", kind=SpanKind.CLIENT, ) as span: # inject trace context into payload headers for lambda Invoke if BotocoreInstrumentor._is_lambda_invoke( diff --git a/instrumentation/opentelemetry-instrumentation-celery/src/opentelemetry/instrumentation/celery/__init__.py b/instrumentation/opentelemetry-instrumentation-celery/src/opentelemetry/instrumentation/celery/__init__.py index ade16d3456..b40642eeff 100644 --- a/instrumentation/opentelemetry-instrumentation-celery/src/opentelemetry/instrumentation/celery/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-celery/src/opentelemetry/instrumentation/celery/__init__.py @@ -136,7 +136,7 @@ def _trace_prerun(self, *args, **kwargs): logger.debug("prerun signal start task_id=%s", task_id) - operation_name = "{0}/{1}".format(_TASK_RUN, task.name) + operation_name = f"{_TASK_RUN}/{task.name}" span = self._tracer.start_span( operation_name, context=tracectx, kind=trace.SpanKind.CONSUMER ) @@ -178,7 +178,7 @@ def _trace_before_publish(self, *args, **kwargs): if task is None or task_id is None: return - operation_name = "{0}/{1}".format(_TASK_APPLY_ASYNC, task.name) + operation_name = f"{_TASK_APPLY_ASYNC}/{task.name}" span = self._tracer.start_span( operation_name, kind=trace.SpanKind.PRODUCER ) diff --git a/instrumentation/opentelemetry-instrumentation-celery/src/opentelemetry/instrumentation/celery/utils.py b/instrumentation/opentelemetry-instrumentation-celery/src/opentelemetry/instrumentation/celery/utils.py index 54cadedb90..a29cebcff0 100644 --- a/instrumentation/opentelemetry-instrumentation-celery/src/opentelemetry/instrumentation/celery/utils.py +++ b/instrumentation/opentelemetry-instrumentation-celery/src/opentelemetry/instrumentation/celery/utils.py @@ -106,7 +106,7 @@ def set_attributes_from_context(span, context): # set attribute name if not set specially for a key if attribute_name is None: - attribute_name = "celery.{}".format(key) + attribute_name = f"celery.{key}" span.set_attribute(attribute_name, value) diff --git a/instrumentation/opentelemetry-instrumentation-celery/tests/test_utils.py b/instrumentation/opentelemetry-instrumentation-celery/tests/test_utils.py index 7e33be6b96..1ca3a48f4e 100644 --- a/instrumentation/opentelemetry-instrumentation-celery/tests/test_utils.py +++ b/instrumentation/opentelemetry-instrumentation-celery/tests/test_utils.py @@ -159,7 +159,7 @@ def fn_task(): utils.retrieve_span(fn_task, task_id), (None, None) ) except Exception as ex: # pylint: disable=broad-except - self.fail("Exception was raised: %s" % ex) + self.fail(f"Exception was raised: {ex}") def test_task_id_from_protocol_v1(self): # ensures a `task_id` is properly returned when Protocol v1 is used. diff --git a/instrumentation/opentelemetry-instrumentation-django/src/opentelemetry/instrumentation/django/middleware.py b/instrumentation/opentelemetry-instrumentation-django/src/opentelemetry/instrumentation/django/middleware.py index 3138c3f95c..f071ba6e56 100644 --- a/instrumentation/opentelemetry-instrumentation-django/src/opentelemetry/instrumentation/django/middleware.py +++ b/instrumentation/opentelemetry-instrumentation-django/src/opentelemetry/instrumentation/django/middleware.py @@ -130,7 +130,7 @@ def _get_span_name(request): return match.view_name except Resolver404: - return "HTTP {}".format(request.method) + return f"HTTP {request.method}" def process_request(self, request): # request.META is a dictionary containing all available HTTP headers @@ -213,7 +213,7 @@ def process_response(self, request, response): if activation and span: add_response_attributes( span, - "{} {}".format(response.status_code, response.reason_phrase), + f"{response.status_code} {response.reason_phrase}", response, ) diff --git a/instrumentation/opentelemetry-instrumentation-django/tests/test_middleware.py b/instrumentation/opentelemetry-instrumentation-django/tests/test_middleware.py index 60e57c2d04..bec805ffd8 100644 --- a/instrumentation/opentelemetry-instrumentation-django/tests/test_middleware.py +++ b/instrumentation/opentelemetry-instrumentation-django/tests/test_middleware.py @@ -349,10 +349,7 @@ def test_trace_response_headers(self): ) self.assertEqual( response.headers["traceresponse"], - "00-{0}-{1}-01".format( - format_trace_id(span.get_span_context().trace_id), - format_span_id(span.get_span_context().span_id), - ), + f"00-{format_trace_id(span.get_span_context().trace_id)}-{format_span_id(span.get_span_context().span_id)}-01", ) self.memory_exporter.clear() diff --git a/instrumentation/opentelemetry-instrumentation-elasticsearch/src/opentelemetry/instrumentation/elasticsearch/__init__.py b/instrumentation/opentelemetry-instrumentation-elasticsearch/src/opentelemetry/instrumentation/elasticsearch/__init__.py index eb01ba08cc..db1939523e 100644 --- a/instrumentation/opentelemetry-instrumentation-elasticsearch/src/opentelemetry/instrumentation/elasticsearch/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-elasticsearch/src/opentelemetry/instrumentation/elasticsearch/__init__.py @@ -192,8 +192,7 @@ def wrapper(wrapped, _, args, kwargs): for member in _ATTRIBUTES_FROM_RESULT: if member in rv: span.set_attribute( - "elasticsearch.{0}".format(member), - str(rv[member]), + f"elasticsearch.{member}", str(rv[member]), ) if callable(response_hook): diff --git a/instrumentation/opentelemetry-instrumentation-elasticsearch/tests/test_elasticsearch.py b/instrumentation/opentelemetry-instrumentation-elasticsearch/tests/test_elasticsearch.py index ed6e75e6fc..a63350299f 100644 --- a/instrumentation/opentelemetry-instrumentation-elasticsearch/tests/test_elasticsearch.py +++ b/instrumentation/opentelemetry-instrumentation-elasticsearch/tests/test_elasticsearch.py @@ -169,7 +169,7 @@ def _test_trace_error(self, code, exc): self.assertFalse(span.status.is_ok) self.assertEqual(span.status.status_code, code) self.assertEqual( - span.status.description, "{}: {}".format(type(exc).__name__, exc) + span.status.description, f"{type(exc).__name__}: {exc}" ) def test_parent(self, request_mock): diff --git a/instrumentation/opentelemetry-instrumentation-falcon/src/opentelemetry/instrumentation/falcon/__init__.py b/instrumentation/opentelemetry-instrumentation-falcon/src/opentelemetry/instrumentation/falcon/__init__.py index dc39e03bf3..5a576dda42 100644 --- a/instrumentation/opentelemetry-instrumentation-falcon/src/opentelemetry/instrumentation/falcon/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-falcon/src/opentelemetry/instrumentation/falcon/__init__.py @@ -264,9 +264,7 @@ def process_resource(self, req, resp, resource, params): resource_name = resource.__class__.__name__ span.set_attribute("falcon.resource", resource_name) - span.update_name( - "{0}.on_{1}".format(resource_name, req.method.lower()) - ) + span.update_name(f"{resource_name}.on_{req.method.lower()}") def process_response( self, req, resp, resource, req_succeeded=None @@ -294,6 +292,7 @@ def process_response( else: status = "500" reason = "{}: {}".format(exc_type.__name__, exc) + reason = f"{exc_type.__name__}: {exc}" status = status.split(" ")[0] try: diff --git a/instrumentation/opentelemetry-instrumentation-falcon/tests/test_falcon.py b/instrumentation/opentelemetry-instrumentation-falcon/tests/test_falcon.py index 3f9c2975de..dbab45a528 100644 --- a/instrumentation/opentelemetry-instrumentation-falcon/tests/test_falcon.py +++ b/instrumentation/opentelemetry-instrumentation-falcon/tests/test_falcon.py @@ -84,9 +84,7 @@ def _test_method(self, method): spans = self.memory_exporter.get_finished_spans() self.assertEqual(len(spans), 1) span = spans[0] - self.assertEqual( - span.name, "HelloWorldResource.on_{0}".format(method.lower()) - ) + self.assertEqual(span.name, f"HelloWorldResource.on_{method.lower()}") self.assertEqual(span.status.status_code, StatusCode.UNSET) self.assertEqual( span.status.description, None, @@ -209,10 +207,7 @@ def test_trace_response(self): ) self.assertEqual( headers["traceresponse"], - "00-{0}-{1}-01".format( - format_trace_id(span.get_span_context().trace_id), - format_span_id(span.get_span_context().span_id), - ), + f"00-{format_trace_id(span.get_span_context().trace_id)}-{format_span_id(span.get_span_context().span_id)}-01", ) set_global_response_propagator(orig) diff --git a/instrumentation/opentelemetry-instrumentation-flask/tests/test_programmatic.py b/instrumentation/opentelemetry-instrumentation-flask/tests/test_programmatic.py index e377950835..ced2927e64 100644 --- a/instrumentation/opentelemetry-instrumentation-flask/tests/test_programmatic.py +++ b/instrumentation/opentelemetry-instrumentation-flask/tests/test_programmatic.py @@ -165,10 +165,7 @@ def test_trace_response(self): ) self.assertEqual( headers["traceresponse"], - "00-{0}-{1}-01".format( - trace.format_trace_id(span.get_span_context().trace_id), - trace.format_span_id(span.get_span_context().span_id), - ), + f"00-{trace.format_trace_id(span.get_span_context().trace_id)}-{trace.format_span_id(span.get_span_context().span_id)}-01", ) set_global_response_propagator(orig) diff --git a/instrumentation/opentelemetry-instrumentation-grpc/src/opentelemetry/instrumentation/grpc/_client.py b/instrumentation/opentelemetry-instrumentation-grpc/src/opentelemetry/instrumentation/grpc/_client.py index d3ad28521a..0f1ed88197 100644 --- a/instrumentation/opentelemetry-instrumentation-grpc/src/opentelemetry/instrumentation/grpc/_client.py +++ b/instrumentation/opentelemetry-instrumentation-grpc/src/opentelemetry/instrumentation/grpc/_client.py @@ -137,7 +137,7 @@ def _intercept(self, request, metadata, client_info, invoker): span.set_status( Status( status_code=StatusCode.ERROR, - description="{}: {}".format(type(exc).__name__, exc), + description=f"{type(exc).__name__}: {exc}", ) ) span.record_exception(exc) diff --git a/instrumentation/opentelemetry-instrumentation-grpc/src/opentelemetry/instrumentation/grpc/_server.py b/instrumentation/opentelemetry-instrumentation-grpc/src/opentelemetry/instrumentation/grpc/_server.py index 8516db14eb..7cefcfe3e7 100644 --- a/instrumentation/opentelemetry-instrumentation-grpc/src/opentelemetry/instrumentation/grpc/_server.py +++ b/instrumentation/opentelemetry-instrumentation-grpc/src/opentelemetry/instrumentation/grpc/_server.py @@ -122,8 +122,7 @@ def abort(self, code, details): ) self._active_span.set_status( Status( - status_code=StatusCode.ERROR, - description="{}:{}".format(code, details), + status_code=StatusCode.ERROR, description=f"{code}:{details}", ) ) return self._servicer_context.abort(code, details) @@ -142,7 +141,7 @@ def set_code(self, code): self._active_span.set_status( Status( status_code=StatusCode.ERROR, - description="{}:{}".format(code, details), + description=f"{code}:{details}", ) ) return self._servicer_context.set_code(code) @@ -153,7 +152,7 @@ def set_details(self, details): self._active_span.set_status( Status( status_code=StatusCode.ERROR, - description="{}:{}".format(self.code, details), + description=f"{self.code}:{details}", ) ) return self._servicer_context.set_details(details) diff --git a/instrumentation/opentelemetry-instrumentation-grpc/tests/_server.py b/instrumentation/opentelemetry-instrumentation-grpc/tests/_server.py index 9bfceebb04..5375253c01 100644 --- a/instrumentation/opentelemetry-instrumentation-grpc/tests/_server.py +++ b/instrumentation/opentelemetry-instrumentation-grpc/tests/_server.py @@ -86,6 +86,6 @@ def create_test_server(port): TestServer(), server ) - server.add_insecure_port("localhost:{}".format(port)) + server.add_insecure_port(f"localhost:{port}") return server diff --git a/instrumentation/opentelemetry-instrumentation-grpc/tests/test_server_interceptor.py b/instrumentation/opentelemetry-instrumentation-grpc/tests/test_server_interceptor.py index 23a6f148e1..2ab84c8651 100644 --- a/instrumentation/opentelemetry-instrumentation-grpc/tests/test_server_interceptor.py +++ b/instrumentation/opentelemetry-instrumentation-grpc/tests/test_server_interceptor.py @@ -90,7 +90,7 @@ def handler(request, context): server.add_generic_rpc_handlers((UnaryUnaryRpcHandler(handler),)) port = server.add_insecure_port("[::]:0") - channel = grpc.insecure_channel("localhost:{:d}".format(port)) + channel = grpc.insecure_channel(f"localhost:{port:d}") rpc_call = "TestServicer/handler" try: @@ -142,7 +142,7 @@ def handler(request, context): server.add_generic_rpc_handlers((UnaryUnaryRpcHandler(handler),)) port = server.add_insecure_port("[::]:0") - channel = grpc.insecure_channel("localhost:{:d}".format(port)) + channel = grpc.insecure_channel(f"localhost:{port:d}") rpc_call = "TestServicer/test" try: @@ -168,7 +168,7 @@ def test_create_span(self): ) add_GRPCTestServerServicer_to_server(Servicer(), server) port = server.add_insecure_port("[::]:0") - channel = grpc.insecure_channel("localhost:{:d}".format(port)) + channel = grpc.insecure_channel(f"localhost:{port:d}") rpc_call = "/GRPCTestServer/SimpleMethod" request = Request(client_id=1, request_data="test") @@ -236,7 +236,7 @@ def SimpleMethod(self, request, context): ) add_GRPCTestServerServicer_to_server(TwoSpanServicer(), server) port = server.add_insecure_port("[::]:0") - channel = grpc.insecure_channel("localhost:{:d}".format(port)) + channel = grpc.insecure_channel(f"localhost:{port:d}") # setup the RPC rpc_call = "/GRPCTestServer/SimpleMethod" @@ -297,7 +297,7 @@ def test_create_span_streaming(self): ) add_GRPCTestServerServicer_to_server(Servicer(), server) port = server.add_insecure_port("[::]:0") - channel = grpc.insecure_channel("localhost:{:d}".format(port)) + channel = grpc.insecure_channel(f"localhost:{port:d}") # setup the RPC rpc_call = "/GRPCTestServer/ServerStreamingMethod" @@ -365,7 +365,7 @@ def ServerStreamingMethod(self, request, context): ) add_GRPCTestServerServicer_to_server(TwoSpanServicer(), server) port = server.add_insecure_port("[::]:0") - channel = grpc.insecure_channel("localhost:{:d}".format(port)) + channel = grpc.insecure_channel(f"localhost:{port:d}") # setup the RPC rpc_call = "/GRPCTestServer/ServerStreamingMethod" @@ -433,7 +433,7 @@ def handler(request, context): server.add_generic_rpc_handlers((UnaryUnaryRpcHandler(handler),)) port = server.add_insecure_port("[::]:0") - channel = grpc.insecure_channel("localhost:{:d}".format(port)) + channel = grpc.insecure_channel(f"localhost:{port:d}") active_span_before_call = trace.get_current_span() try: @@ -469,7 +469,7 @@ def handler(request, context): server.add_generic_rpc_handlers((UnaryUnaryRpcHandler(handler),)) port = server.add_insecure_port("[::]:0") - channel = grpc.insecure_channel("localhost:{:d}".format(port)) + channel = grpc.insecure_channel(f"localhost:{port:d}") try: server.start() @@ -533,7 +533,7 @@ def handler(request, context): server.add_generic_rpc_handlers((UnaryUnaryRpcHandler(handler),)) port = server.add_insecure_port("[::]:0") - channel = grpc.insecure_channel("localhost:{:d}".format(port)) + channel = grpc.insecure_channel(f"localhost:{port:d}") try: server.start() @@ -599,7 +599,7 @@ def handler(request, context): server.add_generic_rpc_handlers((UnaryUnaryRpcHandler(handler),)) port = server.add_insecure_port("[::]:0") - channel = grpc.insecure_channel("localhost:{:d}".format(port)) + channel = grpc.insecure_channel(f"localhost:{port:d}") rpc_call = "TestServicer/handler" @@ -625,9 +625,7 @@ def handler(request, context): self.assertEqual(span.status.status_code, StatusCode.ERROR) self.assertEqual( span.status.description, - "{}:{}".format( - grpc.StatusCode.FAILED_PRECONDITION, failure_message - ), + f"{grpc.StatusCode.FAILED_PRECONDITION}:{failure_message}", ) # Check attributes diff --git a/instrumentation/opentelemetry-instrumentation-httpx/src/opentelemetry/instrumentation/httpx/__init__.py b/instrumentation/opentelemetry-instrumentation-httpx/src/opentelemetry/instrumentation/httpx/__init__.py index 5dd39473ec..a180d65726 100644 --- a/instrumentation/opentelemetry-instrumentation-httpx/src/opentelemetry/instrumentation/httpx/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-httpx/src/opentelemetry/instrumentation/httpx/__init__.py @@ -60,7 +60,7 @@ class ResponseInfo(typing.NamedTuple): def _get_default_span_name(method: str) -> str: - return "HTTP {}".format(method).strip() + return f"HTTP {method.strip()}" def _apply_status_code(span: Span, status_code: int) -> None: diff --git a/instrumentation/opentelemetry-instrumentation-logging/src/opentelemetry/instrumentation/logging/__init__.py b/instrumentation/opentelemetry-instrumentation-logging/src/opentelemetry/instrumentation/logging/__init__.py index e02ac6acb9..4671f8707f 100644 --- a/instrumentation/opentelemetry-instrumentation-logging/src/opentelemetry/instrumentation/logging/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-logging/src/opentelemetry/instrumentation/logging/__init__.py @@ -47,13 +47,13 @@ class LoggingInstrumentor(BaseInstrumentor): # pylint: disable=empty-docstring - __doc__ = """An instrumentor for stdlib logging module. + __doc__ = f"""An instrumentor for stdlib logging module. This instrumentor injects tracing context into logging records and optionally sets the global logging format to the following: .. code-block:: - {default_logging_format} + {DEFAULT_LOGGING_FORMAT} Args: tracer_provider: Tracer provider instance that can be used to fetch a tracer. @@ -68,9 +68,7 @@ class LoggingInstrumentor(BaseInstrumentor): # pylint: disable=empty-docstring logging.FATAL See `BaseInstrumentor` - """.format( - default_logging_format=DEFAULT_LOGGING_FORMAT - ) + """ _old_factory = None diff --git a/instrumentation/opentelemetry-instrumentation-pymemcache/src/opentelemetry/instrumentation/pymemcache/__init__.py b/instrumentation/opentelemetry-instrumentation-pymemcache/src/opentelemetry/instrumentation/pymemcache/__init__.py index 47f70b9e58..374ec46f00 100644 --- a/instrumentation/opentelemetry-instrumentation-pymemcache/src/opentelemetry/instrumentation/pymemcache/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-pymemcache/src/opentelemetry/instrumentation/pymemcache/__init__.py @@ -114,7 +114,7 @@ def _wrap_cmd(tracer, cmd, wrapped, instance, args, kwargs): else: vals = _get_query_string(args[0]) - query = "{}{}{}".format(cmd, " " if vals else "", vals) + query = f"{cmd}{' ' if vals else ''}{vals}" span.set_attribute(SpanAttributes.DB_STATEMENT, query) _set_connection_attributes(span, instance) @@ -188,10 +188,10 @@ def _instrument(self, **kwargs): for cmd in COMMANDS: _wrap( "pymemcache.client.base", - "Client.{}".format(cmd), + f"Client.{cmd}", _wrap_cmd(tracer, cmd), ) def _uninstrument(self, **kwargs): for command in COMMANDS: - unwrap(pymemcache.client.base.Client, "{}".format(command)) + unwrap(pymemcache.client.base.Client, f"{command}") diff --git a/instrumentation/opentelemetry-instrumentation-pymemcache/tests/test_pymemcache.py b/instrumentation/opentelemetry-instrumentation-pymemcache/tests/test_pymemcache.py index c7a7b097d6..6e38c79cde 100644 --- a/instrumentation/opentelemetry-instrumentation-pymemcache/tests/test_pymemcache.py +++ b/instrumentation/opentelemetry-instrumentation-pymemcache/tests/test_pymemcache.py @@ -507,7 +507,7 @@ def make_client(self, *mock_socket_values, **kwargs): ip = TEST_HOST for vals in mock_socket_values: - url_string = "{}:{}".format(ip, current_port) + url_string = f"{ip}:{current_port}" clnt_pool = self.make_client_pool( (ip, current_port), vals, **kwargs ) diff --git a/instrumentation/opentelemetry-instrumentation-pyramid/tests/test_programmatic.py b/instrumentation/opentelemetry-instrumentation-pyramid/tests/test_programmatic.py index a7a0260d4a..1e3263fa01 100644 --- a/instrumentation/opentelemetry-instrumentation-pyramid/tests/test_programmatic.py +++ b/instrumentation/opentelemetry-instrumentation-pyramid/tests/test_programmatic.py @@ -121,10 +121,7 @@ def test_response_headers(self): ) self.assertEqual( headers["traceresponse"], - "00-{0}-{1}-01".format( - trace.format_trace_id(span.get_span_context().trace_id), - trace.format_span_id(span.get_span_context().span_id), - ), + f"00-{trace.format_trace_id(span.get_span_context().trace_id)}-{trace.format_span_id(span.get_span_context().span_id)}-01", ) set_global_response_propagator(orig) diff --git a/instrumentation/opentelemetry-instrumentation-redis/src/opentelemetry/instrumentation/redis/util.py b/instrumentation/opentelemetry-instrumentation-redis/src/opentelemetry/instrumentation/redis/util.py index 3419848eb0..523194080d 100644 --- a/instrumentation/opentelemetry-instrumentation-redis/src/opentelemetry/instrumentation/redis/util.py +++ b/instrumentation/opentelemetry-instrumentation-redis/src/opentelemetry/instrumentation/redis/util.py @@ -64,7 +64,7 @@ def _format_command_args(args): if length + len(cmd) > cmd_max_len: prefix = cmd[: cmd_max_len - length] - out.append("%s%s" % (prefix, value_too_long_mark)) + out.append(f"{prefix}{value_too_long_mark}") break out.append(cmd) diff --git a/instrumentation/opentelemetry-instrumentation-requests/src/opentelemetry/instrumentation/requests/__init__.py b/instrumentation/opentelemetry-instrumentation-requests/src/opentelemetry/instrumentation/requests/__init__.py index e3ba20a6a0..bba05eaaa0 100644 --- a/instrumentation/opentelemetry-instrumentation-requests/src/opentelemetry/instrumentation/requests/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-requests/src/opentelemetry/instrumentation/requests/__init__.py @@ -202,7 +202,7 @@ def _uninstrument_from(instr_root, restore_as_bound_func=False): def get_default_span_name(method): """Default implementation for name_callback, returns HTTP {method_name}.""" - return "HTTP {}".format(method).strip() + return f"HTTP {method.strip()}" class RequestsInstrumentor(BaseInstrumentor): diff --git a/instrumentation/opentelemetry-instrumentation-sklearn/src/opentelemetry/instrumentation/sklearn/__init__.py b/instrumentation/opentelemetry-instrumentation-sklearn/src/opentelemetry/instrumentation/sklearn/__init__.py index 3fe00b57b0..71ed1b6f0f 100644 --- a/instrumentation/opentelemetry-instrumentation-sklearn/src/opentelemetry/instrumentation/sklearn/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-sklearn/src/opentelemetry/instrumentation/sklearn/__init__.py @@ -111,7 +111,7 @@ def implement_span_estimator( name = estimator.__class__.__name__ logger.debug("Instrumenting: %s.%s", name, func.__name__) attributes = attributes or {} - name = "{cls}.{func}".format(cls=name, func=func.__name__) + name = f"{name}.{func.__name__}" return implement_span_function(func, name, attributes) diff --git a/instrumentation/opentelemetry-instrumentation-tornado/src/opentelemetry/instrumentation/tornado/__init__.py b/instrumentation/opentelemetry-instrumentation-tornado/src/opentelemetry/instrumentation/tornado/__init__.py index cb5acc333e..fd7ac8b300 100644 --- a/instrumentation/opentelemetry-instrumentation-tornado/src/opentelemetry/instrumentation/tornado/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-tornado/src/opentelemetry/instrumentation/tornado/__init__.py @@ -249,7 +249,7 @@ def _get_attributes_from_request(request): def _get_operation_name(handler, request): full_class_name = type(handler).__name__ class_name = full_class_name.rsplit(".")[-1] - return "{0}.{1}".format(class_name, request.method.lower()) + return f"{class_name}.{request.method.lower()}" def _start_span(tracer, handler, start_time) -> _TraceContext: diff --git a/instrumentation/opentelemetry-instrumentation-tornado/src/opentelemetry/instrumentation/tornado/client.py b/instrumentation/opentelemetry-instrumentation-tornado/src/opentelemetry/instrumentation/tornado/client.py index 7fe85288ab..04d5e22e93 100644 --- a/instrumentation/opentelemetry-instrumentation-tornado/src/opentelemetry/instrumentation/tornado/client.py +++ b/instrumentation/opentelemetry-instrumentation-tornado/src/opentelemetry/instrumentation/tornado/client.py @@ -88,7 +88,7 @@ def _finish_tracing_callback(future, span, response_hook): if span.is_recording() and exc: if isinstance(exc, HTTPError): status_code = exc.code - description = "{}: {}".format(type(exc).__name__, exc) + description = f"{type(exc).__name__}: {exc}" else: status_code = future.result().code diff --git a/instrumentation/opentelemetry-instrumentation-tornado/tests/test_instrumentation.py b/instrumentation/opentelemetry-instrumentation-tornado/tests/test_instrumentation.py index 249b730d24..ac8e0b1a8f 100644 --- a/instrumentation/opentelemetry-instrumentation-tornado/tests/test_instrumentation.py +++ b/instrumentation/opentelemetry-instrumentation-tornado/tests/test_instrumentation.py @@ -453,10 +453,7 @@ def test_response_headers(self): ) self.assertEqual( headers["traceresponse"], - "00-{0}-{1}-01".format( - trace.format_trace_id(server_span.get_span_context().trace_id), - trace.format_span_id(server_span.get_span_context().span_id), - ), + f"00-{trace.format_trace_id(server_span.get_span_context().trace_id)}-{trace.format_span_id(server_span.get_span_context().span_id)}-01", ) self.memory_exporter.clear() diff --git a/instrumentation/opentelemetry-instrumentation-urllib/src/opentelemetry/instrumentation/urllib/__init__.py b/instrumentation/opentelemetry-instrumentation-urllib/src/opentelemetry/instrumentation/urllib/__init__.py index 9767b08796..e0ce95d9c4 100644 --- a/instrumentation/opentelemetry-instrumentation-urllib/src/opentelemetry/instrumentation/urllib/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-urllib/src/opentelemetry/instrumentation/urllib/__init__.py @@ -171,7 +171,7 @@ def _instrumented_open_call( method = request.get_method().upper() url = request.full_url - span_name = "HTTP {}".format(method).strip() + span_name = f"HTTP {method}".strip() url = remove_url_credentials(url) @@ -215,9 +215,9 @@ def _instrumented_open_call( ver_ = str(getattr(result, "version", "")) if ver_: - labels[SpanAttributes.HTTP_FLAVOR] = "{}.{}".format( - ver_[:1], ver_[:-1] - ) + labels[ + SpanAttributes.HTTP_FLAVOR + ] = f"{ver_[:1]}.{ver_[:-1]}" if callable(response_hook): response_hook(span, request, result) diff --git a/instrumentation/opentelemetry-instrumentation-urllib3/src/opentelemetry/instrumentation/urllib3/__init__.py b/instrumentation/opentelemetry-instrumentation-urllib3/src/opentelemetry/instrumentation/urllib3/__init__.py index d0bb977f74..235c5b477b 100644 --- a/instrumentation/opentelemetry-instrumentation-urllib3/src/opentelemetry/instrumentation/urllib3/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-urllib3/src/opentelemetry/instrumentation/urllib3/__init__.py @@ -161,7 +161,7 @@ def instrumented_urlopen(wrapped, instance, args, kwargs): headers = _prepare_headers(kwargs) body = _get_url_open_arg("body", args, kwargs) - span_name = "HTTP {}".format(method.strip()) + span_name = f"HTTP {method.strip()}" span_attributes = { SpanAttributes.HTTP_METHOD: method, SpanAttributes.HTTP_URL: url, diff --git a/instrumentation/opentelemetry-instrumentation-wsgi/src/opentelemetry/instrumentation/wsgi/__init__.py b/instrumentation/opentelemetry-instrumentation-wsgi/src/opentelemetry/instrumentation/wsgi/__init__.py index 2000829c13..f486791318 100644 --- a/instrumentation/opentelemetry-instrumentation-wsgi/src/opentelemetry/instrumentation/wsgi/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-wsgi/src/opentelemetry/instrumentation/wsgi/__init__.py @@ -210,7 +210,7 @@ def add_response_attributes( def get_default_span_name(environ): """Default implementation for name_callback, returns HTTP {METHOD_NAME}.""" - return "HTTP {}".format(environ.get("REQUEST_METHOD", "")).strip() + return f"HTTP {environ.get('REQUEST_METHOD', '')}".strip() class OpenTelemetryMiddleware: diff --git a/scripts/eachdist.py b/scripts/eachdist.py index 22300e1b75..f2a403835f 100755 --- a/scripts/eachdist.py +++ b/scripts/eachdist.py @@ -31,14 +31,12 @@ def unique(elems): def extraargs_help(calledcmd): return cleandoc( - """ - Additional arguments to pass on to {}. + f""" + Additional arguments to pass on to {calledcmd}. This is collected from any trailing arguments passed to `%(prog)s`. Use an initial `--` to separate them from regular arguments. - """.format( - calledcmd - ) + """ ) @@ -403,7 +401,7 @@ def execute_args(args): rootpath = find_projectroot() targets = find_targets(args.mode, rootpath) if not targets: - sys.exit("Error: No targets selected (root: {})".format(rootpath)) + sys.exit(f"Error: No targets selected (root: {rootpath})") def fmt_for_path(fmt, path): return fmt.format( @@ -419,7 +417,7 @@ def _runcmd(cmd): ) if result is not None and result.returncode not in args.allowexitcode: print( - "'{}' failed with code {}".format(cmd, result.returncode), + f"'{cmd}' failed with code {result.returncode}", file=sys.stderr, ) sys.exit(result.returncode) @@ -474,7 +472,7 @@ def install_args(args): if args.with_test_deps: extras.append("test") if extras: - allfmt += "[{}]".format(",".join(extras)) + allfmt += f"[{','.join(extras)}]" # note the trailing single quote, to close the quote opened above. allfmt += "'" @@ -548,9 +546,9 @@ def update_changelog(path, version, new_entry): try: with open(path, encoding="utf-8") as changelog: text = changelog.read() - if "## [{}]".format(version) in text: + if f"## [{version}]" in text: raise AttributeError( - "{} already contans version {}".format(path, version) + f"{path} already contans version {version}" ) with open(path, encoding="utf-8") as changelog: for line in changelog: @@ -562,11 +560,11 @@ def update_changelog(path, version, new_entry): unreleased_changes = True except FileNotFoundError: - print("file missing: {}".format(path)) + print(f"file missing: {path}") return if unreleased_changes: - print("updating: {}".format(path)) + print(f"updating: {path}") text = re.sub(r"## \[Unreleased\].*", new_entry, text) with open(path, "w", encoding="utf-8") as changelog: changelog.write(text) @@ -617,10 +615,7 @@ def update_version_files(targets, version, packages): print("updating version.py files") targets = filter_packages(targets, packages) update_files( - targets, - "version.py", - "__version__ .*", - '__version__ = "{}"'.format(version), + targets, "version.py", "__version__ .*", f'__version__ = "{version}"', ) @@ -638,7 +633,7 @@ def update_dependencies(targets, version, packages): update_files( targets, "setup.cfg", - r"({}.*)==(.*)".format(package_name), + fr"({package_name}.*)==(.*)", r"\1== " + version, ) @@ -648,14 +643,14 @@ def update_files(targets, filename, search, replace): for target in targets: curr_file = find(filename, target) if curr_file is None: - print("file missing: {}/{}".format(target, filename)) + print(f"file missing: {target}/{filename}") continue with open(curr_file, encoding="utf-8") as _file: text = _file.read() if replace in text: - print("{} already contains {}".format(curr_file, replace)) + print(f"{curr_file} already contains {replace}") continue with open(curr_file, "w", encoding="utf-8") as _file: @@ -681,7 +676,7 @@ def release_args(args): packages = None if "packages" in mcfg: packages = mcfg["packages"].split() - print("update {} packages to {}".format(group, version)) + print(f"update {group} packages to {version}") update_dependencies(targets, version, packages) update_version_files(targets, version, packages) diff --git a/scripts/generate_instrumentation_readme.py b/scripts/generate_instrumentation_readme.py index 4eaa8c907d..dd8f1bb4bb 100755 --- a/scripts/generate_instrumentation_readme.py +++ b/scripts/generate_instrumentation_readme.py @@ -62,9 +62,7 @@ def main(): instruments = (name,) table.append( - "| [{0}](./{0}) | {1} |".format( - instrumentation, ",".join(instruments) - ) + f"| [{instrumentation}](./{instrumentation}) | {','.join(instruments)} |" ) with open( diff --git a/sdk-extension/opentelemetry-sdk-extension-aws/src/opentelemetry/sdk/extension/aws/trace/propagation/aws_xray_format.py b/sdk-extension/opentelemetry-sdk-extension-aws/src/opentelemetry/sdk/extension/aws/trace/propagation/aws_xray_format.py index 9ec12fe3e4..1aff8faf78 100644 --- a/sdk-extension/opentelemetry-sdk-extension-aws/src/opentelemetry/sdk/extension/aws/trace/propagation/aws_xray_format.py +++ b/sdk-extension/opentelemetry-sdk-extension-aws/src/opentelemetry/sdk/extension/aws/trace/propagation/aws_xray_format.py @@ -282,7 +282,7 @@ def inject( if not span_context.is_valid: return - otel_trace_id = "{:032x}".format(span_context.trace_id) + otel_trace_id = f"{span_context.trace_id:032x}" xray_trace_id = TRACE_ID_DELIMITER.join( [ TRACE_ID_VERSION, @@ -291,7 +291,7 @@ def inject( ] ) - parent_id = "{:016x}".format(span_context.span_id) + parent_id = f"{span_context.span_id:016x}" sampling_flag = ( IS_SAMPLED diff --git a/util/opentelemetry-util-http/src/opentelemetry/util/http/__init__.py b/util/opentelemetry-util-http/src/opentelemetry/util/http/__init__.py index 7a4bb01ecf..0c1efe9fe8 100644 --- a/util/opentelemetry-util-http/src/opentelemetry/util/http/__init__.py +++ b/util/opentelemetry-util-http/src/opentelemetry/util/http/__init__.py @@ -35,7 +35,7 @@ def url_disabled(self, url: str) -> bool: def get_traced_request_attrs(instrumentation): traced_request_attrs = environ.get( - _root.format("{}_TRACED_REQUEST_ATTRS".format(instrumentation)), [] + _root.format(f"{instrumentation}_TRACED_REQUEST_ATTRS"), [] ) if traced_request_attrs: @@ -49,7 +49,7 @@ def get_traced_request_attrs(instrumentation): def get_excluded_urls(instrumentation): excluded_urls = environ.get( - _root.format("{}_EXCLUDED_URLS".format(instrumentation)), [] + _root.format(f"{instrumentation}_EXCLUDED_URLS"), [] ) return parse_excluded_urls(excluded_urls)