Displaying logs within Azure function apps - Unable to see print logs on function app when deployed onto Azure

MrFlinstone 711 Reputation points
2025-11-21T17:53:40.9566667+00:00

New to python programming and azure function apps, managed to deploy my first function app, when I run it from my local development environment, it logs useful information which gives me a good insight into what my app is doing, I have not been able to replicate thesame thing wen the app is deployed onto Azure.

Locally, I have written my app such that it logs a lot of information which is useful during debugging.

An example of what my app logs when executed locally can be seen below.

[2025-11-20T19:21:30.423Z] reply: b'250-SIZE 52428800\r\n'
[2025-11-20T19:21:30.425Z] reply: b'250-LIMITS MAILMAX=1000 RCPTMAX=50000\r\n'
[2025-11-20T19:21:30.426Z] reply: b'250-8BITMIME\r\n'
[2025-11-20T19:21:30.426Z] reply: b'250-PIPELINING\r\n'
[2025-11-20T19:21:30.427Z] reply: b'250-PIPECONNECT\r\n'
[2025-11-20T19:21:30.428Z] reply: b'250-AUTH PLAIN LOGIN\r\n'
[2025-11-20T19:21:30.428Z] reply: b'250 HELP\r\n'
[2025-11-20T19:21:30.429Z] reply: retcode (250); Msg: b'server004.mailhost.com Hello host86-161-198-15.range86-xxxx.com []\nSIZE 52428800\nLIMITS MAILMAX=1000 RCPTMAX=50000\n8BITMIME\nPIPELINING\nPIPECONNECT\nAUTH PLAIN LOGIN\nHELP'
[2025-11-20T19:21:30.430Z] send: 'AUTH PLAIN xxxxx\r\n'
[2025-11-20T19:21:30.447Z] reply: b'235 Authentication succeeded\r\n'
[2025-11-20T19:21:30.448Z] reply: retcode (235); Msg: b'Authentication succeeded'
[2025-11-20T19:21:30.449Z] send: 'mail FROM:<******@email.com> size=752\r\n'
[2025-11-20T19:21:30.449Z] SMTP login successful for birthday events.
[2025-11-20T19:21:30.451Z] Sending event email to ******@gmail.com / Happy Birthday 
[2025-11-20T19:21:30.476Z] reply: b'250 OK\r\n'
[2025-11-20T19:21:30.479Z] reply: retcode (250); Msg: b'OK'
[2025-11-20T19:21:30.480Z] send: 'rcpt TO:<******@gmail.com>\r\n'
[2025-11-20T19:21:30.543Z] reply: b'250 Accepted\r\n'
[2025-11-20T19:21:30.546Z] reply: retcode (250); Msg: b'Accepted'
[2025-11-20T19:21:30.546Z] send: 'data\r\n'
[2025-11-20T19:21:30.562Z] reply: b'354 Enter message, ending with "." on a line by itself\r\n'
[2025-11-20T19:21:30.566Z] reply: retcode (354); Msg: b'Enter message, ending with "." on a line by itself'
[2025-11-20T19:21:30.568Z] data: (354, b'Enter message, ending with "." on a line by itself')

Within The app service, Its hooked up to application insights, when I query app insights running the kql below.

traces
| order by timestamp desc
| limit 5000

It mainly returns kudu deployment logs.

I should also point out that this is how I log messages from python.

logging.info("My app job started.")

When I go into filestream, the below is what I see. No instances. Switch to application insights, just says connected, no logs.

User's image

Here is what my hosts.json file looks like.

