-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathazureexample.py
More file actions
70 lines (43 loc) · 1.58 KB
/
azureexample.py
File metadata and controls
70 lines (43 loc) · 1.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import asyncio
import logging
import os
from blacksheep import Application, HTTPException, Response, json, text
from dotenv import load_dotenv
from otel.azure import log_dependency as logcall, use_application_insights
load_dotenv()
os.environ["OTEL_RESOURCE_ATTRIBUTES"] = (
"service.name=learning-app2,service.namespace=learning2,deployment.environment=local"
)
app = Application()
connection_string = os.getenv("APP_INSIGHTS_CONNECTION_STRING")
if connection_string is None:
raise ValueError("Missing env variable: APP_INSIGHTS_CONNECTION_STRING")
use_application_insights(app, connection_string)
logger = logging.getLogger(__name__)
class CustomException(HTTPException):
def __init__(self):
super().__init__(400, "Something wrong!")
@app.exception_handler(CustomException)
async def handler_example(app, request, exc: CustomException):
return json({"message": "Oh, no! " + str(exc)}, 400)
@logcall("Example")
async def dependency_example():
await asyncio.sleep(0.1)
@app.router.get("/")
async def home(request) -> Response:
# logger.warning appear in the traces table
logger.warning("Example warning")
await dependency_example()
return text("Hello, traced BlackSheep!")
@app.router.get("/{name}")
async def greetings(name: str) -> Response:
return text(f"Hello, {name}!")
@app.router.get("/bad-request")
async def bad_request():
raise CustomException()
@app.router.get("/crash")
async def crash_test() -> Response:
raise RuntimeError("Crash test")
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, port=44777)