Ashu
Ashu

Reputation: 1

Send Azure WebApp Logs to the Azure Blob Storage Using Diagnostic Setting

I have deployed a simple flask web app to the azure AppService and it is working fine, now i have to connect blob storage to it to save the logs to the blob storage.

from flask import Flask,request

app = Flask(__name__)

from flask import jsonify
import logging

logging.basicConfig(level=logging.DEBUG, format="%(asctime)s - %(levelname)s - %(message)s")
logger = logging.getLogger(__name__)
@app.route("/api1")
def api1():
    print("hello data is getting printed")
    logger.info("API1 endpoint called. Hello, data is getting printed.")
    return jsonify("Hello World")

I am able to get log file in the blob storage but i am getting only the print statement only not the
logger

{ "time": "2024-09-20T04:47:50.8864337Z", "resultDescription": "hello data is getting printed", "resourceId": "/SUBSCRIPTIONS//RESOURCEGROUPS/FLASKNEW_GROUP/PROVIDERS/MICROSOFT.WEB/SITES/FLASKNEW", "containerId": "flasknew_06688305", "operationName": "Microsoft.Web/sites/log", "category": "AppServiceConsoleLogs", "level": "Informational", "location": "Central India", "EventStampType": "Stamp", "EventPrimaryStampName": "aaa-prod-cvf-023", "EventStampName": "waws-prod-pn1-023", "Host": "lw0sdlwk000BPK", "EventIpAddress": "1111"}

Getting this output in the file not the loggere info can anyone tell me why this is hapening

I have mentioned above

Upvotes: 0

Views: 94

Answers (1)

Jahnavi
Jahnavi

Reputation: 8018

I am able to get log file in the blob storage but I am getting only the print statement only not the logger:

To avoid the above issue, you need to use the file handler or stream handler which are available under logging handlers in python.

Refer here to include the logging handlers in the Python script to handle and write logs to the console.

logfile = "<logfile>.log"
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s", handlers=[
    logging.FileHandler(logfile,mode='a', encoding=None, delay=False)
])

After adding it, use blob service client library to connect it to the blob storage and store in it.

Refer Blog by @Thomas Gauvin for clear understanding with an example on how to include a blob service client in the script.

By referring to the above blog, I have written below code to meet the requirements accordingly.

blob_service_client = BlobServiceClient.from_connection_string("DefaultEndpointsProtocol=https;AccountName=storenewjhsd;AccountKey=xLZRCyVQEs2sbvAXxxxxtxxuJlA==;EndpointSuffix=core.windows.net")
container_name = "new"
def upload_logs():
    blob_client = blob_service_client.get_blob_client(container=container_name, blob=logfile)
    with open(logfile, "rb") as data:
        blob_client.upload_blob(data=logfile)

enter image description here

Alternatively refer this Github for uploading file content to the blob storage with a flask web app.

Upvotes: 0

Related Questions