Skip to content

Commit 60f5d49

Browse files
alexcos78alvarolopez
authored andcommitted
feat: add support to logstash
1 parent 9be0fe3 commit 60f5d49

File tree

2 files changed

+41
-4
lines changed

2 files changed

+41
-4
lines changed

caso/messenger/logstash.py

Lines changed: 25 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,10 @@
2424

2525
from caso import exception
2626
import caso.messenger
27-
27+
#add json lib
28+
import json
29+
#add datetime lib
30+
import datetime
2831

2932
opts = [
3033
cfg.StrOpt("host", default="localhost", help="Logstash host to send records to."),
@@ -49,11 +52,29 @@ def __init__(self, host=CONF.logstash.host, port=CONF.logstash.port):
4952
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
5053

5154
def push(self, records):
55+
56+
# NOTE(acostantini): code for the serialization and push of the
57+
# records in logstash. JSON format to be used and encoding UTF-8
58+
"""Serialization of records to be sent to logstash"""
59+
if not records:
60+
return
61+
62+
#Actual timestamp to be added on each record
63+
cdt = datetime.datetime.now()
64+
ct = int(datetime.datetime.now().timestamp())
65+
66+
#Open the connection with LS
67+
self.sock.connect((self.host, self.port))
68+
5269
"""Push records to logstash using tcp."""
5370
try:
54-
self.sock.connect((self.host, self.port))
55-
for _, record in six.iteritems(records):
56-
self.sock.sendall(record.as_json() + "\n")
71+
for record in records:
72+
#serialization of record
73+
rec=record.logstash_message()
74+
#cASO timestamp added to each record
75+
rec['caso-timestamp']=ct
76+
#Send the record to LS
77+
self.sock.send((json.dumps(rec)+'\n').encode('utf-8'))
5778
except socket.error as e:
5879
raise exception.LogstashConnectionError(
5980
host=self.host, port=self.port, exception=e

caso/record.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,22 @@ def ssm_message(self):
4949
raise NotImplementedError("Method not implemented")
5050

5151

52+
def logstash_message(self):
53+
"""Render record as the expected logstash message."""
54+
opts = {
55+
"by_alias": True,
56+
"exclude_none": True,
57+
}
58+
# NOTE(acostatnini): part related to the definition of the logstash message to be
59+
# serialized before to send data
60+
# NOTE(aloga): do not iter over the dictionary returned by record.dict() as this
61+
# is just a dictionary representation of the object, where no serialization is
62+
# done. In order to get objects correctly serialized we need to convert to JSON,
63+
# then reload the model
64+
serialized_record = json.loads(self.json(**opts))
65+
return serialized_record
66+
67+
5268
class _ValidCloudStatus(str, enum.Enum):
5369
"""This is a private class to enum valid cloud statuses."""
5470

0 commit comments

Comments
 (0)