地理位置和 IP 地址处理Geolocation and IP address handling

本文介绍 Application Insights 中的地理位置查找和 IP 地址处理工作的方式,以及如何修改默认行为。This article explains how geolocation lookup and IP address handling work in Application Insights along with how to modify the default behavior.

默认行为Default behavior

默认情况下,IP 地址是暂时收集的,不会存储在 Application Insights 中。By default IP addresses are temporarily collected, but not stored in Application Insights. 基本过程如下:The basic process is as follows:

将遥测发送到 Azure 后,将使用 IP 地址通过来自 MaxMind 的 GeoLite2 进行地理位置查找。When telemetry is sent to Azure, the IP address is used to do a geolocation lookup using GeoLite2 from MaxMind. 此查找结果用于填充字段 client_Cityclient_StateOrProvinceclient_CountryOrRegionThe results of this lookup are used to populate the fields client_City, client_StateOrProvince, and client_CountryOrRegion. 然后放弃该地址,并将 0.0.0.0 写入 client_IP 字段。The address is then discarded and 0.0.0.0 is written to the client_IP field.

  • 浏览器遥测:我们会暂时收集发送方的 IP 地址。Browser telemetry: We temporarily collect the sender's IP address. IP 地址由引入终结点计算。IP address is calculated by the ingestion endpoint.
  • 服务器遥测:Application Insights 遥测模块暂时收集客户端 IP 地址。Server telemetry: The Application Insights telemetry module temporarily collects the client IP address. 设置 X-Forwarded-For 标头时,不会在本地收集 IP 地址。IP address isn't collected locally when the X-Forwarded-For header is set.

此行为是有意设计的,目的是帮助避免不必要地收集个人数据。This behavior is by design to help avoid unnecessary collection of personal data. 我们建议尽量避免收集个人数据。Whenever possible, we recommend avoiding the collection of personal data.

重写默认行为Overriding default behavior

而默认设置是不收集 IP 地址。While the default is to not collect IP addresses. 我们仍提供灵活选择来替代此行为。We still offer the flexibility to override this behavior. 但是,建议验证集合是否违反任何合规性要求或当地法规。However, we recommend verifying that collection doesn't break any compliance requirements or local regulations.

若要详细了解 Application Insights 中的个人数据处理,请参阅个人数据指南To learn more about personal data handling in Application Insights, consult the guidance for personal data.

存储 IP 地址数据Storing IP address data

若要启用 IP 收集和存储,必须将 Application Insights 组件的 DisableIpMasking 属性设置为 trueTo enable IP collection and storage, the DisableIpMasking property of the Application Insights component must be set to true. 可以通过 Azure 资源管理器模板或调用 REST API 来设置此属性。This property can be set through Azure Resource Manager templates or by calling the REST API.

Azure Resource Manager 模板Azure Resource Manager Template

{
       "id": "/subscriptions/<subscription-id>/resourceGroups/<resource-group-name>/providers/microsoft.insights/components/<resource-name>",
       "name": "<resource-name>",
       "type": "microsoft.insights/components",
       "location": "chinaeast2",
       "tags": {
              
       },
       "kind": "web",
       "properties": {
              "Application_Type": "web",
              "Flow_Type": "Redfield",
              "Request_Source": "IbizaAIExtension",
              // ...
              "DisableIpMasking": true
       }
}

门户Portal

如果只需修改单个 Application Insights 资源的行为,请使用 Azure 门户。If you only need to modify the behavior for a single Application Insights resource, use the Azure portal.

  1. 转到你的 Application Insights 资源并选择“自动化” > “导出模板” Go your Application Insights resource > Automation > Export Template

  2. 选择“部署”Select Deploy

    用红色标注的带有“部署”字样的按钮

  3. 选择“编辑模板”。Select Edit Template.

    用红色标注的带有“编辑”字样的按钮

  4. 对资源的 json 进行以下更改,然后选择“保存”:Make the following changes to the json for your resource and then select Save:

    在屏幕截图中,“IbizaAIExtension”的后面添加了一个逗号,并在下面添加了包含 "DisableIpMasking": true 的新行

    警告

    如果遇到了包含以下消息的错误:“资源组所在的位置不受模板中的一个或多个资源支持。请选择其他资源组。”If you experience an error that says: The resource group is in a location that is not supported by one or more resources in the template. Please choose a different resource group. 请从下拉列表中暂时选择另一个资源组,然后重新选择原始资源组来解决此错误。Temporarily select a different resource group from the dropdown and then re-select your original resource group to resolve the error.

  5. 选择“我同意” > “购买”。 Select I agree > Purchase.

    在按钮(用红色标注,带有“购买”字样)上方用红色标注的带有“我同意上述条款和条件”字样的复选框。

    在这种情况下,实际上没有购买任何新东西。In this case, nothing new is actually being purchased. 我们仅更新现有 Application Insights 资源的配置。We're only updating the configuration of the existing Application Insights resource.

  6. 部署完成后,将会记录新的遥测数据。Once the deployment is complete, new telemetry data will be recorded.

    如果再次选择并编辑模板,则仅显示默认模板,而不会显示新添加的属性。If you select and edit the template again, you'll only see the default template without the newly added property. 如果未看到 IP 地址数据并希望确认是否已设置 "DisableIpMasking": true,请运行以下 PowerShell:If you aren't seeing IP address data and want to confirm that "DisableIpMasking": true is set, run the following PowerShell:

    # Replace `Fabrikam-dev` with the appropriate resource and resource group name.
    # If you aren't using the cloud shell you will need to connect to your Azure account
    # Connect-AzAccount 
    $AppInsights = Get-AzResource -Name 'Fabrikam-dev' -ResourceType 'microsoft.insights/components' -ResourceGroupName 'Fabrikam-dev'
    $AppInsights.Properties
    

    将返回属性列表作为结果。A list of properties will be returned as a result. 其中一个属性显示为 DisableIpMasking: trueOne of the properties should read DisableIpMasking: true. 如果在使用 Azure 资源管理器部署新属性之前运行 PowerShell,该属性将不存在。If you run the PowerShell before deploying the new property with Azure Resource Manager, the property won't exist.

