skip to Main Content

I have an Azure Function app with several HTTP-triggered functions.

Each request is logged to a Log Analytics workspace, in a table called AppRequests, with limited information about the request, like the HttpMethod and ResultCode.

Is there any way to inspect the HTTP headers, like the Origin etc.?

enter image description here

2

Answers


  1. Add below code snippet in your function code to log and view the Http headers in Application Insights.

     foreach (var header in req.Headers)
     {
         _logger.LogInformation($"{header.Key}: {string.Join(", ", header.Value)}");
     }
    

    Function.cs:

    public class Function1
    {
        private readonly ILogger<Function1> _logger;
    
        public Function1(ILogger<Function1> logger)
        {
            _logger = logger;
        }
    
        [Function("Function1")]
        public IActionResult Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post")] HttpRequest req)
        {
            _logger.LogInformation("C# HTTP trigger function processed a request.");
            foreach (var header in req.Headers)
            {
                _logger.LogInformation($"{header.Key}: {string.Join(", ", header.Value)}");
            }
            return new OkObjectResult("Welcome to Azure Functions!");
        }
    }
    

    Application Logs in Portal:

    2024-12-17T15:35:50Z   [Information]   Executing 'Functions.Function1' (Reason='This function was programmatically called via the host APIs.', Id=87ef3960-f6f1-433d-978b-08b523508a25)
    2024-12-17T15:35:50Z   [Information]   C# HTTP trigger function processed a request.
    2024-12-17T15:35:50Z   [Information]   Accept: application/json
    2024-12-17T15:35:50Z   [Information]   Host: rkfn.azurewebsites.net
    2024-12-17T15:35:50Z   [Information]   User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36 Edg/131.0.0.0
    2024-12-17T15:35:50Z   [Information]   Accept-Encoding: gzip, deflate, br, zstd
    2024-12-17T15:35:50Z   [Information]   Accept-Language: en-US,en;q=0.9
    2024-12-17T15:35:50Z   [Information]   Cache-Control: no-cache
    2024-12-17T15:35:50Z   [Information]   Content-Type: application/json
    2024-12-17T15:35:50Z   [Information]   Correlation-Context: %23AzFuncLiveLogsSessionId=451d4e1f-18e9-4c40-83f1-f9fddd2d9686
    //Removed few logs
    2024-12-17T15:35:50Z   [Information]   X-Original-URL: /api/Function1
    2024-12-17T15:35:50Z   [Information]   X-WAWS-Unencoded-URL: /api/Function1
    2024-12-17T15:35:50Z   [Information]   DISGUISED-HOST: rkfn.azurewebsites.net
    2024-12-17T15:35:50Z   [Information]   x-ms-invocation-id: 87ef3960-f6f1-433d-978b-08b523508a25
    2024-12-17T15:35:50Z   [Information]   X-Original-Proto: http
    2024-12-17T15:35:50Z   [Information]   X-Original-Host: localhost:50485
    2024-12-17T15:35:50Z   [Information]   X-Original-For: 127.0.0.1:50659
    2024-12-17T15:35:50Z   [Information]   Executing OkObjectResult, writing value of type 'System.String'.
    2024-12-17T15:35:50Z   [Information]   Executed 'Functions.Function1' (Succeeded, Id=87ef3960-f6f1-433d-978b-08b523508a25, Duration=256ms)
    

    Able to see the Headers under FunctionApp=>Application Insights=>Logs:

    enter image description here

    Login or Signup to reply.
  2. To view HTTP headers for HTTP-triggered Azure Functions, you’ll need to capture and log the headers explicitly in your function code, since Azure Functions don’t automatically log HTTP request headers by default. Below is a simple way to do this using Java for HTTP-triggered Azure Functions:

    Example Java Code for Logging HTTP Headers in an Azure Function:

    import com.microsoft.azure.functions.*;
    import com.microsoft.azure.functions.annotation.*;
    import java.util.logging.*;
    
    public class Function {
        @FunctionName("MyFunction")
        public HttpResponseMessage run(
            @HttpTrigger(name = "req", methods = {HttpMethod.GET, HttpMethod.POST}, authLevel = AuthorizationLevel.FUNCTION) HttpRequestMessage<Optional<String>> request,
            final ExecutionContext context
        ) {
            // Get the headers from the request
            var headers = request.getHeaders();
    
            // Log all headers
            headers.forEach((key, value) -> {
                context.getLogger().info(key + ": " + String.join(", ", value));
            });
    
            // Log a specific header (e.g., Origin)
            String origin = headers.get("Origin") != null ? String.join(", ", headers.get("Origin")) : "No Origin header";
            context.getLogger().info("Origin: " + origin);
    
            // Return a response
            return request.createResponseBuilder(HttpStatus.OK).body("Headers logged successfully").build();
        }
    }
    

    Explanation:
    Access Headers: The HttpRequestMessage<Optional> request object contains the HTTP request, including the headers. You can retrieve the headers using request.getHeaders().

    Log Headers: The headers are logged using the context.getLogger().info() method. In this example, all headers are logged with their names and values.

    Specific Header Logging: If you’re interested in a specific header (like Origin), you can access it using headers.get("Origin") and log it separately.

    Returning a Response: The function then returns a simple HTTP response confirming that the headers were logged successfully.

    Viewing the Logs:
    Once you have this logging in place, you can see the output in several places:

    Log Stream: In the Azure portal, go to your Function App and check the "Log stream" under the Monitoring section to view real-time logs.
    Application Insights: If Application Insights is enabled, you can query the logs and see the headers captured as part of the logs.

    Tips:
    If you want to capture headers like Origin, User-Agent, or others, just access them directly from the headers map like headers.get("Origin").
    Ensure that your function is integrated with either Azure Monitor or Application Insights for easier tracking and querying of logs.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search