{
  "version": "2.0",
  "logging": {
    "logLevel": {
      "Host.Results": "Error",
      "Function": "Debug",
      "Host.Aggregator": "Trace",
      "default": "Information"
    },
    "applicationInsights": {
      "samplingSettings": {
        "isEnabled": true,
        "excludedTypes": "Request"
      }
    }
  },
  "extensionBundle": {
    "id": "Microsoft.Azure.Functions.ExtensionBundle",
    "version": "[4.*, 5.0.0)"
  }
}
Azure Functions
Azure Functions
An Azure service that provides an event-driven serverless compute platform.
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Jerald Felix 9,920 Reputation points
    2025-11-23T16:03:50.4666667+00:00

    Hello MrFlinstone!

    Python Azure Function logs from logging.info() work locally but fail to appear in Application Insights (AI) or Log Stream when deployed, showing only Kudu deployment logs in traces queries and "No instances" in file stream. This occurs because Python Functions on Azure use a worker process model where standard logging.info() requires explicit Azure Functions context integration, host.json sampling drops traces, and the Python runtime version/extension bundle needs Python-specific logging enabled.

    Immediate Fixes

    1. Update host.json (Critical)

    Replace your current host.json with this Python-optimized version to disable sampling and enable function-level logging:

    
    {
    
      "version": "2.0",
    
      "logging": {
    
        "logLevel": {
    
          "default": "Information",
    
          "Function": "Information",
    
          "Host.Results": "Error",
    
          "Host.Aggregator": "Trace",
    
          "Worker": "Information"
    
        },
    
        "applicationInsights": {
    
          "samplingSettings": {
    
            "isEnabled": false
    
          }
    
        }
    
      },
    
      "extensionBundle": {
    
        "id": "Microsoft.Azure.Functions.ExtensionBundle",
    
        "version": "[4.*, 5.0.0)"
    
      }
    
    }
    
    

    Deploy, restart the Function App, and test. The "Worker": "Information" entry and disabled sampling capture Python worker process logs.

    2. Fix Python Logging Code

    Update your function code to use Azure Functions structured logging:

    
    import azure.functions as func
    
    import logging
    
    import sys
    
    from azure.functions import Context
    
    def main(ctx: Context) -> None:
    
        # Use Azure Functions logger with invocation context
    
        log = ctx.get_logger()
    
        log.info("SMTP login successful for birthday events.")
    
        log.info("Sending event email to user@example.com / Happy Birthday")
    
        
    
        # Or configure standard logging properly
    
        logging.basicConfig(level=logging.INFO)
    
        logger = logging.getLogger("azure.function")
    
        logger.info("Custom log message")
    
    

    The ctx.get_logger() automatically attaches invocation ID and routes to AI. Avoid bare logging.info() without context.

    Verification Steps

    Application Insights Query

    Use this refined KQL query post-fix:

    
    traces
    
    | where cloud_RoleName == "YourFunctionAppName"
    
    | where timestamp > ago(1h)
    
    | where message contains "SMTP" or message contains "birthday"
    
    | order by timestamp desc
    
    | limit 100
    
    

    Filter by cloud_RoleName to exclude Kudu logs.

    Enable Log Stream

    1. Function App > Monitoring > Log stream
    2. Select Application Insights (not Filesystem)
    3. Trigger function—logs appear in real-time.

    Check Runtime Settings

    Function App > Configuration > General settings:

    • Python Version: 3.9, 3.10, 3.11, or 3.12 (avoid 3.8)
    • Always On: Enabled for HTTP triggers
    • Restart after changes.

    Why Local Works, Azure Doesn't

    Local development uses func start with console output. Azure Python runs in isolated worker processes where:

    • Logs need explicit routing to AI collector
    • Sampling (default 95%) drops INFO traces
    • File system logging unsupported on Linux Consumption plan
    • Extension bundle version affects Python logging support[8][3]

    Quick Test Function

    Deploy this minimal function to validate logging:

    function.json (HTTP trigger):

    
    {
    
      "scriptFile": "__init__.py",
    
      "bindings": [{"authLevel": "anonymous", "type": "httpTrigger", "direction": "in", "name": "req", "methods": ["get"]}]
    
    }
    
    

    init.py:

    
    import azure.functions as func
    
    import logging
    
    def main(req: func.HttpRequest) -> func.HttpResponse:
    
        logging.info("=== TEST LOG START ===")
    
        log = func.Context.get_current().get_logger()
    
        log.info("Azure Functions logger test - should appear in AI")
    
        logging.info("Standard logger test - should appear in AI")
    
        logging.info("=== TEST LOG END ===")
    
        return func.HttpResponse("Check AI logs", status_code=200)
    
    

    Hit the endpoint, then query AI traces.

    Production Logging Strategy

    Once fixed, re-enable sampling with conservative settings:

    
    "samplingSettings": {
    
      "isEnabled": true,
    
      "maxTelemetryItemsPerSecond": 20,
    
      "excludedTypes": "Request,Dependency"
    
    }
    
    

    Implement structured logging with categories:

    
    logger = logging.getLogger("birthday.smtp")
    
    logger.info("Email sent", extra={"recipient": "user@example.com", "status": "success"})
    
    

    These changes resolve 95% of missing Python Function logs. Deploy the updated host.json first, then test with the sample code.

    Best Regards,

    Jerald Felix

    0 comments No comments

  2. Pravallika KV 4,105 Reputation points Microsoft External Staff Moderator
    2025-11-24T04:06:26.1466667+00:00

    Hi @MrFlinstone ,

    Thanks for reaching out to Microsoft Q&A.

    Ensure that you have the correct Application Insights Instrumentation Key or Connection String set up in your application settings.

    Make sure your host.json file is properly configured to log at the desired levels. For example, you have Host.Results set to Error, but if your function is logging at a lower level like Information or Debug, those logs will not appear. Try changing it to Information or Debug temporarily.

    Confirm that your function is actually being invoked. Sometimes misconfigurations in triggers can lead to functions not running. You can try manually invoking the function and checking the logs again.

    Utilize the Live Metrics Stream in Application Insights to monitor your function app in real time, which can be helpful to diagnose issues without waiting for logs to become available.

    I have tested the same with below configuration, and it worked.

    Sample code:

    import azure.functions as func
    import logging
    
    app = func.FunctionApp(http_auth_level=func.AuthLevel.ANONYMOUS)
    
    @app.route(route="http_trigger", auth_level=func.AuthLevel.ANONYMOUS)
    def http_trigger(req: func.HttpRequest) -> func.HttpResponse:
        logging.info('Python HTTP trigger function processed a request.')
        
        name = req.params.get('name')
        if not name:
            try:
                logging.info('My apps job started-new')
                req_body = req.get_json()
            except ValueError:
                pass
            else:
                name = req_body.get('name')
    
        if name:
            
            return func.HttpResponse(f"Hello, {name}. This HTTP triggered function executed successfully.")
        else:
            logging.info('Extra logging')
            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
            )
    

    host.json:

    {
      "version": "2.0",
      "logging": {
        "logLevel": {
          "Host.Results": "Error",
          "Function": "Trace",
          "Host.Aggregator": "Trace",
          "default": "Information"
        },
        "applicationInsights": {
          "samplingSettings": {
            "isEnabled": true,
            "excludedTypes": "Request"
          }
        }
      },
      "extensionBundle": {
        "id": "Microsoft.Azure.Functions.ExtensionBundle",
        "version": "[4.*, 5.0.0)"
      }
    }
    

    I have also tried with below default host.json and it worked.

    host.json:

    {
      "version": "2.0",
      "logging": {
        "applicationInsights": {
          "samplingSettings": {
            "isEnabled": true,
            "excludedTypes": "Request"
          }
        }
      },
      "extensionBundle": {
        "id": "Microsoft.Azure.Functions.ExtensionBundle",
        "version": "[4.*, 5.0.0)"
      }
    }
    
    

    LogStream:

    Open LogSteam and run the function parallelly.

    image

    Connected!
    2025-11-24T04:00:38Z   [Verbose]   Request successfully matched the route with name 'http_trigger' and template 'api/http_trigger'
    2025-11-24T04:00:38Z   [Information]   Executing 'Functions.http_trigger' (Reason='This function was programmatically called via the host APIs.', Id=fb410169-43ec-473b-93f3-bdaa667cd070)
    2025-11-24T04:00:38Z   [Verbose]   Sending invocation id: 'fb410169-43ec-473b-93f3-bdaa667cd070
    2025-11-24T04:00:38Z   [Verbose]   Posting invocation id:fb410169-43ec-473b-93f3-bdaa667cd070 on workerId:e4acff6c-47bd-40fa-95cc-28353c688f98
    2025-11-24T04:00:38Z   [Information]   Python HTTP trigger function processed a request.
    2025-11-24T04:00:38Z   [Information]   My apps job started-new
    2025-11-24T04:00:38Z   [Information]   Extra logging
    2025-11-24T04:00:38Z   [Information]   Executed 'Functions.http_trigger' (Succeeded, Id=fb410169-43ec-473b-93f3-bdaa667cd070, Duration=42ms)
    

    Hope it helps!


    Please do not forget to click "Accept the answer” and Yes, this can be beneficial to other community members.

    User's image

    If you have any other questions, let me know in the "comments" and I would be happy to help you.


Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.