Skip to content

Commit

Permalink
#186810782 Fix logging (#22)
Browse files Browse the repository at this point in the history
* change print to log
* warning for 400 error
  • Loading branch information
HzANut authored Jan 11, 2024
1 parent ccb97fb commit d6d54a0
Show file tree
Hide file tree
Showing 6 changed files with 42 additions and 34 deletions.
12 changes: 6 additions & 6 deletions moesifpythonrequest/app_config/app_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@
from moesifapi.exceptions.api_exception import *
import json
from .regex_config_helper import RegexConfigHelper
import logging

logger = logging.getLogger(__name__)

# Application Configuration
class AppConfig:
Expand All @@ -17,18 +19,17 @@ def get_config(self, api_client, debug):
return config_api_response
except APIException as inst:
if 401 <= inst.response_code <= 403:
print("Unauthorized access getting application configuration. Please check your Appplication Id.")
logger.warning("Unauthorized access getting application configuration. Please check your Appplication Id.")
if debug:
print("Error getting application configuration, with status code:")
print(inst.response_code)
logger.info(f"Error getting application configuration, with status code: {str(inst.response_code)}")

def parse_configuration(self, config, debug):
"""Parse configuration object and return Etag, sample rate and last updated time"""
try:
return config.headers.get("X-Moesif-Config-ETag"), json.loads(config.raw_body).get('sample_rate', 100), datetime.utcnow()
except:
if debug:
print('Error while parsing the configuration object, setting the sample rate to default')
logger.info('Error while parsing the configuration object, setting the sample rate to default')
return None, 100, datetime.utcnow()

def get_sampling_percentage(self, event_data, config, user_id, company_id):
Expand Down Expand Up @@ -59,8 +60,7 @@ def get_sampling_percentage(self, event_data, config, user_id, company_id):
return config_body.get('sample_rate', 100)

except Exception as e:
print("Error while parsing user or company sample rate")
print(e)
logger.warning(f"Error while parsing user or company sample rate: {str(e)}")

# Use default
return 100
27 changes: 15 additions & 12 deletions moesifpythonrequest/outgoing_recorder/outgoing_recorder.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@
import base64
import json
from ..utility_function.utility_function import UtilityFunction
import logging

logger = logging.getLogger(__name__)


class OutgoingRecorder():
Expand All @@ -13,14 +16,14 @@ class OutgoingRecorder():
def base64_encode(self, data):
try:
if global_variables.DEBUG:
print("about to parse outgoing body as base64")
logger.info("about to parse outgoing body as base64")
encoded_body = (base64.standard_b64encode(data)).decode(encoding='UTF-8')
transfer_encoding = 'base64'
if global_variables.DEBUG:
print("base64 encoded body: " + encoded_body)
logger.info(f"base64 encoded body: {str(encoded_body)}")
except:
if global_variables.DEBUG:
print("Outgoing Body is of type other than json or base64")
logger.warning("Outgoing Body is of type other than json or base64")
encoded_body = None
transfer_encoding = None

Expand All @@ -35,10 +38,10 @@ def prepare_model(self, mock_req, mock_res, event_model, start_time, end_time):
if global_variables.moesif_options.get('LOG_BODY_OUTGOING', True) and mock_req.body:
try:
if global_variables.DEBUG:
print('about to parse request json')
logger.info('about to parse request json')
req_body = json.loads(mock_req.body)
if global_variables.DEBUG:
print("Req body json parsed successfully")
logger.info("Req body json parsed successfully")
req_body = utility_function.mask_body(req_body, global_variables.moesif_options.get('REQUEST_BODY_MASKS'))
req_body_transfer_encoding = 'json'
except:
Expand All @@ -50,10 +53,10 @@ def prepare_model(self, mock_req, mock_res, event_model, start_time, end_time):
if global_variables.moesif_options.get('LOG_BODY_OUTGOING', True) and mock_res.content:
try:
if global_variables.DEBUG:
print("about to process response body as json")
logger.info("about to process response body as json")
rsp_body = json.loads(mock_res.content)
if global_variables.DEBUG:
print("Resp body json parsed successfully")
logger.info("Resp body json parsed successfully")
rsp_body = utility_function.mask_body(rsp_body, global_variables.moesif_options.get('RESPONSE_BODY_MASKS'))
rsp_body_transfer_encoding = 'json'
except:
Expand Down Expand Up @@ -100,7 +103,7 @@ def prepare_recorder(self, options, mock_req, mock_res, start_time, end_time):
event_model['user_id'] = identify_user(mock_req, mock_res)
except:
if global_variables.DEBUG:
print("can not execute identify_user function, Please check moesif settings.")
logger.info("can not execute identify_user function, Please check moesif settings.")

event_model['company_id'] = None
try:
Expand All @@ -109,7 +112,7 @@ def prepare_recorder(self, options, mock_req, mock_res, start_time, end_time):
event_model['company_id'] = identify_company(mock_req, mock_res)
except:
if global_variables.DEBUG:
print("can not execute identify_company function, Please check moesif settings.")
logger.info("can not execute identify_company function, Please check moesif settings.")

event_model['session_token'] = None
try:
Expand All @@ -118,7 +121,7 @@ def prepare_recorder(self, options, mock_req, mock_res, start_time, end_time):
event_model['session_token'] = get_session_token(mock_req, mock_res)
except:
if global_variables.DEBUG:
print("Can not execute get_session_token function. Please check moesif settings.")
logger.info("Can not execute get_session_token function. Please check moesif settings.")

