Truncate a string with string format - Wed, Apr 13, 2022
Truncate a string with string format
During the last few days I was programming CI-code for processing k8s manifests
. And for easier debugging I wanted to print some information about the manifest if an error occurred. In particular the kind
of object and its name from the metadata
.
I was using PyYAML
to read the manifest and convert them to dictionaries. Printing one of these dictionaries like this:
print(f"Could not find builder for kind {kind} in {yaml_doc}")
produced a lengthy output, not so easy to read:
Could not find builder for kind AlertmanagerConfig in {'apiVersion': 'monitoring.coreos.com/v1alpha1', 'kind': 'AlertmanagerConfig', 'metadata': {'name': 'alertmanager-config', 'namespace': 'test', 'labels': {'monitoring/alertmanager': 'test'}}, 'spec': {'route': {'receiver': 'null', 'routes': [{'receiver': 'email_to_dietmar', 'matchers': [{'name': 'alertname', 'value': 'LowThreshold', 'regex': False}], 'groupWait': '5s', 'continue': True}, {'receiver': 'admin', 'matchers': [{'name': 'severity', 'value': 'Indeterminate', 'regex': False}], 'groupWait': '5s', 'continue': True}, {'receiver': 'nagios', 'matchers': [{'name': 'severity', 'value': 'Warning', 'regex': False}], 'groupWait': '5s', 'continue': True}, {'receiver': 'Alerting', 'matchers': [{'name':...
So I searched for a way to truncate the dictionaries to only include the first fewcharacters
which usually contain the kind
and metadata
. Having this information one could start troubleshooting by looking at the particular manifest and not convoluting the log with redundant information.
After reading the documentation about string formatting
I changed to code as follows:
print(f"Could not find builder for kind {kind} in {yaml_doc!s:200.200}...")
The string format expression in the curly brackets first calls str()
on the dict converting it to a string. Truncation is done by adding the precision
format 200.200
which means that only the first 200 characters should be used.
The truncated output is more readable and contains type and name of the object:
Could not find builder for kind AlertmanagerConfig in {'apiVersion': 'monitoring.coreos.com/v1alpha1', 'kind': 'AlertmanagerConfig', 'metadata': {'name': 'alertmanager-config', 'namespace': 'test', 'labels': {'monitoring/alertmanag...