Skip to content

Commit 3b8a0c7

Browse files
committed
Changing logging to use print on python
Signed-off-by: Alice Gibbons <alice@diagrid.io>
1 parent 6915373 commit 3b8a0c7

File tree

6 files changed

+32
-69
lines changed
  • conversation/python/http/conversation
  • jobs/python/sdk/job-service
  • pub_sub/python/sdk/checkout
  • secrets_management/python
  • workflows/python/sdk/order-processor

6 files changed

+32
-69
lines changed

conversation/python/http/conversation/app.py

Lines changed: 23 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -10,16 +10,9 @@
1010
# See the License for the specific language governing permissions and
1111
# limitations under the License.
1212
# ------------------------------------------------------------
13-
import logging
1413
import requests
1514
import os
1615

17-
# Configure logging to only show the message without level/logger prefix
18-
logging.basicConfig(
19-
level=logging.INFO,
20-
format='%(message)s'
21-
)
22-
2316
base_url = os.getenv('BASE_URL', 'http://localhost') + ':' + os.getenv(
2417
'DAPR_HTTP_PORT', '3500')
2518

@@ -53,34 +46,33 @@
5346
json=input
5447
)
5548

56-
logging.info('Conversation input sent: What is dapr?')
49+
print('Conversation input sent: What is dapr?')
5750

5851
# Parse conversation output
5952
data = result.json()
6053
try:
6154
if 'outputs' in data and len(data['outputs']) > 0:
6255
out = data['outputs'][0]
6356
if out.get('model'):
64-
logging.info('Model: ' + out['model'])
57+
print('Model: ' + out['model'])
6558
if out.get('usage'):
6659
u = out['usage']
67-
logging.info('Usage: prompt_tokens=%s completion_tokens=%s total_tokens=%s',
68-
u.get('promptTokens'), u.get('completionTokens'), u.get('totalTokens'))
60+
print(f'Usage: prompt_tokens={u.get("promptTokens")} completion_tokens={u.get("completionTokens")} total_tokens={u.get("totalTokens")}')
6961
if 'choices' in out and len(out['choices']) > 0:
7062
output = out["choices"][0]["message"]["content"]
71-
logging.info('Output response: ' + output)
63+
print('Output response: ' + output)
7264
else:
73-
logging.error('No choices in output')
65+
print('No choices in output')
7466
else:
75-
logging.error('No outputs found in response')
76-
logging.error('Response data: ' + str(data))
67+
print('No outputs found in response')
68+
print('Response data: ' + str(data))
7769

7870
except (KeyError, IndexError) as e:
79-
logging.error(f'Error parsing response: {e}')
71+
print(f'Error parsing response: {e}')
8072
if 'outputs' in data:
81-
logging.info(f'Available outputs: {data["outputs"]}')
73+
print(f'Available outputs: {data["outputs"]}')
8274
else:
83-
logging.info(f'No outputs found in response')
75+
print('No outputs found in response')
8476

