admin管理员组

文章数量:1434909

This is the output of an Azure Function running in a kubernetes pod.

How can I enable the timestamp in my logs?
Can I have one line of log for each message instead of two?

info: Function.name_of_the_function.User[0]
      this is the info message from the function...
info: Function.name_of_the_function.User[0]
      this is the info message from the function...
info: Function.name_of_the_function.User[0]
      this is the info message from the function...
info: Function.name_of_the_function.User[0]
      this is the info message from the function...

Here is my hosts.json

  "logging": {
    "applicationInsights": {
      "samplingSettings": {
        "isEnabled": false,
        "excludedTypes": "Request"
      }
    },
    "console": {
      "isEnabled": "false",
      "DisableColors": true
    },
    "fileLoggingMode": "always",
    "logLevel": {
      "Host": "Warning",
      "Function": "Warning",
      "Function.solr_catalog": "Warning",
      "Function.solr_catalog.User": "Information",
      "Azure.Core": "Warning",
      "Azure.Messaging": "Warning",
      "default": "none"
    }
  },

This is the output of an Azure Function running in a kubernetes pod.

How can I enable the timestamp in my logs?
Can I have one line of log for each message instead of two?

info: Function.name_of_the_function.User[0]
      this is the info message from the function...
info: Function.name_of_the_function.User[0]
      this is the info message from the function...
info: Function.name_of_the_function.User[0]
      this is the info message from the function...
info: Function.name_of_the_function.User[0]
      this is the info message from the function...

Here is my hosts.json

  "logging": {
    "applicationInsights": {
      "samplingSettings": {
        "isEnabled": false,
        "excludedTypes": "Request"
      }
    },
    "console": {
      "isEnabled": "false",
      "DisableColors": true
    },
    "fileLoggingMode": "always",
    "logLevel": {
      "Host": "Warning",
      "Function": "Warning",
      "Function.solr_catalog": "Warning",
      "Function.solr_catalog.User": "Information",
      "Azure.Core": "Warning",
      "Azure.Messaging": "Warning",
      "default": "none"
    }
  },
Share Improve this question edited Nov 20, 2024 at 15:27 freedev asked Nov 17, 2024 at 16:34 freedevfreedev 30.4k12 gold badges127 silver badges138 bronze badges 4
  • Do you have any host.json configured? learn.microsoft/en-us/azure/azure-functions/… – Alfred Luu Commented Nov 17, 2024 at 18:05
  • @AlfredLuu yep, added in the question... – freedev Commented Nov 18, 2024 at 8:18
  • try using Using kubectl raw – Sampath Commented Nov 20, 2024 at 14:15
  • @freedev is your issue resolved? Check below my answer for the same. – Arko Commented Nov 25, 2024 at 10:02
Add a comment  | 

1 Answer 1

Reset to default 1

Azure Functions in Python use the logging module. By default, the Azure Functions runtime adds its own structure to logs, which may cause the output you’re seeing. To ensure proper timestamps and single-line logs, explicitly configure Python's logging module in your function code.

Update your function code as below-

import azure.functions as func
import logging
from datetime import datetime


logging.basicConfig(level=logging.INFO)

app = func.FunctionApp()

@app.route(route="HttpTrigger", auth_level=func.AuthLevel.ANONYMOUS)
def HttpTrigger(req: func.HttpRequest) -> func.HttpResponse:
    # Include a timestamp in your log
    timestamp = datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]

    logging.info(f"{timestamp} - Processing a new request.")

    name = req.params.get('name')
    if not name:
        try:
            req_body = req.get_json()
        except ValueError:
            pass
        else:
            name = req_body.get('name')

    if name:
        logging.info(f"{timestamp} - Successfully processed request for name: {name}.")
        return func.HttpResponse(
            f"Hello, {name}. This HTTP triggered function executed successfully."
        )
    else:
        logging.warning(f"{timestamp} - No name provided in the query string or request body.")
        return func.HttpResponse(
            "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response.",
            status_code=200
        )

took reference from here

Update the host.json to ensure console logging is enabled and that logs are configured correctly

{
  "version": "2.0",
  "logging": {
    "console": {
      "isEnabled": true,
      "DisableColors": true
    },
    "applicationInsights": {
      "samplingSettings": {
        "isEnabled": false,
        "excludedTypes": "Request"
      }
    },
    "logLevel": {
      "default": "Information",
      "Function.HttpTrigger": "Information"
    }
  }
}

Update the Dockerfile

FROM mcr.microsoft/azure-functions/python:4-python3.9

ENV AzureWebJobsScriptRoot=/home/site/wwwroot \
    AzureFunctionsJobHost__Logging__Console__IsEnabled=true

COPY . /home/site/wwwroot

Build and push the container image to your container registry

Build and deploy your Function to your acr

inside your aks create a

deployment

apiVersion: apps/v1
kind: Deployment
metadata:
  name: azure-function-logging
spec:
  replicas: 1
  selector:
    matchLabels:
      app: azure-function-logging
  template:
    metadata:
      labels:
        app: azure-function-logging
    spec:
      containers:
      - name: azure-function-logging
        image: <your-registry>/azure-function-logging:latest
        ports:
        - containerPort: 80
        env:
        - name: FUNCTIONS_WORKER_RUNTIME
          value: "python"
        - name: AzureWebJobsStorage
          value: "<your-storage-connection-string>"

and a Service

apiVersion: v1
kind: Service
metadata:
  name: azure-function-logging
spec:
  selector:
    app: azure-function-logging
  ports:
  - protocol: TCP
    port: 80
    targetPort: 80
  type: LoadBalancer

Now go to your aks and check the logs

kubectl get pods

kubectl logs aks-azure-function-cb7c8b64c-f77tn

Done. Use datetime.utcnow().strftime to include timestamps in every log message.

本文标签: AKS Python Azure Functionconsole log without timestampStack Overflow