Skip to content

Commit d6d54a0

Browse files
authored
#186810782 Fix logging (#22)
* change print to log * warning for 400 error
1 parent ccb97fb commit d6d54a0

File tree

6 files changed

+42
-34
lines changed

6 files changed

+42
-34
lines changed

moesifpythonrequest/app_config/app_config.py

+6-6
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,9 @@
22
from moesifapi.exceptions.api_exception import *
33
import json
44
from .regex_config_helper import RegexConfigHelper
5+
import logging
56

7+
logger = logging.getLogger(__name__)
68

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

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

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

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

6565
# Use default
6666
return 100

moesifpythonrequest/outgoing_recorder/outgoing_recorder.py

+15-12
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,9 @@
55
import base64
66
import json
77
from ..utility_function.utility_function import UtilityFunction
8+
import logging
9+
10+
logger = logging.getLogger(__name__)
811

912

1013
class OutgoingRecorder():
@@ -13,14 +16,14 @@ class OutgoingRecorder():
1316
def base64_encode(self, data):
1417
try:
1518
if global_variables.DEBUG:
16-
print("about to parse outgoing body as base64")
19+
logger.info("about to parse outgoing body as base64")
1720
encoded_body = (base64.standard_b64encode(data)).decode(encoding='UTF-8')
1821
transfer_encoding = 'base64'
1922
if global_variables.DEBUG:
20-
print("base64 encoded body: " + encoded_body)
23+
logger.info(f"base64 encoded body: {str(encoded_body)}")
2124
except:
2225
if global_variables.DEBUG:
23-
print("Outgoing Body is of type other than json or base64")
26+
logger.warning("Outgoing Body is of type other than json or base64")
2427
encoded_body = None
2528
transfer_encoding = None
2629

@@ -35,10 +38,10 @@ def prepare_model(self, mock_req, mock_res, event_model, start_time, end_time):
3538
if global_variables.moesif_options.get('LOG_BODY_OUTGOING', True) and mock_req.body:
3639
try:
3740
if global_variables.DEBUG:
38-
print('about to parse request json')
41+
logger.info('about to parse request json')
3942
req_body = json.loads(mock_req.body)
4043
if global_variables.DEBUG:
41-
print("Req body json parsed successfully")
44+
logger.info("Req body json parsed successfully")
4245
req_body = utility_function.mask_body(req_body, global_variables.moesif_options.get('REQUEST_BODY_MASKS'))
4346
req_body_transfer_encoding = 'json'
4447
except:
@@ -50,10 +53,10 @@ def prepare_model(self, mock_req, mock_res, event_model, start_time, end_time):
5053
if global_variables.moesif_options.get('LOG_BODY_OUTGOING', True) and mock_res.content:
5154
try:
5255
if global_variables.DEBUG:
53-
print("about to process response body as json")
56+
logger.info("about to process response body as json")
5457
rsp_body = json.loads(mock_res.content)
5558
if global_variables.DEBUG:
56-
print("Resp body json parsed successfully")
59+
logger.info("Resp body json parsed successfully")
5760
rsp_body = utility_function.mask_body(rsp_body, global_variables.moesif_options.get('RESPONSE_BODY_MASKS'))
5861
rsp_body_transfer_encoding = 'json'
5962
except:
@@ -100,7 +103,7 @@ def prepare_recorder(self, options, mock_req, mock_res, start_time, end_time):
100103
event_model['user_id'] = identify_user(mock_req, mock_res)
101104
except:
102105
if global_variables.DEBUG:
103-
print("can not execute identify_user function, Please check moesif settings.")
106+
logger.info("can not execute identify_user function, Please check moesif settings.")
104107

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

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

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

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

141144
# Prepare the moesif model
142145
mo_model = self.prepare_model(mock_req, mock_res, event_model, start_time, end_time)

moesifpythonrequest/send_moesif/send_moesif.py

+12-10
Original file line numberDiff line numberDiff line change
@@ -5,14 +5,17 @@
55
import threading
66
import random
77
import math
8+
import logging
9+
10+
logger = logging.getLogger(__name__)
811

