Skip to content

Commit 9712d82

Browse files
authored
Cosmos Diagnostics Logging Filters and optimizations. (Azure#39897)
* Updates on Cosmos Diagnostics Adds the ability to use logging.Filters on diagnostics logs based on the same filterable parameters as the cosmos diagnostics handler. Also adds some optimizations to reduce time spent on logging diagnostics. Lastly improves the formatting of the diagnostics log to improve readabilty especially when errors are logged. * Update CHANGELOG.md * Update CHANGELOG.md * updates to cosmos diagnostics * update to logging policy and tests * pylint updates * Update README.md * Remove diagnostics handler This removes the custom diagnostics handler and instead allows the use of logging filters. * Update CHANGELOG.md * Update _cosmos_http_logging_policy.py * update recommended changes * updates
1 parent 32a2eac commit 9712d82

9 files changed

+415
-438
lines changed

sdk/cosmos/azure-cosmos/CHANGELOG.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
### 4.10.0b5 (Unreleased)
44

55
#### Features Added
6+
* Added ability to use Filters from Logging module on Diagnostics Logging based on Http request/response related attributes. See [PR 39897](https://github.com/Azure/azure-sdk-for-python/pull/39897)
67

78
#### Breaking Changes
89

@@ -11,8 +12,10 @@
1112
* Fixed health check to check the first write region when it is not specified in the preferred regions. See [PR 40588](https://github.com/Azure/azure-sdk-for-python/pull/40588).
1213

1314
#### Other Changes
15+
* Optimized Diagnostics Logging by reducing time spent on logging. Logged Errors are more readable and formatted. See [PR 39897](https://github.com/Azure/azure-sdk-for-python/pull/39897)
1416
* Health checks are now done concurrently and for all regions for async apis. See [PR 40588](https://github.com/Azure/azure-sdk-for-python/pull/40588).
1517

18+
1619
### 4.10.0b4 (2025-04-01)
1720

1821
#### Bugs Fixed

sdk/cosmos/azure-cosmos/README.md

Lines changed: 31 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -950,53 +950,39 @@ However, if you desire to use the CosmosHttpLoggingPolicy to obtain additional i
950950
client = CosmosClient(URL, credential=KEY, enable_diagnostics_logging=True)
951951
database = client.create_database(DATABASE_NAME, logger=logger)
952952
```
953-
**NOTICE: The Following is a Preview Feature that is subject to significant change.**
954-
To further customize what gets logged, you can use a **PREVIEW** diagnostics handler to filter out the logs you don't want to see.
955-
There are several ways to use the diagnostics handler, those include the following:
956-
- Using the "CosmosDiagnosticsHandler" class, which has default behaviour that can be modified.
957-
**NOTE: The diagnostics handler will only be used if the `enable_diagnostics_logging` argument is passed in at the client constructor.
958-
The CosmosDiagnosticsHandler is also a special type of dictionary that is callable and that has preset keys. The values it expects are functions related to it's relevant diagnostic data. (e.g. ```diagnostics_handler["duration"]``` expects a function that takes in an int and returns a boolean as it relates to the duration of an operation to complete).**
959-
```python
960-
from azure.cosmos import CosmosClient, CosmosDiagnosticsHandler
961-
import logging
962-
# Initialize the logger
963-
logger = logging.getLogger('azure.cosmos')
964-
logger.setLevel(logging.INFO)
965-
file_handler = logging.FileHandler('diagnostics1.output')
966-
logger.addHandler(file_handler)
967-
diagnostics_handler = cosmos_diagnostics_handler.CosmosDiagnosticsHandler()
968-
diagnostics_handler["duration"] = lambda x: x > 2000
969-
client = CosmosClient(URL, credential=KEY,logger=logger, diagnostics_handler=diagnostics_handler, enable_diagnostics_logging=True)
970-
971-
```
972-
- Using a dictionary with the relevant functions to filter out the logs you don't want to see.
973-
```python
974-
# Initialize the logger
975-
logger = logging.getLogger('azure.cosmos')
976-
logger.setLevel(logging.INFO)
977-
file_handler = logging.FileHandler('diagnostics2.output')
978-
logger.addHandler(file_handler)
979-
diagnostics_handler = {
980-
"duration": lambda x: x > 2000
981-
}
982-
client = CosmosClient(URL, credential=KEY,logger=logger, diagnostics_handler=diagnostics_handler, enable_diagnostics_logging=True)
983-
```
984-
- Using a function that will replace the should_log function in the CosmosHttpLoggingPolicy which expects certain paramameters and returns a boolean. **Note: the parameters of the custom should_log must match the parameters of the original should_log function as shown in the sample.**
985-
```python
986-
# Custom should_log method
987-
def should_log(self, **kwargs):
988-
return kwargs.get('duration') and kwargs['duration'] > 2000
989-
990-
# Initialize the logger
953+
**NOTICE: The Following is a Preview Feature.**
954+
To further customize what gets logged, you can use logger filters to filter out the logs you don't want to see. You are able to filter based on the following attributes in the log record of cosmos diagnostics logs:
955+
- `status_code`
956+
- `sub_status_code`
957+
- `duration`
958+
- `verb`
959+
- `database_name`
960+
- `collection_name`
961+
- `operation_type`
962+
- `url`
963+
- `resource_type`
964+
- `is_request`
965+
966+
You can take a look at the samples [here][cosmos_diagnostics_filter_sample] or take a quick look at this snippet:
967+
- Using **filters** from the **logging** library, it is possible to filter the diagnostics logs. Several filterable attributes are made available to the log record of the diagnostics logs when using logging filters.
968+
```python
969+
import logging
970+
from azure.cosmos import CosmosClient
991971
logger = logging.getLogger('azure.cosmos')
992972
logger.setLevel(logging.INFO)
993-
file_handler = logging.FileHandler('diagnostics3.output')
973+
file_handler = logging.FileHandler('diagnostics.output')
994974
logger.addHandler(file_handler)
995-
996-
# Initialize the Cosmos client with custom diagnostics handler
997-
client = CosmosClient(endpoint, key,logger=logger, diagnostics_handler=should_log, enable_diagnostics_logging=True)
998-
```
999-
975+
# Create a filter to filter out logs
976+
class CustomFilter(logging.Filter):
977+
def filter(self, record):
978+
ret = (hasattr(record, 'status_code') and record.status_code > 400
979+
and not (record.status_code in [404, 409, 412] and getattr(record, 'sub_status_code', None) in [0, None])
980+
and hasattr(record, 'duration') and record.duration > 1000)
981+
return ret
982+
# Add the filter to the logger
983+
logger.addFilter(CustomFilter())
984+
client = CosmosClient(endpoint, key,logger=logger, enable_diagnostics_logging=True)
985+
```
1000986
### Telemetry
1001987
Azure Core provides the ability for our Python SDKs to use OpenTelemetry with them. The only packages that need to be installed
1002988
to use this functionality are the following:
@@ -1060,6 +1046,7 @@ For more extensive documentation on the Cosmos DB service, see the [Azure Cosmos
10601046
[BM25]: https://learn.microsoft.com/azure/search/index-similarity-and-scoring
10611047
[cosmos_fts]: https://aka.ms/cosmosfulltextsearch
10621048
[cosmos_index_policy_change]: https://learn.microsoft.com/azure/cosmos-db/index-policy#modifying-the-indexing-policy
1049+
[cosmos_diagnostics_filter_sample]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/cosmos/azure-cosmos/samples/diagnostics_filter_sample.py
10631050

10641051
## Contributing
10651052

sdk/cosmos/azure-cosmos/azure/cosmos/_cosmos_client_connection.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -214,7 +214,6 @@ def __init__( # pylint: disable=too-many-statements
214214
logger=kwargs.pop("logger", None),
215215
enable_diagnostics_logging=kwargs.pop("enable_diagnostics_logging", False),
216216
global_endpoint_manager=self._global_endpoint_manager,
217-
diagnostics_handler=kwargs.pop("diagnostics_handler", None),
218217
**kwargs
219218
),
220219
]

0 commit comments

Comments
 (0)