Skip to content

Commit 63fbf12

Browse files
authored
Merge pull request #7 from sophia-ramsey/m-hietala/adding_telemetry_support
adding telemetry support
2 parents 2b74e0e + 602e2f0 commit 63fbf12

File tree

5 files changed

+81
-9
lines changed

5 files changed

+81
-9
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
metadata description = 'Assigns MonitoringMetricsContributor role to Application Insights.'
2+
param appInsightsName string
3+
param principalId string
4+
5+
resource appInsights 'Microsoft.Insights/components@2020-02-02' existing = {
6+
name: appInsightsName
7+
}
8+
9+
//var monitoringMetricsPublisherRole = subscriptionResourceId('Microsoft.Authorization/roleDefinitions', '3913510d-42f4-4e42-8a64-420c390055eb')
10+
var monitoringMetricsContributorRole = subscriptionResourceId('Microsoft.Authorization/roleDefinitions', '749f88d5-cbae-40b8-bcfc-e573ddc772fa')
11+
12+
resource monitoringMetricsContributorRoleAssignment 'Microsoft.Authorization/roleAssignments@2022-04-01' = {
13+
scope: appInsights // Use when specifying a scope that is different than the deployment scope
14+
name: guid(subscription().id, resourceGroup().id, principalId, monitoringMetricsContributorRole)
15+
properties: {
16+
roleDefinitionId: monitoringMetricsContributorRole
17+
principalId: principalId
18+
}
19+
}

infra/main.bicep

+13
Original file line numberDiff line numberDiff line change
@@ -276,6 +276,19 @@ module backendRoleAzureAIDeveloperRG 'core/security/role.bicep' = {
276276
}
277277
}
278278

279+
var resolvedApplicationInsightsName = !useApplicationInsights || !empty(aiExistingProjectConnectionString)
280+
? ''
281+
: !empty(applicationInsightsName) ? applicationInsightsName : '${abbrs.insightsComponents}${resourceToken}'
282+
283+
module monitoringMetricsContribuitorRoleAzureAIDeveloperRG 'core/security/appinsights-access.bicep' = if (!empty(resolvedApplicationInsightsName)) {
284+
name: 'monitoringmetricscontributor-role-azureai-developer-rg'
285+
scope: rg
286+
params: {
287+
appInsightsName: resolvedApplicationInsightsName
288+
principalId: api.outputs.SERVICE_API_IDENTITY_PRINCIPAL_ID
289+
}
290+
}
291+
279292
resource existingProjectRG 'Microsoft.Resources/resourceGroups@2021-04-01' existing = if (!empty(aiExistingProjectConnectionString)) {
280293
name: split(aiExistingProjectConnectionString, ';')[2]
281294
}

src/Dockerfile

+6
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,12 @@ WORKDIR /code
66

77
COPY . .
88

9+
ENV ENABLE_AZURE_MONITOR_TRACING=false
10+
11+
ENV AZURE_TRACING_GEN_AI_CONTENT_RECORDING_ENABLED=false
12+
13+
#ENV APP_LOG_FILE=app.log
14+
915
RUN pip install --no-cache-dir --upgrade -r requirements.txt
1016

1117
EXPOSE 50505

src/api/main.py

+39-8
Original file line numberDiff line numberDiff line change
@@ -28,14 +28,31 @@
2828
stream_handler.setFormatter(stream_formatter)
2929
logger.addHandler(stream_handler)
3030

31-
# Configure the file handler
32-
log_file_path = os.getenv("APP_LOG_FILE", "app.log")
33-
file_handler = logging.FileHandler(log_file_path)
34-
file_handler.setLevel(logging.INFO)
35-
file_formatter = logging.Formatter("%(asctime)s [%(levelname)s] %(name)s: %(message)s")
36-
file_handler.setFormatter(file_formatter)
37-
logger.addHandler(file_handler)
38-
31+
# Configure logging to file, if log file name is provided
32+
log_file_name = os.getenv("APP_LOG_FILE")
33+
if log_file_name is not None:
34+
file_handler = logging.FileHandler(log_file_name)
35+
file_handler.setLevel(logging.INFO)
36+
file_formatter = logging.Formatter("%(asctime)s [%(levelname)s] %(name)s: %(message)s")
37+
file_handler.setFormatter(file_formatter)
38+
logger.addHandler(file_handler)
39+
40+
enable_trace_string = os.getenv("ENABLE_AZURE_MONITOR_TRACING")
41+
enable_trace = False
42+
if enable_trace_string is None:
43+
enable_trace = False
44+
else:
45+
enable_trace = str(enable_trace_string).lower() == "true"
46+
if enable_trace:
47+
logger.info("Tracing is enabled.")
48+
try:
49+
from azure.monitor.opentelemetry import configure_azure_monitor
50+
except ModuleNotFoundError:
51+
logger.error("Required libraries for tracing not installed.")
52+
logger.error("Please make sure azure-monitor-opentelemetry is installed.")
53+
exit()
54+
else:
55+
logger.info("Tracing is not enabled")
3956

4057
@contextlib.asynccontextmanager
4158
async def lifespan(app: fastapi.FastAPI):
@@ -54,6 +71,20 @@ async def lifespan(app: fastapi.FastAPI):
5471
)
5572
logger.info("Created AIProjectClient")
5673

74+
if enable_trace:
75+
application_insights_connection_string = ""
76+
try:
77+
application_insights_connection_string = await ai_client.telemetry.get_connection_string()
78+
except Exception as e:
79+
e_string = str(e)
80+
logger.error("Failed to get Application Insights connection string, error: %s", e_string)
81+
if not application_insights_connection_string:
82+
logger.error("Application Insights was not enabled for this project.")
83+
logger.error("Enable it via the 'Tracing' tab in your AI Foundry project page.")
84+
exit()
85+
else:
86+
configure_azure_monitor(connection_string=application_insights_connection_string)
87+
5788
file_names = ["product_info_1.md", "product_info_2.md"] #TODO: can we get the file names from the folder so customers can upload?
5889
for file_name in file_names:
5990
file_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'files', file_name))

src/requirements.txt

+4-1
Original file line numberDiff line numberDiff line change
@@ -3,4 +3,7 @@ uvicorn[standard]==0.29.0
33
gunicorn==22.0.0
44
azure-identity==1.19.0
55
aiohttp==3.11.1
6-
azure-ai-projects
6+
azure-ai-projects
7+
azure-core-tracing-opentelemetry
8+
azure-monitor-opentelemetry
9+
opentelemetry-sdk

0 commit comments

Comments
 (0)