Skip to content

Commit 989b184

Browse files
rakshith91srnagar
andauthored
Logsinjestion SDK initial commit (Azure#24136)
* Logs Ingestion Initial Commit * some code * CI * update * package init * fix * lint * lint * sample test file * generate with dpg * generate using DPG * Rename to data collection * rename to ingestion * regen * add credentuial * patch * patch * expose * oops * case insensitive enum * int optional * updated sample * regen * changes * reqs * readme * lint * lint * fix build * build * parallel uploads + lint * changelog * Update sdk/monitor/azure-monitor-ingestion/MANIFEST.in * API change * Apply suggestions from code review Co-authored-by: Srikanta <51379715+srnagar@users.noreply.github.com> * Update eng/.docsettings.yml * sdist * bug fix * Update sdk/monitor/azure-monitor-ingestion/CHANGELOG.md Co-authored-by: Srikanta <51379715+srnagar@users.noreply.github.com>
1 parent ceb8d15 commit 989b184

39 files changed

+1833
-1
lines changed

.vscode/cspell.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,7 @@
105105
"sdk/ml/azure-ai-ml/azure/ai/ml/_restclient/**",
106106
"sdk/ml/azure-ai-ml/azure/ai/ml/entities/_job/job_name_generator.py",
107107
"sdk/ml/azure-ai-ml/tests/**",
108+
"sdk/monitor/azure-monitor-ingestion/**",
108109
"eng/**/*.json",
109110
"eng/*.txt",
110111
"eng/tox/tox.ini",
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
# Release History
2+
3+
## 1.0.0b1 (2022-07-13)
4+
5+
## Features
6+
- Version (1.0.0b1) is the first preview of our efforts to create a user-friendly and Pythonic client library for Azure Monitor Ingestion.
7+
For more information about this, and preview releases of other Azure SDK libraries, please visit https://azure.github.io/azure-sdk/releases/latest/python.html.
8+
- Added `~azure.monitor.ingestion.LogsIngestionClient` to send logs to Azure Monitor along with `~azure.monitor.ingestion.aio.LogsIngestionClient`.
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
Copyright (c) Microsoft Corporation.
2+
3+
MIT License
4+
5+
Permission is hereby granted, free of charge, to any person obtaining a copy
6+
of this software and associated documentation files (the "Software"), to deal
7+
in the Software without restriction, including without limitation the rights
8+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
copies of the Software, and to permit persons to whom the Software is
10+
furnished to do so, subject to the following conditions:
11+
12+
The above copyright notice and this permission notice shall be included in all
13+
copies or substantial portions of the Software.
14+
15+
THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21+
SOFTWARE.
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
recursive-include tests *.py
2+
recursive-include samples *.py
3+
include *.md
4+
include LICENSE
5+
include azure/__init__.py
6+
include azure/monitor/__init__.py
7+
include azure/monitor/ingestion/py.typed
Lines changed: 195 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,195 @@
1+
# Azure Monitor Ingestion client library for Python
2+
3+
The Azure Monitor Ingestion client library is used to send custom logs to [Azure Monitor][azure_monitor_overview].
4+
5+
This library allows you to send data from virtually any source to supported built-in tables or to custom tables
6+
that you create in Log Analytics workspace. You can even extend the schema of built-in tables with custom columns.
7+
8+
**Resources:**
9+
10+
- [Source code][source]
11+
- [Package (PyPI)][package]
12+
- [API reference documentation][python-ingestion-ref-docs]
13+
- [Service documentation][azure_monitor_overview]
14+
- [Samples][samples]
15+
- [Change log][changelog]
16+
17+
## _Disclaimer_
18+
19+
_Azure SDK Python packages support for Python 2.7 has ended on 01 January 2022. For more information and questions, please refer to https://github.com/Azure/azure-sdk-for-python/issues/20691_
20+
21+
## Getting started
22+
23+
### Prerequisites
24+
25+
- Python 3.6 or later
26+
- An [Azure subscription][azure_subscription]
27+
- An [Azure Log Analytics workspace][azure_monitor_create_using_portal].
28+
- A [Data Collection Endpoint][data_collection_endpoint]
29+
- A [Data Collection Rule][data_collection_rule]
30+
31+
### Install the package
32+
33+
Install the Azure Monitor Ingestion client library for Python with [pip][pip]:
34+
35+
```bash
36+
pip install azure-monitor-ingestion
37+
```
38+
39+
40+
### Create the client
41+
42+
An authenticated client is required to upload Logs to Azure Monitor. The library includes both synchronous and asynchronous forms of the clients. To authenticate, create an instance of a token credential. Use that instance when creating a `LogsIngestionClient`. The following examples use `DefaultAzureCredential` from the [azure-identity](https://pypi.org/project/azure-identity/) package.
43+
44+
#### Synchronous clients
45+
46+
Consider the following example, which creates synchronous clients for uploading logs:
47+
48+
```python
49+
import os
50+
from azure.identity import DefaultAzureCredential
51+
from azure.monitor.ingestion import LogsIngestionClient
52+
53+
endpoint = os.environ['DATA_COLLECTION_ENDPOINT']
54+
credential = DefaultAzureCredential()
55+
logs_client = LogsIngestionClient(endpoint, credential)
56+
```
57+
58+
#### Asynchronous clients
59+
60+
The asynchronous forms of the client APIs are found in the `.aio`-suffixed namespace. For example:
61+
62+
```python
63+
import os
64+
from azure.identity.aio import DefaultAzureCredential
65+
from azure.monitor.ingestion.aio import LogsIngestionClient
66+
67+
endpoint = os.environ['DATA_COLLECTION_ENDPOINT']
68+
credential = DefaultAzureCredential()
69+
logs_client = LogsIngestionClient(endpoint, credential)
70+
```
71+
72+
## Key concepts
73+
74+
### Data Collection Endpoint
75+
76+
Data Collection Endpoints (DCEs) allow you to uniquely configure ingestion settings for Azure Monitor. [This
77+
article][data_collection_endpoint] provides an overview of data collection endpoints including their contents and
78+
structure and how you can create and work with them.
79+
80+
### Data Collection Rule
81+
82+
Data collection rules (DCR) define data collected by Azure Monitor and specify how and where that data should be sent or
83+
stored. The REST API call must specify a DCR to use. A single DCE can support multiple DCRs, so you can specify a
84+
different DCR for different sources and target tables.
85+
86+
The DCR must understand the structure of the input data and the structure of the target table. If the two don't match,
87+
it can use a transformation to convert the source data to match the target table. You may also use the transform to
88+
filter source data and perform any other calculations or conversions.
89+
90+
For more details, refer to [Data collection rules in Azure Monitor](https://docs.microsoft.com/azure/azure-monitor/essentials/data-collection-rule-overview).
91+
92+
### Log Analytics Workspace Tables
93+
94+
Custom logs can send data to any custom table that you create and to certain built-in tables in your Log Analytics
95+
workspace. The target table must exist before you can send data to it. The following built-in tables are currently supported:
96+
97+
- [CommonSecurityLog](https://docs.microsoft.com/azure/azure-monitor/reference/tables/commonsecuritylog)
98+
- [SecurityEvents](https://docs.microsoft.com/azure/azure-monitor/reference/tables/securityevent)
99+
- [Syslog](https://docs.microsoft.com/azure/azure-monitor/reference/tables/syslog)
100+
- [WindowsEvents](https://docs.microsoft.com/azure/azure-monitor/reference/tables/windowsevent)
101+
102+
## Examples
103+
104+
- [Upload custom logs](#upload-custom-logs)
105+
106+
### Upload custom logs
107+
108+
This example shows uploading logs to Azure monitor.
109+
110+
```python
111+
import os
112+
from azure.monitor.ingestion import LogsIngestionClient, UploadLogsStatus
113+
from azure.identity import DefaultAzureCredential
114+
115+
endpoint = os.environ['DATA_COLLECTION_ENDPOINT']
116+
credential = DefaultAzureCredential()
117+
118+
client = LogsIngestionClient(endpoint=endpoint, credential=credential, logging_enable=True)
119+
120+
rule_id = os.environ['LOGS_DCR_RULE_ID']
121+
body = [
122+
{
123+
"Time": "2021-12-08T23:51:14.1104269Z",
124+
"Computer": "Computer1",
125+
"AdditionalContext": "context-2"
126+
},
127+
{
128+
"Time": "2021-12-08T23:51:14.1104269Z",
129+
"Computer": "Computer2",
130+
"AdditionalContext": "context"
131+
}
132+
]
133+
134+
response = client.upload(rule_id=rule_id, stream_name=os.environ['LOGS_DCR_STREAM_NAME'], logs=body)
135+
if response.status != UploadLogsStatus.SUCCESS:
136+
failed_logs = response.failed_logs_index
137+
print(failed_logs)
138+
```
139+
140+
## Troubleshooting
141+
142+
Enable the `azure.monitor.ingestion` logger to collect traces from the library.
143+
144+
### General
145+
146+
Monitor Ingestion client library will raise exceptions defined in [Azure Core][azure_core_exceptions].
147+
148+
### Logging
149+
150+
This library uses the standard [logging][python_logging] library for logging. Basic information about HTTP sessions, such as URLs and headers, is logged at the `INFO` level.
151+
152+
### Optional configuration
153+
154+
Optional keyword arguments can be passed in at the client and per-operation level. The `azure-core` [reference documentation][azure_core_ref_docs] describes available configurations for retries, logging, transport protocols, and more.
155+
156+
## Next steps
157+
158+
To learn more about Azure Monitor, see the [Azure Monitor service documentation][azure_monitor_overview].
159+
160+
### Samples
161+
162+
The following code samples show common scenarios with the Azure Monitor Ingestion client library.
163+
164+
#### Logs Ingestion samples
165+
166+
- [Upload a list of logs](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/monitor/azure-monitor-ingestion/samples/sample_send_small_logs.py) ([async sample](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/monitor/azure-monitor-ingestion/samples/async_samples/sample_send_small_logs_async.py))
167+
168+
## Contributing
169+
170+
This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit [cla.microsoft.com][cla].
171+
172+
When you submit a pull request, a CLA-bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repositories using our CLA.
173+
174+
This project has adopted the [Microsoft Open Source Code of Conduct][code_of_conduct]. For more information see the [Code of Conduct FAQ][coc_faq] or contact [opencode@microsoft.com][coc_contact] with any additional questions or comments.
175+
176+
<!-- LINKS -->
177+
178+
[azure_core_exceptions]: https://aka.ms/azsdk/python/core/docs#module-azure.core.exceptions
179+
[azure_core_ref_docs]: https://aka.ms/azsdk/python/core/docs
180+
[azure_monitor_overview]: https://docs.microsoft.com/azure/azure-monitor/
181+
[azure_subscription]: https://azure.microsoft.com/free/python/
182+
[changelog]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/monitor/azure-monitor-ingestion/CHANGELOG.md
183+
[package]: https://aka.ms/azsdk-python-monitor-ingestion-pypi
184+
[pip]: https://pypi.org/project/pip/
185+
[python_logging]: https://docs.python.org/3/library/logging.html
186+
[python-ingestion-ref-docs]: https://aka.ms/azsdk/python/monitor-ingestion/docs
187+
[samples]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/monitor/azure-monitor-ingestion/samples
188+
[source]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/monitor/azure-monitor-ingestion/
189+
[data_collection_endpoint]: https://docs.microsoft.com//azure/azure-monitor/essentials/data-collection-endpoint-overview
190+
[data_collection_rule]: https://docs.microsoft.com/azure/azure-monitor/essentials/data-collection-rule-overview
191+
192+
[cla]: https://cla.microsoft.com
193+
[code_of_conduct]: https://opensource.microsoft.com/codeofconduct/
194+
[coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/
195+
[coc_contact]: mailto:opencode@microsoft.com
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
__path__ = __import__('pkgutil').extend_path(__path__, __name__) # type: ignore
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
__path__ = __import__('pkgutil').extend_path(__path__, __name__) # type: ignore
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
# coding=utf-8
2+
# --------------------------------------------------------------------------
3+
# Copyright (c) Microsoft Corporation. All rights reserved.
4+
# Licensed under the MIT License. See License.txt in the project root for license information.
5+
# Code generated by Microsoft (R) AutoRest Code Generator.
6+
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
7+
# --------------------------------------------------------------------------
8+
9+
from ._client import MonitorIngestionClient
10+
from ._models import UploadLogsResult, UploadLogsStatus
11+
12+
try:
13+
from ._patch import __all__ as _patch_all
14+
from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import
15+
except ImportError:
16+
_patch_all = []
17+
from ._patch import patch_sdk as _patch_sdk
18+
19+
__all__ = ["MonitorIngestionClient", "UploadLogsResult", "UploadLogsStatus"]
20+
__all__.extend([p for p in _patch_all if p not in __all__])
21+
22+
_patch_sdk()
Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
# coding=utf-8
2+
# --------------------------------------------------------------------------
3+
# Copyright (c) Microsoft Corporation. All rights reserved.
4+
# Licensed under the MIT License. See License.txt in the project root for license information.
5+
# Code generated by Microsoft (R) AutoRest Code Generator.
6+
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
7+
# --------------------------------------------------------------------------
8+
9+
from copy import deepcopy
10+
from typing import Any, TYPE_CHECKING
11+
12+
from msrest import Deserializer, Serializer
13+
14+
from azure.core import PipelineClient
15+
from azure.core.rest import HttpRequest, HttpResponse
16+
17+
from ._configuration import MonitorIngestionClientConfiguration
18+
from ._operations import MonitorIngestionClientOperationsMixin
19+
20+
if TYPE_CHECKING:
21+
# pylint: disable=unused-import,ungrouped-imports
22+
from typing import Dict
23+
24+
from azure.core.credentials import TokenCredential
25+
26+
27+
class MonitorIngestionClient(
28+
MonitorIngestionClientOperationsMixin
29+
): # pylint: disable=client-accepts-api-version-keyword
30+
"""Azure Monitor Data Collection Python Client.
31+
32+
:param endpoint: The Data Collection Endpoint for the Data Collection Rule, for example
33+
https://dce-name.eastus-2.ingest.monitor.azure.com. Required.
34+
:type endpoint: str
35+
:param credential: Credential needed for the client to connect to Azure. Required.
36+
:type credential: ~azure.core.credentials.TokenCredential
37+
:keyword api_version: Api Version. Default value is "2021-11-01-preview". Note that overriding
38+
this default value may result in unsupported behavior.
39+
:paramtype api_version: str
40+
"""
41+
42+
def __init__(
43+
self, endpoint: str, credential: "TokenCredential", **kwargs: Any
44+
) -> None:
45+
_endpoint = "{endpoint}"
46+
self._config = MonitorIngestionClientConfiguration(
47+
endpoint=endpoint, credential=credential, **kwargs
48+
)
49+
self._client = PipelineClient(base_url=_endpoint, config=self._config, **kwargs)
50+
51+
self._serialize = Serializer()
52+
self._deserialize = Deserializer()
53+
self._serialize.client_side_validation = False
54+
55+
def send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse:
56+
"""Runs the network request through the client's chained policies.
57+
58+
>>> from azure.core.rest import HttpRequest
59+
>>> request = HttpRequest("GET", "https://www.example.org/")
60+
<HttpRequest [GET], url: 'https://www.example.org/'>
61+
>>> response = client.send_request(request)
62+
<HttpResponse: 200 OK>
63+
64+
For more information on this code flow, see https://aka.ms/azsdk/python/protocol/quickstart
65+
66+
:param request: The network request you want to make. Required.
67+
:type request: ~azure.core.rest.HttpRequest
68+
:keyword bool stream: Whether the response payload will be streamed. Defaults to False.
69+
:return: The response of your network call. Does not do error handling on your response.
70+
:rtype: ~azure.core.rest.HttpResponse
71+
"""
72+
73+
request_copy = deepcopy(request)
74+
path_format_arguments = {
75+
"endpoint": self._serialize.url(
76+
"self._config.endpoint", self._config.endpoint, "str", skip_quote=True
77+
),
78+
}
79+
80+
request_copy.url = self._client.format_url(
81+
request_copy.url, **path_format_arguments
82+
)
83+
return self._client.send_request(request_copy, **kwargs)
84+
85+
def close(self):
86+
# type: () -> None
87+
self._client.close()
88+
89+
def __enter__(self):
90+
# type: () -> MonitorIngestionClient
91+
self._client.__enter__()
92+
return self
93+
94+
def __exit__(self, *exc_details):
95+
# type: (Any) -> None
96+
self._client.__exit__(*exc_details)

0 commit comments

Comments
 (0)