Skip to content

Commit 4e2d587

Browse files
Added version support and example for disk monitoring.
1 parent 95c8446 commit 4e2d587

File tree

10 files changed

+214
-87
lines changed

10 files changed

+214
-87
lines changed

README.md

Lines changed: 84 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -25,43 +25,98 @@ Requirements.
2525

2626
Python 2.7 and 3.4+
2727

28+
Documentation
29+
-------------
30+
https://logicmonitor-api-sdk-py.readthedocs.io/en/latest/
31+
32+
2833
Getting Started
2934
---------------
3035

31-
Please install using pip and then run below a working example for submitting the metrics to your account:
36+
Please install using pip and then run below a working example for submitting the disk metrics to
37+
your LM account. This script will monitor the Usage, Free and Total of the disk at every 10 sec
38+
interval.
3239

3340
```python
34-
35-
from __future__ import print_function
41+
import logging
42+
import os
43+
import sys
3644
import time
37-
import random
45+
46+
import psutil as psutil
47+
3848
import logicmonitor_api_sdk
39-
49+
from logicmonitor_api_sdk.api.response_interface import ResonseInterface
50+
from logicmonitor_api_sdk.models import Resource, DataSource, DataPoint, \
51+
DataSourceInstance
52+
4053
from logicmonitor_api_sdk.api.metrics import Metrics
41-
from logicmonitor_api_sdk.models.resource import Resource
42-
from logicmonitor_api_sdk.models.datasource import DataSource
43-
from logicmonitor_api_sdk.models.datasource_instance import DataSourceInstance
44-
from logicmonitor_api_sdk.models.datapoint import DataPoint
45-
46-
# Configure API key authorization: LMv1
47-
configuration = logicmonitor_api_sdk.Configuration(company = 'YOUR_COMPANY', authentication={ 'id': 'YOUR_ACCESS_ID', 'key' : 'YOUR_ACCESS_KEY'})
48-
49-
# create an instance of the API class
50-
metric_api = Metrics(interval=20, batch = True)
51-
resource = Resource(ids={"system.hostname": "SampleDevice"}, create=True, name="SampleDevice", properties={'using.sdk': 'true'})
52-
ds = DataSource(name="DSName")
53-
instance = DataSourceInstance(name="instance")
54-
dp = DataPoint(name="dataPoint")
55-
56-
while True:
57-
# Generate the random data for current epoch.
58-
values = {str(int(time.time())): random.randint(10, 100)}
59-
metric_api.send_metrics(resource=resource,
60-
datasource=ds,
61-
instance=instance,
62-
datapoint=dp,
63-
values=values)
64-
time.sleep(10)
54+
55+
logger = logging.getLogger('lmingest.api')
56+
logger.setLevel(logging.INFO)
57+
58+
configuration = logicmonitor_api_sdk.Configuration()
59+
# For debug log, set the value to True
60+
configuration.debug = True
61+
62+
63+
class MyResponse(ResonseInterface):
64+
"""
65+
Sample callback to handle the response from the REST endpoints
66+
"""
67+
68+
def success_callback(self, request, response, status, request_id):
69+
logger.info("%s: %s: %s", response, status, request_id)
70+
71+
def error_callback(self, request, response, status, request_id, reason):
72+
logger.error("%s: %s: %s %s", response, status, reason, request_id)
73+
74+
75+
def MetricRequest():
76+
"""
77+
Main function to get the CPU values using `psutil` and send to Metrics REST endpoint
78+
"""
79+
device_name = os.uname()[1]
80+
resource = Resource(ids={'system.displayname': device_name}, name=device_name,
81+
create=True)
82+
datasource = DataSource(name="DiskUsingSDK")
83+
datapoints = ['total', 'used', 'free']
84+
metric_api = Metrics(batch=True, interval=10, response_callback=MyResponse())
85+
while True:
86+
partitions = psutil.disk_partitions()
87+
for p in partitions:
88+
instance_name = p.device
89+
usage = psutil.disk_usage(instance_name).__dict__
90+
# Create the instance object for every device. Name should not have the
91+
# special characters so replacing it with the '-'.
92+
instance = DataSourceInstance(name=instance_name.replace('/', '-'),
93+
display_name=instance_name)
94+
for one_datapoint in datapoints:
95+
datapoint = DataPoint(name=one_datapoint)
96+
values = {str(int(time.time())): str(usage[one_datapoint])}
97+
metric_api.send_metrics(resource=resource,
98+
datasource=datasource,
99+
instance=instance,
100+
datapoint=datapoint,
101+
values=values)
102+
time.sleep(10)
103+
104+
105+
if __name__ == "__main__":
106+
MetricRequest()
107+
108+
```
109+
110+
Then run the program as:
111+
112+
```python
113+
114+
pip install psutil
115+
LM_COMPANY=<ACOUNT_NAME> LM_ACCESS_ID=<ID> LM_ACCESS_KEY='<KEY>' python disk_metrics.py
65116
```
66117