event_model['metadata'] = None
try:
Expand All @@ -127,7 +130,7 @@ def prepare_recorder(self, options, mock_req, mock_res, start_time, end_time):
event_model['metadata'] = get_metadata(mock_req, mock_res)
except:
if global_variables.DEBUG:
print("can not execute get_metadata function, please check moesif settings.")
logger.info("can not execute get_metadata function, please check moesif settings.")

try:
skip_event = options.get('SKIP_OUTGOING', None)
Expand All @@ -136,7 +139,7 @@ def prepare_recorder(self, options, mock_req, mock_res, start_time, end_time):
return mock_res
except:
if global_variables.DEBUG:
print("Having difficulty executing skip_event function. Please check moesif settings.")
logger.info("Having difficulty executing skip_event function. Please check moesif settings.")

# Prepare the moesif model
mo_model = self.prepare_model(mock_req, mock_res, event_model, start_time, end_time)
Expand Down
22 changes: 12 additions & 10 deletions moesifpythonrequest/send_moesif/send_moesif.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,17 @@
import threading
import random
import math
import logging

logger = logging.getLogger(__name__)


class SendMoesif():
# Function to send event to Moesif
def send_event(self, event_model):
try:
if gv.DEBUG:
print('Calling API to create event')
logger.info('Calling API to create event')
event_api_response = gv.api_client.create_event(event_model)
event_response_config_etag = event_api_response.get("X-Moesif-Config-ETag")

Expand All @@ -26,27 +29,26 @@ def send_event(self, event_model):
gv.config, gv.DEBUG)
except:
if gv.DEBUG:
print('Error while updating the application configuration')
logger.info('Error while updating the application configuration')
if gv.DEBUG:
print("Event sent successfully")
logger.info("Event sent successfully")
except APIException as inst:
if 401 <= inst.response_code <= 403:
print("Unauthorized access sending event to Moesif. Please check your Appplication Id.")
logger.error("Unauthorized access sending event to Moesif. Please check your Appplication Id.")
if gv.DEBUG:
print("Error sending event to Moesif, with status code:")
print(inst.response_code)
logger.info(f"Error sending event to Moesif, with status code: {str(inst.response_code)}")

# Function to send event async
def send_moesif_async(self, event_model):
try:
mask_event_model = gv.moesif_options.get('MASK_EVENT_MODEL', None)
if mask_event_model is not None:
if gv.DEBUG:
print('Masking the event')
logger.info('Masking the event')
event_model = mask_event_model(event_model)
except:
if gv.DEBUG:
print("Can not execute MASK_EVENT_MODEL function. Please check moesif settings.")
logger.info("Can not execute MASK_EVENT_MODEL function. Please check moesif settings.")

random_percentage = random.random() * 100
gv.sampling_percentage = gv.app_config.get_sampling_percentage(event_model, gv.config, event_model.user_id, event_model.company_id)
Expand All @@ -55,9 +57,9 @@ def send_moesif_async(self, event_model):
event_model.weight = 1 if gv.sampling_percentage == 0 else math.floor(100 / gv.sampling_percentage)
sending_background_thread = threading.Thread(target=self.send_event, args=(event_model,))
if gv.DEBUG:
print('Staring a new thread')
logger.info('Staring a new thread')
sending_background_thread.start()
else:
if gv.DEBUG:
print('Skipped Event due to sampling percentage: ' + str(
logger.info('Skipped Event due to sampling percentage: ' + str(
gv.sampling_percentage) + ' and random percentage: ' + str(random_percentage))
9 changes: 6 additions & 3 deletions moesifpythonrequest/start_capture/start_capture.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@
from ..send_moesif.send_moesif import SendMoesif
from ..app_config.app_config import AppConfig
from moesifapi.moesif_api_client import MoesifAPIClient, Configuration
import logging

logger = logging.getLogger(__name__)

class StartCapture():

Expand All @@ -15,9 +18,9 @@ def start_capture_outgoing(self, options):
gv.DEBUG = gv.moesif_options.get('LOCAL_DEBUG', False)

if gv.MOESIF_PATCH:
print('Already started patching the outgoing requests')
logger.info('Already started patching the outgoing requests')
else:
print('Starting to patch the outgoing requests')
logger.info('Starting to patch the outgoing requests')

gv.MOESIF_PATCH = True
# Create an instance of the class
Expand All @@ -44,6 +47,6 @@ def start_capture_outgoing(self, options):
gv.config, gv.DEBUG)
except:
if gv.DEBUG:
print('Error while parsing application configuration on initialization')
logger.info('Error while parsing application configuration on initialization')

_unpatch = patch_instance.patch(send_async.send_moesif_async)
4 changes: 2 additions & 2 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
requests==2.31.0
moesifapi==1.4.1
requests
moesifapi==1.4.2
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
# Versions should comply with PEP440. For a discussion on single-sourcing
# the version across setup.py and the project code, see
# https://packaging.python.org/en/latest/single_source_version.html
version='0.3.2',
version='0.3.3',

description='Moesif Python request',
long_description=long_description,
Expand Down

0 comments on commit d6d54a0

Please sign in to comment.