|
| 1 | +using Microsoft.AspNetCore.Builder; |
| 2 | +using Microsoft.AspNetCore.Http; |
| 3 | +using System; |
| 4 | +using System.Threading.Tasks; |
| 5 | + |
| 6 | +namespace Liquid.Microservices.Runtime.Telemetry |
| 7 | +{ |
| 8 | + /// <summary> |
| 9 | + /// Cria uma extensão para o middleware |
| 10 | + /// </summary> |
| 11 | + public static class TelemetryExtensions |
| 12 | + { |
| 13 | + /// <summary> |
| 14 | + /// Ativa o middleware customizado AppInsightsTelemetry para capturar todos os eventos das API. |
| 15 | + /// e registrar logg no AppInsights com os detalhes adequados |
| 16 | + /// </summary> |
| 17 | + /// <param name="builder"></param> |
| 18 | + /// <returns></returns> |
| 19 | + public static IApplicationBuilder UseTelemetry(this IApplicationBuilder builder) |
| 20 | + { |
| 21 | + return builder.UseMiddleware<AppInsightsTelemetryMiddleware>(); |
| 22 | + } |
| 23 | + } |
| 24 | + |
| 25 | + /// <summary> |
| 26 | + /// This telemetry don't will use the TelemetryClient because we need centrilaze all messages to AppInsights |
| 27 | + /// </summary> |
| 28 | + public class AppInsightsTelemetryMiddleware |
| 29 | + { |
| 30 | + private readonly LightTelemetry _telemetry = (LightTelemetry)WorkBench.Telemetry; |
| 31 | + |
| 32 | + private readonly RequestDelegate _next; |
| 33 | + |
| 34 | + /// <summary> |
| 35 | + /// Middleware de Telemetria de Exceções 500 |
| 36 | + /// </summary> |
| 37 | + /// <param name="next"></param> |
| 38 | + public AppInsightsTelemetryMiddleware(RequestDelegate next) |
| 39 | + { |
| 40 | + _next = next; |
| 41 | + } |
| 42 | + |
| 43 | + /// <summary> |
| 44 | + /// Intercepta a chamada da API |
| 45 | + /// </summary> |
| 46 | + /// <param name="context"></param> |
| 47 | + /// <returns></returns> |
| 48 | + public async Task Invoke(HttpContext context) |
| 49 | + { |
| 50 | + try |
| 51 | + { |
| 52 | + //TODO: Write log's to AppInsights or another techonology. |
| 53 | + //TODO: Why trackEvent for every rest call?! |
| 54 | + //_telemetry.TrackEvent($"Telemetry from middleware."); |
| 55 | + |
| 56 | + await _next(context); |
| 57 | + } |
| 58 | + catch (Exception ex) |
| 59 | + { |
| 60 | + _telemetry.TrackException(ex); |
| 61 | + throw ex; //TODO: Check if its correcty |
| 62 | + } |
| 63 | + } |
| 64 | + } |
| 65 | +} |
0 commit comments