Skip to content

Commit 8c041d8

Browse files
adding in cloud logs
1 parent da70332 commit 8c041d8

File tree

2 files changed

+69
-0
lines changed

2 files changed

+69
-0
lines changed

apps/cos-event-trigger/app.py

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,67 @@
11
#!/usr/bin/env python3
22
from flask import Flask, request, jsonify
33
import json
4+
import os
5+
import httpx
46
from datetime import datetime
57

68
app = Flask(__name__)
79

10+
# IBM Cloud Logging configuration
11+
IBM_INSTANCE_ID = os.environ.get("IBM_INSTANCE_ID")
12+
CE_REGION = os.environ.get("CE_REGION", "us-south")
13+
IBM_APP_NAME = os.environ.get("CE_APP", "cos-event-trigger")
14+
IBM_SUBSYSTEM_NAME = os.environ.get("CE_PROJECT_ID", "event-processor")
15+
IBM_LOG_SEVERITY = os.environ.get("IBM_LOG_SEVERITY", "info")
16+
17+
def get_iam_token():
18+
ibmcloud_api_key = os.environ.get('IBMCLOUD_API_KEY')
19+
if not ibmcloud_api_key:
20+
raise ValueError("IBMCLOUD_API_KEY environment variable not found")
21+
hdrs = { 'Accept': 'application/json', 'Content-Type' : 'application/x-www-form-urlencoded' }
22+
params = { 'grant_type' : 'urn:ibm:params:oauth:grant-type:apikey',
23+
'apikey': ibmcloud_api_key }
24+
resp = httpx.post('https://iam.cloud.ibm.com/identity/token', data = params, headers = hdrs)
25+
# raise exception if invalid status
26+
resp.raise_for_status()
27+
json_payload = resp.json()
28+
token = json_payload['access_token']
29+
return token
30+
31+
def send_to_ibm_logging(log_text, severity=None):
32+
"""Send log to IBM Cloud Logging"""
33+
if not IBM_INSTANCE_ID:
34+
print("IBM Cloud Logging not configured. Set IBM_INSTANCE_ID and IBM_IAM_TOKEN environment variables.")
35+
return False
36+
37+
url = f"https://{IBM_INSTANCE_ID}.ingress.{CE_REGION}.logs.cloud.ibm.com/logs/v1/singles"
38+
39+
iam_token = get_iam_token()
40+
41+
headers = {
42+
"Content-Type": "application/json",
43+
"Authorization": iam_token
44+
}
45+
46+
payload = [{
47+
"applicationName": IBM_APP_NAME,
48+
"subsystemName": IBM_SUBSYSTEM_NAME,
49+
"severity": severity or IBM_LOG_SEVERITY,
50+
"text": log_text
51+
}]
52+
53+
try:
54+
response = httpx.post(url, headers=headers, json=payload, timeout=10.0)
55+
if response.status_code >= 200 and response.status_code < 300:
56+
print(f"Successfully sent log to IBM Cloud Logging: {response.status_code}")
57+
return True
58+
else:
59+
print(f"Failed to send log to IBM Cloud Logging: {response.status_code}, {response.text}")
60+
return False
61+
except Exception as e:
62+
print(f"Error sending log to IBM Cloud Logging: {str(e)}")
63+
return False
64+
865
# Equivalent to EventStats in Go
966
class EventStats:
1067
def __init__(self):
@@ -46,6 +103,10 @@ def handle_event():
46103
print(f"{current_time} - Received:")
47104
print(f"\nBody: {body}")
48105

106+
# Send to IBM Cloud Logging
107+
log_message = f"COS Event: {operation} on {bucket}/{key} - {body}"
108+
send_to_ibm_logging(log_message)
109+
49110
return "OK"
50111

51112
if __name__ == '__main__':
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,16 @@
1+
anyio==4.9.0
12
blinker==1.9.0
3+
certifi==2025.1.31
24
click==8.1.8
35
flask==3.1.0
6+
h11==0.14.0
7+
httpcore==1.0.7
8+
httpx==0.28.1
9+
idna==3.10
410
itsdangerous==2.2.0
511
jinja2==3.1.6
612
markupsafe==3.0.2
713
pip==24.3.1
14+
sniffio==1.3.1
15+
typing-extensions==4.12.2
816
werkzeug==3.1.3

0 commit comments

Comments
 (0)