67118

119+
Get in Touch
120+
------------
121+
122+
If you'd like to suggest a feature or report a bug, please add an issue `here <https://github.com/logicmonitor/logicmonitor_api_sdk_py/issues>`_.

docs/source/conf.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,21 +17,24 @@
1717
sys.setrecursionlimit(1500)
1818

1919
# -- Project information -----------------------------------------------------
20+
_version = {}
21+
with open("../../logicmonitor_api_sdk/version.py") as fp:
22+
exec(fp.read(), _version)
2023

2124
project = 'LogicMonitor API SDK Python'
2225
copyright = '2021, Logicmonitor'
2326
author = 'Logicmonitor'
2427

2528
# The full version, including alpha/beta/rc tags
26-
release = '0.0.1'
29+
release = str(_version["__version__"])
2730

2831
# -- General configuration ---------------------------------------------------
2932

3033
# Add any Sphinx extension module names here, as strings. They can be
3134
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
3235
# ones.
3336
# extensions = ['rinoh.frontend.sphinx', 'sphinx.ext.autodoc', 'sphinx_markdown_builder']
34-
extensions = ['sphinx.ext.napoleon', 'sphinx.ext.autosectionlabel']
37+
extensions = ['sphinx.ext.napoleon', 'sphinx.ext.autosectionlabel', ]
3538

3639
# Add any paths that contain templates here, relative to this directory.
3740
templates_path = ['_templates']

docs/source/index.rst

Lines changed: 17 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -21,11 +21,6 @@ alerting.
2121
More details are available on `support
2222
site <https://www.logicmonitor.com/support>`__
2323

24-
Version
25-
*******
26-
27-
- API version: 0.0.1
28-
- Package version: 0.0.1.beta
2924

3025
Requirements.
3126
*************
@@ -45,11 +40,11 @@ Github
4540

4641
.. code:: sh
4742
48-
pip install logicmonitor_api_sdk_py
43+
pip install logicmonitor_api_sdk
4944
5045
| (you may need to run ``pip`` with root permission:
5146
52-
``sudo pip install logicmonitor_api_sdk_py``)
47+
``sudo pip install logicmonitor_api_sdk``)
5348

5449
Then import the package:
5550

@@ -61,39 +56,19 @@ Then import the package:
6156
Getting Started
6257
***************
6358

64-
Please follow the :ref:`RST Installation` and then run below a working example for submitting the metrics to your account:
65-
66-
.. code:: python
67-
68-
from __future__ import print_function
69-
import time
70-
import random
71-
import logicmonitor_api_sdk
59+
Please follow the :ref:`RST Installation` and then run below a working example for submitting the disk
60+
metrics to your LM account. This script will monitor the Usage, Free and Total of the disk at
61+
every 10 sec interval.
7262

73-
from logicmonitor_api_sdk.api.metrics import Metrics
74-
from logicmonitor_api_sdk.models.resource import Resource
75-
from logicmonitor_api_sdk.models.datasource import DataSource
76-
from logicmonitor_api_sdk.models.datasource_instance import DataSourceInstance
77-
from logicmonitor_api_sdk.models.datapoint import DataPoint
63+
.. literalinclude:: ../../example/disk_metrics.py
64+
:language: python
7865

79-
# Configure API key authorization: LMv1
80-
configuration = logicmonitor_api_sdk.Configuration(company = 'YOUR_COMPANY', authentication={ 'id': 'YOUR_ACCESS_ID', 'key' : 'YOUR_ACCESS_KEY'})
66+
Then run the program as:
8167

82-
# create an instance of the API class
83-
metric_api = Metrics(interval=20, batch = True)
84-
resource = Resource(ids={"system.hostname": "SampleDevice"}, create=True, name="SampleDevice", properties={'using.sdk': 'true'})
85-
ds = DataSource(name="DSName")
86-
instance = DataSourceInstance(name="instance")
87-
dp = DataPoint(name="dataPoint")
68+
.. code:: python
8869
89-
while True:
90-
values = {str(int(time.time())): random.randint(10, 100)}
91-
metric_api.send_metrics(resource=resource,
92-
datasource=ds,
93-
instance=instance,
94-
datapoint=dp,
95-
values=values)
96-
time.sleep(10)
70+
pip install psutil
71+
LM_COMPANY=<ACOUNT_NAME> LM_ACCESS_ID=<ID> LM_ACCESS_KEY='<KEY>' python disk_metrics.py
9772
9873
9974
.. _RST Configuration:
@@ -164,3 +139,9 @@ ResonseInterface
164139
.. |se| raw:: html
165140

166141
</strike>
142+
143+
144+
Get in Touch
145+
============
146+
147+
If you'd like to suggest a feature or report a bug, please add an issue `here <https://github.com/logicmonitor/logicmonitor_api_sdk_py/issues>`_.

