Search code examples
azureazure-application-insights

Is it possible to prevent requests from certain IP addresses being sent to Application Insights?


My client is using a PenTest tool to test his web applications hosted in Azure. He would like to not see the exceptions that are generated from this in Application Insights as they are making it very difficult to find actual application errors.

Is it possible to filter out requests from specific IP addresses so that they are not sent to App Insights? Using something like a TelemetryProcessor maybe? I've found examples that check things like request response codes but I can't seem to find how to do it for IP address.

Thanks


Solution

  • If you know the ip addresses, then you can use TelemetryProcessor.

    Here is the code snippet:

    public class IPFilter : ITelemetryProcessor
    {
        private ITelemetryProcessor Next { get; set; }
    
        // next will point to the next TelemetryProcessor in the chain.
        public IPFilter(ITelemetryProcessor next)
        {
            this.Next = next;
        }
    
        public void Process(ITelemetry item)
        {
            // To filter out an item, return without calling the next processor.
            if (!FilterIp(item)) { return; }
    
            this.Next.Process(item);
        }
    
        // Example: replace with your own criteria.
        private bool FilterIp(ITelemetry item)
        {
            RequestTelemetry requestTelemetry = item as RequestTelemetry;
    
            if (requestTelemetry != null && requestTelemetry.Context != null && requestTelemetry.Context.Location != null && !String.IsNullOrEmpty(requestTelemetry.Context.Location.Ip))
            {
                //you can modify the condition as per your requirement
                if (requestTelemetry.Context.Location.Ip == "XXX.XXX.XXX.XXX")
                    return false;
            }
            return true;
        }
    
    }
    

    At last, do not forget register your custom ITelemetryProcessor. Here is the official doc for your reference.