Skip to content

Commit

Permalink
feat(logger): possibility to override debug mode's default logging me…
Browse files Browse the repository at this point in the history
…chanism
  • Loading branch information
KaiSchwarz-cnic committed May 7, 2020
1 parent 65c68db commit 944d9de
Show file tree
Hide file tree
Showing 6 changed files with 115 additions and 10 deletions.
3 changes: 1 addition & 2 deletions AUTHORS.md
@@ -1,5 +1,4 @@
> ⚠ This document _only_ reflects the responsible developers at HEXONET GmbH. For a list of MUCH-APPRECIATED CONTRIBUTORS -- people who helped developing and extending this library, applying patches, adding helpful comments
and thus generally made it that much better, see [GitHub's list of contributors](https://github.com/hexonet/python-sdk/contributors).

* [Anthony Schneider](//github.com/anthonyschn) - Original Implementation
* [Kai Schwarz](//github.com/papakai) - Full Review
* [Kai Schwarz](//github.com/papakai) - Development Lead
24 changes: 24 additions & 0 deletions README.md
Expand Up @@ -23,6 +23,7 @@ This module is a connector library for the insanely fast HEXONET Backend API. Fo
* Automatic IDN Domain name conversion to punycode (our API accepts only punycode format in commands)
* Allows nested associative arrays in API commands to improve for bulk parameters
* Connecting and communication with our API
* Possibility to use a custom mechanism for debug mode
* Several ways to access and deal with response data
* Getting the command again returned together with the response
* Sessionless communication
Expand Down Expand Up @@ -91,6 +92,29 @@ e.g. `$cl->setURL("http://127.0.0.1:8765/api/call.cgi");` would change the port.

Don't use `https` for that setup as it leads to slowing things down as of the https `overhead` of securing the connection. In this setup we just connect to localhost, so no direct outgoing network traffic using `http`. The apache configuration finally takes care passing it to `https` for the final communication to the HEXONET API.

### Customize Logging / Outputs

When having the debug mode activated hexonet.apiconnector.logger will be used for doing outputs by default.
Of course it could be of interest for integrators to look for a way of getting this replaced by a custom mechanism like forwarding things to a 3rd-party software, logging into file or whatever.

```python
from hexonet.apiconnector.apiclient import APIClient as AC
# import your module from your custom namespace of course
from hexonet.apiconnector.customlogger import CustomLogger as CL

cl = AC()
# LIVE System would be used otherwise by default
cl.useOTESystem()
# enable debug output (inactive by default)
cl.enableDebugMode()
# provide your custom logger mechanism
cl.setCustomLogger(CL())
cl.setCredentials("test.user", "test.passw0rd")
r = cl.request({"COMMAND" => "StatusAccount"})
```

NOTE: Find an example for a custom logger class implementation in `hexonet/apiconnector/customlogger.py`. If you have questions, feel free to open a github issue.

## How to use this module in your project

All you need to know, can be found [here](https://hexonet-python-sdk.readthedocs.io/en/latest/#usage-guide).
Expand Down
30 changes: 24 additions & 6 deletions hexonet/apiconnector/apiclient.py
Expand Up @@ -8,6 +8,7 @@
:license: MIT, see LICENSE for more details.
"""

from hexonet.apiconnector.logger import Logger
from hexonet.apiconnector.response import Response
from hexonet.apiconnector.responsetemplatemanager import ResponseTemplateManager as RTM
from hexonet.apiconnector.socketconfig import SocketConfig
Expand Down Expand Up @@ -39,6 +40,22 @@ def __init__(self):
self.__ua = ""
# additional connection settings
self.__curlopts = {}
# logger class instance
self.setDefaultLogger()

def setCustomLogger(self, logger):
"""
Set custom logger to use instead of the default one
"""
self.__logger = logger
return self

def setDefaultLogger(self):
"""
Set default logger to use
"""
self.__logger = Logger()
return self

def setProxy(self, proxy):
"""
Expand Down Expand Up @@ -270,6 +287,7 @@ def request(self, cmd):
}
data = self.getPOSTData(newcmd).encode('UTF-8')
secured = self.getPOSTData(newcmd, True).encode('UTF-8')
error = None
try:
headers = {
'User-Agent': self.getUserAgent()
Expand All @@ -281,13 +299,13 @@ def request(self, cmd):
proxyurl = urlparse(self.__curlopts["PROXY"])
req.set_proxy(proxyurl.netloc, proxyurl.scheme)
body = urlopen(req, timeout=self.__socketTimeout).read()
if (self.__debugMode):
print((self.__socketURL, secured, body, '\n', '\n'))
except Exception:
except Exception as e:
error = str(e)
body = rtm.getTemplate("httperror").getPlain()
if (self.__debugMode):
print((self.__socketURL, secured, "HTTP communication failed", body, '\n', '\n'))
return Response(body, newcmd, cfg)
r = Response(body, newcmd, cfg)
if (self.__debugMode):
self.__logger.log(secured, r, error)
return r

def requestNextResponsePage(self, rr):
"""
Expand Down
37 changes: 37 additions & 0 deletions hexonet/apiconnector/customlogger.py
@@ -0,0 +1,37 @@
# -*- coding: utf-8 -*-
"""
hexonet.apiconnector.customlogger
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This module provides all necessary functionality for
debug outputs
:copyright: © 2020 by HEXONET GmbH.
:license: MIT, see LICENSE for more details.
"""

from hexonet.apiconnector.logger import Logger
import sys


class CustomLogger(Logger, object):
"""
The Logger class covers all you need to cover debug outputs of the API communication.
"""

def __init__(self):
"""
constructor calling parent constructor
"""
super(CustomLogger, self).__init__()

def log(self, post, r, error):
"""
output/log given data
"""
#
# implement your own logic here
#
# print(r.getCommandPlain())
# print(post)
# if error:
# print("HTTP communication failed: %s" % (error), sys.stderr)
# print(r.getPlain())
27 changes: 27 additions & 0 deletions hexonet/apiconnector/logger.py
@@ -0,0 +1,27 @@
# -*- coding: utf-8 -*-
"""
hexonet.apiconnector.logger
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This module provides all necessary functionality for
debug outputs see the customlogger class on how to override this
:copyright: © 2018 by HEXONET GmbH.
:license: MIT, see LICENSE for more details.
"""

import sys


class Logger(object):
"""
The Logger class covers all you need to cover debug outputs of the API communication.
"""

def log(self, post, r, error):
"""
output/log given data
"""
print(r.getCommandPlain())
print(post)
if error:
print("HTTP communication failed: %s" % (error), sys.stderr)
print(r.getPlain())
4 changes: 2 additions & 2 deletions setup.py
Expand Up @@ -35,8 +35,8 @@ def find_version(*file_paths):
description=PACKAGE + ' is a connector library for the insanely fast HEXONET Backend API',
long_description=long_description,
long_description_content_type="text/markdown",
author='Anthony Schneider',
author_email='anthonys@hexonet.net',
author='Kai Schwarz',
author_email='kschwarz@hexonet.net',
maintainer='Kai Schwarz',
maintainer_email='kschwarz@hexonet.net',
url='https://github.com/hexonet/python-sdk/',
Expand Down

0 comments on commit 944d9de

Please sign in to comment.