在 Application Insight .Net Core 2.1 中使用自定义属性记录用户名和 IP [英] Log UserName and IP with Custom Properties in Application Insight .Net Core 2.1

查看:33
本文介绍了在 Application Insight .Net Core 2.1 中使用自定义属性记录用户名和 IP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在 .Net Core 2.0 上运行 Intranet 应用程序.应用程序洞察对于捕获异常非常有帮助.因此,当用户向我们寻求支持时,我们希望找到导致应用程序洞察出现问题的请求.我添加了一个 ClientIpHeaderTelemetryInitializer,如下所示:

 公共类 CustomTelemetry : ClientIpHeaderTelemetryInitializer{私有只读 IHttpContextAccessor _httpContextAccessor ;公共自定义遥测(IHttpContextAccessor httpContextAccessor):base(httpContextAccessor){_httpContextAccessor = httpContextAccessor;}///<总结>///实现初始化逻辑.///</总结>///<param name="platformContext">Http 上下文.</param>///<param name="requestTelemetry">请求与当前请求关联的遥测对象.</param>///<param name="telemetry">要初始化的遥测项目.</param>protected override void OnInitializeTelemetry(HttpContext platformContext, RequestTelemetry requestTelemetry, ITelemetry遥测){requestTelemetry.Properties.Add("UserName", _httpContextAccessor.HttpContext.User.Identity.Name);if (string.IsNullOrEmpty(telemetry.Context.Location.Ip)){LocationContext location = requestTelemetry.Context.Location;遥测.Context.Location.Ip = location.Ip;requestTelemetry.Properties.Add("InternalIP", location.Ip);}}}

初始化器在启动时注册如下:

services.AddSingleton();

当我查看请求时,自定义数据仍然是空的.
我注册错了吗?我在 Application Insights 的集成测试中找到了添加服务的完全相同的行(尽管已注释掉...)
有没有人有什么想法?

解决方案

我终于让它达到了我的目的.

 公共类 CustomTelemetry : ClientIpHeaderTelemetryInitializer{私有只读 IHttpContextAccessor _httpContextAccessor ;公共自定义遥测(IHttpContextAccessor httpContextAccessor):base(httpContextAccessor){_httpContextAccessor = httpContextAccessor;}///<总结>///实现初始化逻辑.///</总结>///<param name="platformContext">Http 上下文.</param>///<param name="requestTelemetry">请求与当前请求关联的遥测对象.</param>///<param name="telemetry">要初始化的遥测项目.</param>protected override void OnInitializeTelemetry(HttpContext platformContext, RequestTelemetry requestTelemetry, ITelemetry遥测){var userName = _httpContextAccessor.HttpContext?.User?.Identity?.Name;//仅在请求失败时设置...var ip = _httpContextAccessor.HttpContext?.Connection?.RemoteIpAddress?.ToString();if (ip != null) telemetry.Context.GlobalProperties.TryAdd("InternalIP", ip);if(userName != null) requestTelemetry.Properties.Add("UserName", userName);}}

(注意:ClientIpHeaderTelemetryInitializer 是 AppInsights 的一部分)

这里重要的是从 HttpContext 获取所有内容,检查它是否为 null 并添加自定义属性.否则,IP 的内置属性可能会被覆盖.

We are running an intranet Application on .Net Core 2.0. Application insight is very helpfull to catch exceptions. So when the User comes up to us for support we would like to find his request that caused problems in application insight. I added an ClientIpHeaderTelemetryInitializer like this:

public class CustomTelemetry : ClientIpHeaderTelemetryInitializer
    {
        private readonly IHttpContextAccessor _httpContextAccessor ;

        public CustomTelemetry(IHttpContextAccessor httpContextAccessor) : base(httpContextAccessor)
        {
            _httpContextAccessor = httpContextAccessor;
        }

        /// <summary>
        /// Implements initialization logic.
        /// </summary>
        /// <param name="platformContext">Http context.</param>
        /// <param name="requestTelemetry">Request telemetry object associated with the current request.</param>
        /// <param name="telemetry">Telemetry item to initialize.</param>
        protected override void OnInitializeTelemetry(HttpContext platformContext, RequestTelemetry requestTelemetry, ITelemetry telemetry)
        {

            requestTelemetry.Properties.Add("UserName", _httpContextAccessor.HttpContext.User.Identity.Name);
            if (string.IsNullOrEmpty(telemetry.Context.Location.Ip))
            {
                LocationContext location = requestTelemetry.Context.Location;
                telemetry.Context.Location.Ip = location.Ip;
                requestTelemetry.Properties.Add("InternalIP", location.Ip);
            }
        }
    }

The Initalizer is registered at startup like this:

services.AddSingleton<ITelemetryInitializer, CustomTelemetry>();  

When I look at the requests Custom Data still turns up empty.
Did I register it wrong? I found the exact same line to add the service in the Integration Tests of Application Insights (although commented out...)
Has anyone an Idea whats wrong?

解决方案

I finally got it working for my purposes.

public class CustomTelemetry : ClientIpHeaderTelemetryInitializer
    {
        private readonly IHttpContextAccessor _httpContextAccessor ;

        public CustomTelemetry(IHttpContextAccessor httpContextAccessor) : base(httpContextAccessor)
        {
            _httpContextAccessor = httpContextAccessor;
        }

        /// <summary>
        /// Implements initialization logic.
        /// </summary>
        /// <param name="platformContext">Http context.</param>
        /// <param name="requestTelemetry">Request telemetry object associated with the current request.</param>
        /// <param name="telemetry">Telemetry item to initialize.</param>
        protected override void OnInitializeTelemetry(HttpContext platformContext, RequestTelemetry requestTelemetry, ITelemetry telemetry)
        {
            var userName = _httpContextAccessor.HttpContext?.User?.Identity?.Name; // Only set when request failed...
            var ip = _httpContextAccessor.HttpContext?.Connection?.RemoteIpAddress?.ToString();
            if (ip != null) telemetry.Context.GlobalProperties.TryAdd("InternalIP", ip);
            if(userName != null) requestTelemetry.Properties.Add("UserName", userName);
        }
     }

(Note: ClientIpHeaderTelemetryInitializer is part of AppInsights)

Important here is to get everything from the HttpContext, checking if it is null and adding custom properties. The built in properties for IP can get overwritten otherwise. Migrosoft GDPR Blogpost

In the Startup add this to ConfigureService

services.AddSingleton<ITelemetryInitializer, CustomTelemetry>();

Make sure to add the ContextAccessor beforehand so it can be injected:

services.AddHttpContextAccessor();

In Configure add this at the beginning:

app.UseForwardedHeaders(new ForwardedHeadersOptions{ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto});

This is very important to optain the IP Adress when using reverse proxy like IIS. Otherwise you will always receive localhost. UseForwardedHeaders() without options just does nothing! (Also you will need a test setup with a remote server)

Getting the Username just seems to work when the Request fails (tested with 500 Internal Server Error). Otherwise the HttpContextAccessor doesn't populate the User object. Could be a 2.1 thing, quite annoying maybe someone finds a way to get it for every request.

In the end your information should arrive at ApplicationInsights and look like this:

这篇关于在 Application Insight .Net Core 2.1 中使用自定义属性记录用户名和 IP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