clarity-api-sdk-python 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,22 @@
1
+ Metadata-Version: 2.4
2
+ Name: clarity-api-sdk-python
3
+ Version: 0.1.0
4
+ Summary: A Python SDK to connect to the CTI API server.
5
+ Author-email: "Chesapeake Technology Inc." <support@chesapeaketech.com>
6
+ Project-URL: Homepage, https://github.com/chesapeake-tech/clarity-api-sdk-python
7
+ Classifier: Programming Language :: Python :: 3
8
+ Classifier: License :: OSI Approved :: MIT License
9
+ Classifier: Operating System :: OS Independent
10
+ Requires-Python: >=3.12
11
+ Description-Content-Type: text/markdown
12
+ Requires-Dist: structlog
13
+
14
+ # Clarity API SDK for Python
15
+
16
+ A Python SDK for connecting to the CTI API server, with structured logging included.
17
+
18
+ ## Installation
19
+
20
+ ```bash
21
+ pip install clarity-api-sdk-python
22
+ ```
@@ -0,0 +1,9 @@
1
+ # Clarity API SDK for Python
2
+
3
+ A Python SDK for connecting to the CTI API server, with structured logging included.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ pip install clarity-api-sdk-python
9
+ ```
@@ -0,0 +1,28 @@
1
+
2
+ [build-system]
3
+ requires = ["setuptools>=61.0"]
4
+ build-backend = "setuptools.build_meta"
5
+
6
+ [project]
7
+ name = "clarity-api-sdk-python"
8
+ version = "0.1.0"
9
+ authors = [
10
+ { name="Chesapeake Technology Inc.", email="support@chesapeaketech.com" },
11
+ ]
12
+ description = "A Python SDK to connect to the CTI API server."
13
+ readme = "README.md"
14
+ requires-python = ">=3.12"
15
+ classifiers = [
16
+ "Programming Language :: Python :: 3",
17
+ "License :: OSI Approved :: MIT License",
18
+ "Operating System :: OS Independent",
19
+ ]
20
+ dependencies = [
21
+ "structlog",
22
+ ]
23
+
24
+ [project.urls]
25
+ "Homepage" = "https://github.com/chesapeake-tech/clarity-api-sdk-python"
26
+
27
+ [tool.setuptools.packages.find]
28
+ where = ["src"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,22 @@
1
+ Metadata-Version: 2.4
2
+ Name: clarity-api-sdk-python
3
+ Version: 0.1.0
4
+ Summary: A Python SDK to connect to the CTI API server.
5
+ Author-email: "Chesapeake Technology Inc." <support@chesapeaketech.com>
6
+ Project-URL: Homepage, https://github.com/chesapeake-tech/clarity-api-sdk-python
7
+ Classifier: Programming Language :: Python :: 3
8
+ Classifier: License :: OSI Approved :: MIT License
9
+ Classifier: Operating System :: OS Independent
10
+ Requires-Python: >=3.12
11
+ Description-Content-Type: text/markdown
12
+ Requires-Dist: structlog
13
+
14
+ # Clarity API SDK for Python
15
+
16
+ A Python SDK for connecting to the CTI API server, with structured logging included.
17
+
18
+ ## Installation
19
+
20
+ ```bash
21
+ pip install clarity-api-sdk-python
22
+ ```
@@ -0,0 +1,9 @@
1
+ README.md
2
+ pyproject.toml
3
+ src/clarity_api_sdk_python.egg-info/PKG-INFO
4
+ src/clarity_api_sdk_python.egg-info/SOURCES.txt
5
+ src/clarity_api_sdk_python.egg-info/dependency_links.txt
6
+ src/clarity_api_sdk_python.egg-info/requires.txt
7
+ src/clarity_api_sdk_python.egg-info/top_level.txt
8
+ src/logger/__init__.py
9
+ src/logger/logger.py
@@ -0,0 +1,3 @@
1
+ """import modules"""
2
+
3
+ from .logger import get_logger, initialize_logger # noqa
@@ -0,0 +1,275 @@
1
+ """Structured Logger configuration."""
2
+
3
+ from collections import OrderedDict
4
+ from dataclasses import dataclass
5
+ import logging
6
+ import socket
7
+ import sys
8
+ from typing import Optional
9
+ import urllib.error
10
+ import urllib.request
11
+
12
+ import structlog
13
+
14
+
15
+ @dataclass
16
+ class ExternalLoggerConfig:
17
+ """External logger configuration parameters."""
18
+
19
+ def __init__(
20
+ self, name: str, level: int = logging.CRITICAL, disabled=False, propagate=False
21
+ ):
22
+ """Construct an external logger configuration to configure external logging.
23
+
24
+ Args:
25
+ name: The name of the external logger
26
+ level: The level to set for the logger
27
+ disabled: Whether or not to disable logging
28
+ propagate: Whether or not to propagate the log messages to the parent logger
29
+ """
30
+ self.name = name
31
+ self.level = level
32
+ self.disabled = disabled
33
+ self.propagate = propagate
34
+
35
+
36
+ def get_logger(name: str) -> logging.Logger:
37
+ """Creates a structlog logger with the specified name.
38
+
39
+ Args:
40
+ name (str): The logger name.
41
+
42
+ Returns:
43
+ logging.Logger: The structlog logger.
44
+ """
45
+ return structlog.get_logger(name)
46
+
47
+
48
+ def _flatten_extra_processor(_, __, event_dict):
49
+ """A structlog processor to flatten the 'extra' dictionary into the top level.
50
+
51
+ Args:
52
+ event_dict (structlog.typing.EventDict): The log event dictionary to be processed.
53
+
54
+ Returns:
55
+ structlog.typing.EventDict: The processed event dictionary with extra flattened.
56
+ """
57
+ if "extra" in event_dict:
58
+ extra_data = event_dict.pop("extra")
59
+ if isinstance(extra_data, dict):
60
+ # Merge extra data into the main event_dict
61
+ event_dict.update(extra_data)
62
+ return event_dict
63
+
64
+
65
+ def _get_aws_metadata() -> dict:
66
+ """A structlog processor to add AWS instance metadata to the log entry.
67
+ This is an expensive call, so only call it when necessary.
68
+
69
+ This function attempts to retrieve the instance-id, instance-type, and
70
+ public-ipv4 from the AWS metadata service with a short timeout. If the
71
+ information cannot be retrieved, 'unknown' is used as a fallback value.
72
+
73
+ For more details, see https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instancedata-data-retrieval.html
74
+
75
+ Returns:
76
+ dict: A dictionary with AWS metadata.
77
+ """
78
+
79
+ def _get_metadata(key: str, timeout: int = 1) -> str:
80
+ """Helper to fetch a metadata key with a timeout."""
81
+ try:
82
+ # yes, a hard coded IPv4 is best practice
83
+ url = f"http://169.254.169.245/latest/meta-data/{key}"
84
+ with urllib.request.urlopen(url, timeout=timeout) as response:
85
+ return response.read().decode("utf-8")
86
+ except (urllib.error.URLError, socket.timeout):
87
+ return "unknown"
88
+
89
+ return {
90
+ "aws_instance_id": _get_metadata("instance-id"),
91
+ "aws_instance_type": _get_metadata("instance-type"),
92
+ "aws_public_ipv4": _get_metadata("public-ipv4"),
93
+ }
94
+
95
+
96
+ def _order_event_dict(
97
+ _logger: structlog.typing.WrappedLogger,
98
+ _method_name: str,
99
+ event_dict: structlog.typing.EventDict,
100
+ ) -> structlog.typing.EventDict:
101
+ """A structlog processor to reorder the event dictionary.
102
+
103
+ This processor ensures that certain important keys ("timestamp", "job_id",
104
+ "level", "event") appear at the beginning of the log entry, making the
105
+ logs more readable and consistent. The specified keys are ordered first,
106
+ and any other keys in the event dictionary are appended afterwards in the
107
+ order they were originally.
108
+
109
+ Args:
110
+ event_dict (structlog.typing.EventDict): The log event dictionary to be reordered.
111
+
112
+ Returns:
113
+ collections.OrderedDict: The event dictionary with keys reordered.
114
+ """
115
+ key_order = ["timestamp", "jobId", "level", "event"]
116
+ # Use OrderedDict to preserve the order of the remaining keys.
117
+ ordered_event_dict = OrderedDict()
118
+ for key in key_order:
119
+ if key in event_dict:
120
+ ordered_event_dict[key] = event_dict.pop(key)
121
+
122
+ # Add the rest of the items, which will now be at the end.
123
+ ordered_event_dict.update(event_dict.items())
124
+
125
+ return ordered_event_dict
126
+
127
+
128
+ def _secret_redaction_processor(_, __, event_dict):
129
+ """A structlog processor to redact sensitive information in log entries.
130
+
131
+ Args:
132
+ event_dict (structlog.typing.EventDict): The log event dictionary to be processed.
133
+
134
+ Returns:
135
+ structlog.typing.EventDict: The processed event dictionary.
136
+ """
137
+ sensitive_keys = ["password", "api_key", "token", "SecretString"]
138
+
139
+ def redact_dict(data):
140
+ """Recursively redact sensitive keys in nested dictionaries.
141
+
142
+ Args:
143
+ data (dict): The dictionary to redact sensitive keys.
144
+
145
+ Returns:
146
+ dict: The redacted dictionary.
147
+ """
148
+ if isinstance(data, dict):
149
+ for key, value in data.items():
150
+ if key in sensitive_keys:
151
+ data[key] = "[REDACTED]"
152
+ elif isinstance(value, dict):
153
+ redact_dict(value)
154
+ return data
155
+
156
+ # Redact top-level sensitive keys
157
+ for key in sensitive_keys:
158
+ if key in event_dict:
159
+ event_dict[key] = "[REDACTED]"
160
+
161
+ # Check for nested dictionaries and redact them
162
+ for key, value in event_dict.items():
163
+ if isinstance(value, dict):
164
+ redact_dict(value)
165
+
166
+ return event_dict
167
+
168
+
169
+ def initialize_logger(
170
+ initial_context: Optional[dict] = None,
171
+ external_logger_configurations: Optional[list[ExternalLoggerConfig]] = None,
172
+ ) -> None:
173
+ """Configures logging for the application using structlog.
174
+
175
+ This function sets up `structlog` to produce structured JSON logs. It
176
+ configures a chain of processors to enrich log entries with contextual
177
+ information such as timestamps, host details, and log levels. The standard
178
+ Python `logging` module is configured to act as the sink, directing the
179
+ formatted JSON logs to standard output in JSONL format.
180
+
181
+ The processor chain includes:
182
+ - Merging context variables.
183
+ - Filtering by log level.
184
+ - Adding logger name and log level.
185
+ - `add_host_info`: Custom processor to add hostname and IP.
186
+ - `TimeStamper`: Adds an ISO formatted timestamp.
187
+ - `PositionalArgumentsFormatter`: Formats positional arguments into the message.
188
+ - Exception and stack info renderers.
189
+ - `UnicodeDecoder`: Decodes unicode characters.
190
+ - `order_event_dict`: Custom processor to ensure a consistent key order.
191
+ - `JSONRenderer`: Renders the final log entry as a JSON string.
192
+
193
+ Args:
194
+ initial_context (dict, optional): A dictionary of key-value pairs to
195
+ bind to the context at the start of the application. These values
196
+ will be included in every log message. Defaults to None.
197
+ external_logger_configurations (list[ExternalLoggerConfig], optional): A list of configuration
198
+ """
199
+ # Configure standard logging to be the sink for structlog.
200
+ # The format="%(message)s" is important because structlog will format the log record
201
+ # into a JSON string and pass it as the 'message'.
202
+ logging.basicConfig(
203
+ level=_level(),
204
+ format="%(message)s",
205
+ stream=sys.stdout,
206
+ )
207
+
208
+ # configure external loggers
209
+ if external_logger_configurations:
210
+ for config in external_logger_configurations:
211
+ logger = logging.getLogger(config.name)
212
+ logger.setLevel(config.level)
213
+ logger.disabled = config.disabled
214
+ logger.propagate = config.propagate
215
+
216
+ # Configure structlog to produce JSON logs.
217
+ structlog.configure(
218
+ processors=[
219
+ # Merge contextvars into the event dictionary.
220
+ structlog.contextvars.merge_contextvars,
221
+ # Filter logs by level.
222
+ structlog.stdlib.filter_by_level,
223
+ # Add logger name and log level to the event dict.
224
+ structlog.stdlib.add_logger_name,
225
+ structlog.stdlib.add_log_level,
226
+ # Add a timestamp in ISO format.
227
+ structlog.processors.TimeStamper(fmt="iso"),
228
+ # Render positional arguments into the message.
229
+ structlog.stdlib.PositionalArgumentsFormatter(),
230
+ # If the log record contains an exception, render it.
231
+ structlog.processors.StackInfoRenderer(),
232
+ structlog.processors.format_exc_info,
233
+ _flatten_extra_processor,
234
+ _secret_redaction_processor,
235
+ # Decode unicode characters.
236
+ structlog.processors.UnicodeDecoder(),
237
+ # partial sort of key values.
238
+ _order_event_dict,
239
+ # Render the final event dict as JSON.
240
+ structlog.processors.JSONRenderer(),
241
+ ],
242
+ # Use a standard library logger factory.
243
+ logger_factory=structlog.stdlib.LoggerFactory(),
244
+ # Use a wrapper class to provide standard logging methods.
245
+ wrapper_class=structlog.stdlib.BoundLogger,
246
+ # Cache the logger on first use.
247
+ cache_logger_on_first_use=True,
248
+ )
249
+
250
+ # Gather static context information at startup.
251
+ static_context = {}
252
+ static_context.update(_get_aws_metadata())
253
+
254
+ # Merge with any context provided at startup.
255
+ if initial_context:
256
+ static_context.update(initial_context)
257
+
258
+ # Bind the initial context if it's provided.
259
+ # This context will be included in all logs.
260
+ if initial_context:
261
+ structlog.contextvars.bind_contextvars(**static_context)
262
+
263
+
264
+ def _level():
265
+ """Get the log level for the logger.
266
+
267
+ Set optional environment variable.
268
+
269
+ - MANUAL only logs ERROR
270
+ - PRODUCTION - turns off debug
271
+
272
+ Returns:
273
+ str: log level
274
+ """
275
+ return "DEBUG"