8577
tool_call_input = {
8678
'inputs': [{
@@ -140,41 +132,40 @@
140132
json=tool_call_input
141133
)
142134

143-
logging.info('Tool calling input sent: What is the weather like in San Francisco in celsius?')
135+
print('Tool calling input sent: What is the weather like in San Francisco in celsius?')
144136

145137
# Parse conversation output
146138
data = tool_call_result.json()
147139
if 'outputs' in data and len(data['outputs']) > 0:
148140
output = data['outputs'][0]
149141
if output.get('model'):
150-
logging.info('Model: %s', output['model'])
142+
print('Model: ' + output['model'])
151143
if output.get('usage'):
152144
u = output['usage']
153-
logging.info('Usage: prompt_tokens=%s completion_tokens=%s total_tokens=%s',
154-
u.get('promptTokens'), u.get('completionTokens'), u.get('totalTokens'))
145+
print(f'Usage: prompt_tokens={u.get("promptTokens")} completion_tokens={u.get("completionTokens")} total_tokens={u.get("totalTokens")}')
155146
if 'choices' in output and len(output['choices']) > 0:
156147
choice = output['choices'][0]
157148
if 'message' in choice:
158149
message = choice['message']
159150

160151
if 'content' in message and message['content']:
161-
logging.info('Output message: ' + message['content'])
152+
print('Output message: ' + message['content'])
162153

163154
if 'toolCalls' in message and message['toolCalls']:
164-
logging.info('Tool calls detected:')
155+
print('Tool calls detected:')
165156
for tool_call in message['toolCalls']:
166-
logging.info('Tool call: ' + str(tool_call))
157+
print('Tool call: ' + str(tool_call))
167158

168159
if 'function' in tool_call:
169160
func_call = tool_call['function']
170-
logging.info(f"Function name: {func_call.get('name', 'unknown')}")
171-
logging.info(f"Function arguments: {func_call.get('arguments', 'none')}")
161+
print(f"Function name: {func_call.get('name', 'unknown')}")
162+
print(f"Function arguments: {func_call.get('arguments', 'none')}")
172163
else:
173-
logging.info('Tool calls not found')
164+
print('Tool calls not found')
174165
else:
175-
logging.error('No message in choice')
166+
print('No message in choice')
176167
else:
177-
logging.error('No choices in output')
168+
print('No choices in output')
178169
else:
179-
logging.error('No outputs in response')
180-
logging.error('Response data: ' + str(data))
170+
print('No outputs in response')
171+
print('Response data: ' + str(data))

jobs/python/sdk/job-service/app.py

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
import os
22
import json
3-
import logging
43
from datetime import timedelta
54
from typing import Optional
65
from fastapi import FastAPI, HTTPException, Response
@@ -16,10 +15,6 @@
1615
print('Warning: protobuf not available, jobs with data will be scheduled without data', flush=True)
1716

1817

19-
# Configure logging
20-
logging.basicConfig(level=logging.INFO)
21-
logger = logging.getLogger(__name__)
22-
2318
# Initialize FastAPI app
2419
app = FastAPI(title="Dapr Jobs Service", version="1.0.0")
2520

pub_sub/python/sdk/checkout/app.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,6 @@
11
from dapr.clients import DaprClient
22
import json
33
import time
4-
import logging
5-
6-
logging.basicConfig(level=logging.INFO)
74

85
with DaprClient() as client:
96
for i in range(1, 10):
@@ -15,5 +12,5 @@
1512
data=json.dumps(order),
1613
data_content_type='application/json',
1714
)
18-
logging.info('Published data: ' + json.dumps(order))
15+
print('Published data: ' + json.dumps(order))
1916
time.sleep(1)

secrets_management/python/http/order-processor/app.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,6 @@
22
import requests
33
import os
44

5-
logging.basicConfig(level=logging.INFO)
6-
75
base_url = os.getenv('BASE_URL', 'http://localhost') + ':' + os.getenv(
86
'DAPR_HTTP_PORT', '3500')
97
DAPR_SECRET_STORE = 'localsecretstore'

secrets_management/python/sdk/order-processor/app.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
import logging
21
from dapr.clients import DaprClient
32

43
DAPR_SECRET_STORE = 'localsecretstore'

workflows/python/sdk/order-processor/workflow.py

Lines changed: 8 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
from datetime import timedelta
2-
import logging
32
import json
43

54
from dapr.ext.workflow import DaprWorkflowContext, WorkflowActivityContext, WorkflowRuntime, when_any
@@ -13,8 +12,6 @@
1312

1413
wfr = WorkflowRuntime()
1514

16-
logging.basicConfig(level=logging.INFO)
17-
1815

1916
@wfr.workflow(name="order_processing_workflow")
2017
def order_processing_workflow(ctx: DaprWorkflowContext, order_payload_str: str):
@@ -78,36 +75,28 @@ def order_processing_workflow(ctx: DaprWorkflowContext, order_payload_str: str):
7875
@wfr.activity(name="notify_activity")
7976
def notify_activity(ctx: WorkflowActivityContext, input: Notification):
8077
"""Defines Notify Activity. This is used by the workflow to send out a notification"""
81-
# Create a logger
82-
logger = logging.getLogger('NotifyActivity')
83-
logger.info(input.message)
78+
print(input.message, flush=True)
8479

8580

8681
@wfr.activity(name="process_payment_activity")
8782
def process_payment_activity(ctx: WorkflowActivityContext, input: PaymentRequest):
8883
"""Defines Process Payment Activity.This is used by the workflow to process a payment"""
89-
logger = logging.getLogger('ProcessPaymentActivity')
90-
logger.info('Processing payment: '+f'{input.request_id}'+' for '
91-
+f'{input.quantity}' +' ' +f'{input.item_being_purchased}'+' at '+f'{input.amount}'
92-
+' USD')
93-
logger.info(f'Payment for request ID {input.request_id} processed successfully')
84+
print(f'Processing payment: {input.request_id} for {input.quantity} {input.item_being_purchased} at {input.amount} USD', flush=True)
85+
print(f'Payment for request ID {input.request_id} processed successfully', flush=True)
9486

9587

9688
@wfr.activity(name="verify_inventory_activity")
9789
def verify_inventory_activity(ctx: WorkflowActivityContext,
9890
input: InventoryRequest) -> InventoryResult:
9991
"""Defines Verify Inventory Activity. This is used by the workflow to verify if inventory
10092
is available for the order"""
101-
logger = logging.getLogger('VerifyInventoryActivity')
102-
103-
logger.info('Verifying inventory for order '+f'{input.request_id}'+' of '
104-
+f'{input.quantity}' +' ' +f'{input.item_name}')
93+
print(f'Verifying inventory for order {input.request_id} of {input.quantity} {input.item_name}', flush=True)
10594
with DaprClient(f'{settings.DAPR_RUNTIME_HOST}:{settings.DAPR_GRPC_PORT}') as client:
10695
result = client.get_state(store_name, input.item_name)
10796
if result.data is None:
10897
return InventoryResult(False, None)
10998
res_json=json.loads(str(result.data.decode('utf-8')))
110-
logger.info(f'There are {res_json["quantity"]} {res_json["name"]} available for purchase')
99+
print(f'There are {res_json["quantity"]} {res_json["name"]} available for purchase', flush=True)
111100
inventory_item = InventoryItem(item_name=input.item_name,
112101
per_item_cost=res_json['per_item_cost'],
113102
quantity=res_json['quantity'])
@@ -124,10 +113,7 @@ def update_inventory_activity(ctx: WorkflowActivityContext,
124113
"""Defines Update Inventory Activity. This is used by the workflow to check if inventory
125114
is sufficient to fulfill the order and updates inventory by reducing order quantity from
126115
inventory."""
127-
logger = logging.getLogger('UpdateInventoryActivity')
128-
129-
logger.info('Checking inventory for order ' +f'{input.request_id}'+' for '
130-
+f'{input.quantity}' +' ' +f'{input.item_being_purchased}')
116+
print(f'Checking inventory for order {input.request_id} for {input.quantity} {input.item_being_purchased}', flush=True)
131117
with DaprClient(f'{settings.DAPR_RUNTIME_HOST}:{settings.DAPR_GRPC_PORT}') as client:
132118
result = client.get_state(store_name, input.item_being_purchased)
133119
res_json=json.loads(str(result.data.decode('utf-8')))
@@ -138,7 +124,7 @@ def update_inventory_activity(ctx: WorkflowActivityContext,
138124
+' could not be processed. Insufficient inventory.')
139125
new_val = f'{{"name": "{input.item_being_purchased}", "quantity": {str(new_quantity)}, "per_item_cost": {str(per_item_cost)}}}'
140126
client.save_state(store_name, input.item_being_purchased, new_val)
141-
logger.info(f'There are now {new_quantity} {input.item_being_purchased} left in stock')
127+
print(f'There are now {new_quantity} {input.item_being_purchased} left in stock', flush=True)
142128

143129

144130

@@ -148,7 +134,4 @@ def request_approval_activity(ctx: WorkflowActivityContext,
148134
"""Defines Request Approval Activity. This is used by the workflow to request approval
149135
for payment of an order. This activity is used only if the order total cost is greater than
150136
a particular threshold"""
151-
logger = logging.getLogger('RequestApprovalActivity')
152-
153-
logger.info('Requesting approval for payment of '+f'{input["total_cost"]}'+' USD for '
154-
+f'{input["quantity"]}' +' ' +f'{input["item_name"]}')
137+
print(f'Requesting approval for payment of {input["total_cost"]} USD for {input["quantity"]} {input["item_name"]}', flush=True)

0 commit comments

Comments
 (0)