example/cpu_metrics.py

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,25 +6,25 @@
66
import psutil as psutil
77

88
sys.path.append("..")
9+
import logicmonitor_api_sdk
910
from logicmonitor_api_sdk.api.response_interface import ResonseInterface
1011
from logicmonitor_api_sdk.models import Resource, DataSource, DataPoint, \
1112
DataSourceInstance
1213

13-
import logicmonitor_api_sdk
1414
from logicmonitor_api_sdk.api.metrics import Metrics
1515

1616
logger = logging.getLogger('lmingest.api')
1717
logger.setLevel(logging.INFO)
1818

19-
configuration = logicmonitor_api_sdk.Configuration(company='COMPANY_NAME',
20-
authentication={
21-
'id': 'ID',
22-
'key': 'KEY'})
23-
19+
configuration = logicmonitor_api_sdk.Configuration()
20+
# For debug log, set the value to True
2421
configuration.debug = False
2522

2623

2724
class MyResponse(ResonseInterface):
25+
"""
26+
Sample callback to handle the response from the REST endpoints
27+
"""
2828

2929
def success_callback(self, request, response, status, request_id):
3030
logger.info("%s: %s: %s", response, status, request_id)
@@ -34,6 +34,9 @@ def error_callback(self, request, response, status, request_id, reason):
3434

3535

3636
def MetricRequest():
37+
"""
38+
Main function to get the CPU values using `psutil` and send to Metrics REST endpoint
39+
"""
3740
device_name = os.uname()[1]
3841
resource = Resource(ids={'system.displayname': device_name}, name=device_name,
3942
create=True)
@@ -52,4 +55,5 @@ def MetricRequest():
5255
time.sleep(10)
5356

5457

55-
MetricRequest()
58+
if __name__ == "__main__":
59+
MetricRequest()

example/disk_metrics.py

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
import logging
2+
import os
3+
import sys
4+
import time
5+
6+
import psutil as psutil
7+
8+
sys.path.append("..")
9+
import logicmonitor_api_sdk
10+
from logicmonitor_api_sdk.api.response_interface import ResonseInterface
11+
from logicmonitor_api_sdk.models import Resource, DataSource, DataPoint, \
12+
DataSourceInstance
13+
14+
from logicmonitor_api_sdk.api.metrics import Metrics
15+
16+
logger = logging.getLogger('lmingest.api')
17+
logger.setLevel(logging.INFO)
18+
19+
configuration = logicmonitor_api_sdk.Configuration()
20+
# For debug log, set the value to True
21+
configuration.debug = False
22+
23+
24+
class MyResponse(ResonseInterface):
25+
"""
26+
Sample callback to handle the response from the REST endpoints
27+
"""
28+
29+
def success_callback(self, request, response, status, request_id):
30+
logger.info("%s: %s: %s", response, status, request_id)
31+
32+
def error_callback(self, request, response, status, request_id, reason):
33+
logger.error("%s: %s: %s %s", response, status, reason, request_id)
34+
35+
36+
def MetricRequest():
37+
"""
38+
Main function to get the CPU values using `psutil` and send to Metrics REST endpoint
39+
"""
40+
device_name = os.uname()[1]
41+
resource = Resource(ids={'system.displayname': device_name}, name=device_name,
42+
create=True)
43+
datasource = DataSource(name="DiskUsingSDK")
44+
datapoints = ['total', 'used', 'free']
45+
metric_api = Metrics(batch=True, interval=10, response_callback=MyResponse())
46+
while True:
47+
partitions = psutil.disk_partitions()
48+
for p in partitions:
49+
# Using the device as instance name. We can use the mountpoint as well.
50+
instance_name = p.device
51+
usage = psutil.disk_usage(instance_name).__dict__
52+
# Create the instance object for every device. Name should not have the
53+
# special characters so replacing it with the '-'.
54+
instance = DataSourceInstance(name=instance_name.replace('/', '-'),
55+
display_name=instance_name)
56+
for one_datapoint in datapoints:
57+
datapoint = DataPoint(name=one_datapoint)
58+
values = {str(int(time.time())): str(usage[one_datapoint])}
59+
metric_api.send_metrics(resource=resource,
60+
datasource=datasource,
61+
instance=instance,
62+
datapoint=datapoint,
63+
values=values)
64+
time.sleep(10)
65+
66+
67+
if __name__ == "__main__":
68+
MetricRequest()

logicmonitor_api_sdk/__init__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,3 +24,4 @@
2424
from logicmonitor_api_sdk.models.rest_metrics_v1 import RestMetricsV1
2525
from logicmonitor_api_sdk.models.rest_resource_properties_v1 import \
2626
RestResourcePropertiesV1
27+
from logicmonitor_api_sdk.version import __version__

0 commit comments

Comments
 (0)