Skip to content

Commit 449ceb7

Browse files
authored
Merge pull request #2 from logicmonitor/DEV-73717-Logs-class-initialisation-failing-with-Type-Error
Log API call changes
2 parents f76f4fc + 74f848c commit 449ceb7

File tree

4 files changed

+77
-14
lines changed

4 files changed

+77
-14
lines changed

docs/source/index.rst

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,21 @@ Then run the program as:
8181
LM_COMPANY=<ACOUNT_NAME> LM_ACCESS_ID=<ID> LM_ACCESS_KEY='<KEY>' python disk_metrics.py
8282
8383
84+
Simple Example - Logs
85+
=====================
86+
87+
Run below script to send a log to Logicmonitor.
88+
89+
.. literalinclude:: ../../example/log_non_batch.py
90+
:language: python
91+
92+
then run the script as :
93+
94+
.. code:: python
95+
96+
pip install psutil
97+
python log_non_batch.py
98+
8499
.. _RST Configuration:
85100

86101
Configuration
@@ -107,6 +122,13 @@ Metrics Ingestion API
107122
.. automodule:: logicmonitor_data_sdk.api.metrics
108123
:members:
109124

125+
.. _RST LogsAPI:
126+
127+
Logs Ingestion API
128+
=====================
129+
.. automodule:: logicmonitor_data_sdk.api.logs
130+
:members:
131+
110132

111133
Models
112134
******

example/log_non_batch.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
2+
import logging
3+
import os
4+
import time
5+
6+
import psutil as psutil
7+
8+
import logicmonitor_data_sdk
9+
10+
from logicmonitor_data_sdk.api.logs import Logs
11+
from logicmonitor_data_sdk.models import Resource
12+
13+
logger = logging.getLogger('lmdata.api')
14+
logger.setLevel(logging.INFO)
15+
16+
configuration = logicmonitor_data_sdk.Configuration(company='yourcompany',
17+
id='accessID',
18+
key='accessKey')
19+
20+
21+
resource = Resource(ids={"System.hostname": "192.168.1.33"})
22+
log_api = Logs(batch = False)
23+
log_api.send_logs(resource = resource,msg= "this is smaple log")
24+
25+
26+
27+
28+
29+

logicmonitor_data_sdk/api/logs.py

Lines changed: 26 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# coding: utf-8
1+
# coding: utf-8
22
"""
33
Logs API client: It formats and submit REST API calls to LogicMonitor.
44
"""
@@ -52,10 +52,12 @@ def send_logs(self, **kwargs): # noqa: E501
5252
5353
Args:
5454
resource (:class:`logicmonitor_data_sdk.models.resource.Resource`): The Resource object.
55-
logs (:obj:`dict`): The logs details in dictonary. e.g. {'msg' : 'This is sample logs'}.
55+
msg (:obj:`str`): The log message. e.g. msg = "this is sample log msg".
56+
timestamp (:obj:`str` or :obj:`int`, Optional): The timestamp when the event occurred. Supported date formats are ISO8601 and Unix Epoch (in secs, ms, ns).
57+
metadata (:obj:`dict`,Optional): Metadata which can be used for defining logsource and other properties.
5658
5759
Return:
58-
If in :class:`Metrics` batching is enabled then None
60+
If in :class:`Logs` batching is enabled then None
5961
Otherwise the REST response will be return.
6062
6163
Examples:
@@ -66,10 +68,10 @@ def send_logs(self, **kwargs): # noqa: E501
6668
>>>
6769
>>> conf = Configuration(company="ACCOUNT_NAME", id= 'API_ACCESS_ID', key= 'API_ACCESS_KEY')
6870
>>> # Create the Log client with batching enable
69-
>>> log_api = Logs()
70-
>>> # Create the Resource object using the 'system.deviceId' properties.
71+
>>> log_api = Logs() # By default batching is enabled with interval of 30 sec.
72+
>>> # Create the Resource object using the 'system.hostname' properties.
7173
>>> resource = Resource(ids={"system.hostname": "SampleDevice"}, name="SampleDevice", properties={'using.sdk': 'true'})
72-
>>> log_api.send_logs(resource=resource, logs={'msg' : 'This is sample logs'})
74+
>>> log_api.send_logs(resource=resource, msg = "this is a sample log")
7375
"""
7476

7577
"""LogIngestApi # noqa: E501
@@ -88,28 +90,34 @@ def send_logs(self, **kwargs): # noqa: E501
8890
returns the request thread.
8991
"""
9092

91-
all_params = ['resource', 'logs'] # noqa: E501
93+
all_params = ['resource', 'msg','timestamp', 'metadata'] # noqa: E501
9294
params = locals()
9395
for key, val in six.iteritems(params['kwargs']):
9496
if key not in all_params:
9597
raise TypeError(
96-
"Got an unexpected keyword argument '%s' to method SendMetrics" % key
98+
"Got an unexpected keyword argument '%s' to method send_logs()" % key
9799
)
98100
params[key] = val
99101
del params['kwargs']
100102
del params['self']
101103
del params['all_params']
102104
for one in all_params:
103-
if not params.__contains__(one):
105+
if (one!='timestamp' and one!='metadata') and (not params.__contains__(one)):
104106
raise TypeError(
105107
"Some arguments are missing keys='%s'" %
106-
str(params.keys())
108+
one
107109
)
108110
# logger.debug("Request Send for {}".format(str(params['resource'].ids)))
109111
if self.batch:
110112
# self.add_request(**kwargs)
113+
logs = {}
114+
logs['msg'] = kwargs['msg']
115+
if kwargs.__contains__('timestamp'):
116+
logs['timestamp'] = kwargs['timestamp']
117+
if kwargs.__contains__('metadata'):
118+
logs['metadata'] = kwargs['metadata']
111119
self.add_request(resource=copy.deepcopy(kwargs['resource']),
112-
logs=kwargs['logs'])
120+
logs=logs)
113121
else:
114122
return self._single_request(**kwargs)
115123

@@ -149,13 +157,18 @@ def _do_request(self):
149157
def _merge_request(self, single_request):
150158
resource = single_request['resource']
151159
logs = single_request['logs']
152-
logs['_lm.resourceId'] = resource.ids
160+
logs['_lm.resourceId'] = resource.ids
153161
self._payload_cache.append(logs)
154162

155163
def _single_request(self, **kwargs):
156164
resource = kwargs['resource']
157-
logs = kwargs['logs']
165+
logs = {}
166+
logs['msg']= kwargs['msg']
158167
logs['_lm.resourceId'] = resource.ids
168+
if kwargs.__contains__('timestamp'):
169+
logs['timestamp'] = kwargs['timestamp']
170+
if kwargs.__contains__('metadata'):
171+
logs['metadata'] = kwargs['metadata']
159172
body = []
160173
body.append(logs)
161174
return self.make_request(path='/log/ingest', method='POST',

logicmonitor_data_sdk/version.py

Lines changed: 0 additions & 1 deletion
This file was deleted.

0 commit comments

Comments
 (0)