REST APIRest API

用于做出相同修改的 REST API 有效负载如下:The Rest API payload to make the same modifications is as follows:

PATCH https://management.chinacloudapi.cn/subscriptions/<sub-id>/resourceGroups/<rg-name>/providers/microsoft.insights/components/<resource-name>?api-version=2018-05-01-preview HTTP/1.1
Host: management.chinacloudapi.cn
Authorization: AUTH_TOKEN
Content-Type: application/json
Content-Length: 54

{
       "location": "<resource location>",
       "kind": "web",
       "properties": {
              "Application_Type": "web",
              "DisableIpMasking": true
       }
}

遥测初始化程序Telemetry initializer

如果需要比 DisableIpMasking 更灵活的替代方法,则可以使用遥测初始化表达式将全部或部分 IP 地址复制到自定义字段。If you need a more flexible alternative than DisableIpMasking, you can use a telemetry initializer to copy all or part the IP address to a custom field.

ASP.NET / ASP.NET CoreASP.NET / ASP.NET Core

using Microsoft.ApplicationInsights.Channel;
using Microsoft.ApplicationInsights.DataContracts;
using Microsoft.ApplicationInsights.Extensibility;

namespace MyWebApp
{
    public class CloneIPAddress : ITelemetryInitializer
    {
        public void Initialize(ITelemetry telemetry)
        {
            ISupportProperties propTelemetry = telemetry as ISupportProperties;

            if (propTelemetry !=null && !propTelemetry.Properties.ContainsKey("client-ip"))
            {
                string clientIPValue = telemetry.Context.Location.Ip;
                propTelemetry.Properties.Add("client-ip", clientIPValue);
            }
        }
    } 
}

备注

如果无法访问 ISupportProperties,请检查并确保运行最新稳定版本的 Application Insights SDK。If you are unable to access ISupportProperties, check and make sure you are running the latest stable release of the Application Insights SDK. ISupportProperties 适合用于高基数值,而 GlobalProperties 更适合用于低基数值,如区域名称、环境名称等。ISupportProperties are intended for high cardinality values, whereas GlobalProperties are more appropriate for low cardinality values like region name, environment name, etc.

为 ASP.NET 启用遥测初始化表达式Enable telemetry initializer for ASP.NET

using Microsoft.ApplicationInsights.Extensibility;


namespace MyWebApp
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
              //Enable your telemetry initializer:
              TelemetryConfiguration.Active.TelemetryInitializers.Add(new CloneIPAddress());
        }
    }
}

为 ASP.NET Core 启用遥测初始化表达式Enable telemetry initializer for ASP.NET Core

对于 ASP.NET Core,可以采用与 ASP.NET 相同的方式创建遥测初始化表达式,但若要启用初始化表达式,请参考以下示例:You can create your telemetry initializer the same way for ASP.NET Core as ASP.NET but to enable the initializer, use the following example for reference:

 using Microsoft.ApplicationInsights.Extensibility;
 using CustomInitializer.Telemetry;
 public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton<ITelemetryInitializer, CloneIPAddress>();
}

查看遥测初始化表达式的结果View the results of your telemetry initializer

如果将新流量发送到站点,请等待几分钟。If you send new traffic to your site, and wait a few minutes. 然后,可以运行查询,确认集合正常工作:You can then run a query to confirm collection is working:

requests
| where timestamp > ago(1h) 
| project appName, operation_Name, url, resultCode, client_IP, customDimensions.["client-ip"]

新收集的 IP 地址将显示在 customDimensions_client-ip 列中。Newly collected IP addresses will appear in the customDimensions_client-ip column. 默认的 client-ip 列仍将四个八进制数全部归零。The default client-ip column will still have all four octets either zeroed out.

如果从 localhost 进行测试,并且 customDimensions_client-ip 的值为 ::1,则此值为预期行为。If testing from localhost, and the value for customDimensions_client-ip is ::1, this value is expected behavior. ::1 表示 IPv6 中的环回地址。::1 represents the loopback address in IPv6. 它等效于 IPv4 中的 127.0.01It's equivalent to 127.0.01 in IPv4.

后续步骤Next Steps

  • 详细了解 Application Insights 中的个人数据收集Learn more about personal data collection in Application Insights.

  • 详细了解 Application Insights 中 IP 地址收集的工作原理。Learn more about how IP address collection in Application Insights works. (本文是由我们的某位工程师早前撰写的一篇外部博客文章。(This article an older external blog post written by one of our engineers. 其中所述的机制不同当前的默认行为,现在,IP 地址将记录为 0.0.0.0,不过此文更深入地描述了内置 ClientIpHeaderTelemetryInitializer 的机制。)It predates the current default behavior where IP address is recorded as 0.0.0.0, but it goes into greater depth on the mechanics of the built-in ClientIpHeaderTelemetryInitializer.)