Skip to content

Commit

Permalink
Version 0.1.2
Browse files Browse the repository at this point in the history
Runtime fixes
  • Loading branch information
hbldh committed Sep 19, 2024
1 parent 7093a03 commit 8e41ab0
Show file tree
Hide file tree
Showing 6 changed files with 51 additions and 16 deletions.
2 changes: 1 addition & 1 deletion examples/nodinite.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ def main():
logger.setLevel(logging.DEBUG)
logger.addHandler(
NodiniteLogAPIEventHandler(
"https://nodiniteinstall.westeurope.cloudapp.azure.com/Nodinite/Test",
"https://integrationswedwise.westeurope.cloudapp.azure.com/Nodinite/Test",
2,
"Python API Handler",
"http://localhost:8000",
Expand Down
2 changes: 1 addition & 1 deletion src/pynodinite/__about__.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
__version__ = "0.1.1"
__version__ = "0.1.2"
15 changes: 10 additions & 5 deletions src/pynodinite/core.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
import base64
import datetime
import getpass
import json
import logging
import os
from sys import platform
import platform

from pynodinite.enums import EndpointType, EventDirections




class NodiniteBaseLogEventHandler(logging.Handler):
def __init__(
self,
Expand Down Expand Up @@ -54,6 +57,7 @@ def format(self, record: logging.LogRecord) -> str:
string ProcessingTime - Flow execution time so far in milliseconds
"""
dt = datetime.datetime.now()
# TODO: How to handle context values? Args? Extra?
direction = record.args[0].value if record.args else EventDirections.DEFAULT.value
context = record.args[1] if record.args and len(record.args) > 1 and isinstance(record.args[1], dict) else {}
Expand All @@ -68,20 +72,21 @@ def format(self, record: logging.LogRecord) -> str:
"EndPointDirection": 1, # Direction for Endpoint transport
"EndPointTypeId": self.endpoint_type_id, # Type of Endpoint transport
"OriginalMessageTypeName": record.name, # The name of the message type
"LogDateTime": datetime.datetime.fromtimestamp(record.created).isoformat(),
"LogDateTime": dt.isoformat(), #datetime.datetime.fromtimestamp(record.created).isoformat(),
# Optional fields ----------------------------------------------------------
"SequenceNo": record.args[3] if record.args and len(record.args) > 3 else "",
"EventDirection": direction,
"ProcessingUser": f"{os.environ['userdomain']}\\{getpass.getuser()}",
"LogText": record.msg,
"LogStatus": record.levelno,
"LogStatus": str(record.levelno),
"ProcessName": record.processName,
"ProcessingMachineName": platform.node(),
"ProcessingModuleName": __name__,
"ProcessingModuleType": "Python Application",
"ProcessingModuleType": "pyNodinite",
"Body": base64.b64encode(body.encode()).decode("ascii"),
"Context": context,
}
return doc
return json.dumps(doc)

def emit(self, record: logging.LogRecord) -> None:
raise NotImplementedError("Do not use this base class!")
2 changes: 1 addition & 1 deletion src/pynodinite/enums.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ class EndpointDirection(Enum):
RECEIVE = 0
# Send -One-Way, for example, send a file to SFTP
SEND = 1
# Two-way Receive -For example an An API sponsoring incoming requests
# Two-way Receive -For example an API sponsoring incoming requests
TWOWAY_RECEIVE = 10
# Two-way Send - A client calling some REST API or a call to a stored parameterized procedure
TWOWAY_SEND = 11
Expand Down
30 changes: 27 additions & 3 deletions src/pynodinite/handlers/activemq.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,36 @@
import logging
import threading

try:
import stomp
except ImportError:
pass

from pynodinite.core import NodiniteBaseLogEventHandler


class NodiniteActiveMQHandler(NodiniteBaseLogEventHandler):
def __init__(self, log_agent_id, endpoint_name, endpoint_uri, endpoint_type_id):
def __init__(self, host, port, username, password, destination, log_agent_id, endpoint_name, endpoint_uri, endpoint_type_id):
super().__init__(log_agent_id, endpoint_name, endpoint_uri, endpoint_type_id)
raise NotImplementedError()
self.host = host
self.port = port
self.username = username
self.password = password
self.destination = destination

self.lock = threading.Lock()
self.conn = None

def emit(self, record: logging.LogRecord) -> None:
pass
doc = self.format(record)

with self.lock:
if self.conn is None or not self.conn.is_connected():
self.conn = stomp.Connection([(self.host, self.port)])
self.conn.set_listener('', stomp.ConnectionListener())
self.conn.set_socket_keepalive(True, 60) # set keepalive timeout to 60 seconds
self.conn.start()
self.conn.connect(self.username, self.password)

self.conn.send(body=doc, destination=self.destination)

16 changes: 11 additions & 5 deletions src/pynodinite/handlers/direct.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import datetime
import json
import logging
from threading import Thread
from urllib.error import HTTPError
from urllib.request import Request, urlopen

from pynodinite.core import NodiniteBaseLogEventHandler
Expand Down Expand Up @@ -51,14 +53,18 @@ def _send_to_log_api(self, record: logging.LogRecord) -> None:
doc = self.format(record)
req = Request(
f"{self._logapi_url}/LogAPI/api/logevent",
json.dumps(doc, ensure_ascii=True).encode("ascii"),
{"Content-Type": "application/json"},
data=doc.encode('utf-8'),
headers={"Content-Type": "application/json"},
method="POST",
)

with urlopen(req) as response:
result = json.loads(response.read())
try:
with urlopen(req) as response:
result = json.loads(response.read())
except HTTPError as e:
print(e)

if result["status"] != 0:
if result["Status"] != 0:
# Error has occurred.
# TODO: Handle exceptions?
pass
Expand Down

0 comments on commit 8e41ab0

Please sign in to comment.