912

1013
class SendMoesif():
1114
# Function to send event to Moesif
1215
def send_event(self, event_model):
1316
try:
1417
if gv.DEBUG:
15-
print('Calling API to create event')
18+
logger.info('Calling API to create event')
1619
event_api_response = gv.api_client.create_event(event_model)
1720
event_response_config_etag = event_api_response.get("X-Moesif-Config-ETag")
1821

@@ -26,27 +29,26 @@ def send_event(self, event_model):
2629
gv.config, gv.DEBUG)
2730
except:
2831
if gv.DEBUG:
29-
print('Error while updating the application configuration')
32+
logger.info('Error while updating the application configuration')
3033
if gv.DEBUG:
31-
print("Event sent successfully")
34+
logger.info("Event sent successfully")
3235
except APIException as inst:
3336
if 401 <= inst.response_code <= 403:
34-
print("Unauthorized access sending event to Moesif. Please check your Appplication Id.")
37+
logger.error("Unauthorized access sending event to Moesif. Please check your Appplication Id.")
3538
if gv.DEBUG:
36-
print("Error sending event to Moesif, with status code:")
37-
print(inst.response_code)
39+
logger.info(f"Error sending event to Moesif, with status code: {str(inst.response_code)}")
3840

3941
# Function to send event async
4042
def send_moesif_async(self, event_model):
4143
try:
4244
mask_event_model = gv.moesif_options.get('MASK_EVENT_MODEL', None)
4345
if mask_event_model is not None:
4446
if gv.DEBUG:
45-
print('Masking the event')
47+
logger.info('Masking the event')
4648
event_model = mask_event_model(event_model)
4749
except:
4850
if gv.DEBUG:
49-
print("Can not execute MASK_EVENT_MODEL function. Please check moesif settings.")
51+
logger.info("Can not execute MASK_EVENT_MODEL function. Please check moesif settings.")
5052

5153
random_percentage = random.random() * 100
5254
gv.sampling_percentage = gv.app_config.get_sampling_percentage(event_model, gv.config, event_model.user_id, event_model.company_id)
@@ -55,9 +57,9 @@ def send_moesif_async(self, event_model):
5557
event_model.weight = 1 if gv.sampling_percentage == 0 else math.floor(100 / gv.sampling_percentage)
5658
sending_background_thread = threading.Thread(target=self.send_event, args=(event_model,))
5759
if gv.DEBUG:
58-
print('Staring a new thread')
60+
logger.info('Staring a new thread')
5961
sending_background_thread.start()
6062
else:
6163
if gv.DEBUG:
62-
print('Skipped Event due to sampling percentage: ' + str(
64+
logger.info('Skipped Event due to sampling percentage: ' + str(
6365
gv.sampling_percentage) + ' and random percentage: ' + str(random_percentage))

moesifpythonrequest/start_capture/start_capture.py

+6-3
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,9 @@
44
from ..send_moesif.send_moesif import SendMoesif
55
from ..app_config.app_config import AppConfig
66
from moesifapi.moesif_api_client import MoesifAPIClient, Configuration
7+
import logging
8+
9+
logger = logging.getLogger(__name__)
710

811
class StartCapture():
912

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

1720
if gv.MOESIF_PATCH:
18-
print('Already started patching the outgoing requests')
21+
logger.info('Already started patching the outgoing requests')
1922
else:
20-
print('Starting to patch the outgoing requests')
23+
logger.info('Starting to patch the outgoing requests')
2124

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

4952
_unpatch = patch_instance.patch(send_async.send_moesif_async)

requirements.txt

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,2 @@
1-
requests==2.31.0
2-
moesifapi==1.4.1
1+
requests
2+
moesifapi==1.4.2

setup.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@
2828
# Versions should comply with PEP440. For a discussion on single-sourcing
2929
# the version across setup.py and the project code, see
3030
# https://packaging.python.org/en/latest/single_source_version.html
31-
version='0.3.2',
31+
version='0.3.3',
3232

3333
description='Moesif Python request',
3434
long_description=long_description,

0 commit comments

Comments
 (0)