Skip to content

Commit

Permalink
feat: added open telemetry (#198)
Browse files Browse the repository at this point in the history
* feat: added open telemetry support
#91

* removed commented code
  • Loading branch information
ashukequinor authored Dec 16, 2024
1 parent 54ecfc5 commit 5cf7d5a
Show file tree
Hide file tree
Showing 6 changed files with 23 additions and 30 deletions.
3 changes: 1 addition & 2 deletions src/ChemDec.Api/ChemDec.Api.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,12 @@
<PackageReference Include="AutoMapper" Version="13.0.1" />
<PackageReference Include="Azure.Extensions.AspNetCore.Configuration.Secrets" Version="1.3.1" />
<PackageReference Include="Azure.Identity" Version="1.12.0" />
<PackageReference Include="Azure.Monitor.OpenTelemetry.AspNetCore" Version="1.2.0" />
<PackageReference Include="Azure.Security.KeyVault.Keys" Version="4.6.0" />
<PackageReference Include="Azure.Security.KeyVault.Secrets" Version="4.6.0" />
<PackageReference Include="Azure.Storage.Blobs" Version="12.21.0" />
<PackageReference Include="FluentValidation" Version="11.9.2" />
<PackageReference Include="LazyCache" Version="2.4.0" />
<PackageReference Include="Microsoft.ApplicationInsights" Version="2.22.0" />
<PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.22.0" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.OpenIdConnect" Version="8.0.7" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="8.0.7" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.7" />
Expand Down
4 changes: 0 additions & 4 deletions src/ChemDec.Api/Controllers/Handlers/ChemicalHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,6 @@
using Microsoft.EntityFrameworkCore;
using System.Text;
using Microsoft.Extensions.Configuration;
using Microsoft.ApplicationInsights.Channel;
using System.Reflection;
using Microsoft.ApplicationInsights;
using ChemDec.Api.Datamodel;

namespace ChemDec.Api.Controllers.Handlers
{
Expand Down
16 changes: 6 additions & 10 deletions src/ChemDec.Api/Controllers/Handlers/ShipmentHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,10 @@
using AutoMapper.QueryableExtensions;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.ApplicationInsights;
using Azure.Storage.Blobs;
using Azure.Storage;
using System.Text;
using Microsoft.AspNetCore.Http;
using Microsoft.IdentityModel.Abstractions;

namespace ChemDec.Api.Controllers.Handlers
{
Expand All @@ -27,9 +25,8 @@ public class ShipmentHandler
private readonly IConfiguration config;
private readonly MailSender mailSender;
private readonly LoggerHelper loggerHelper;
private readonly TelemetryClient telemetry;

public ShipmentHandler(Db.ChemContext db, IMapper mapper, UserResolver userResolver, UserService userService, IConfiguration config, MailSender mailSender, LoggerHelper loggerHelper, TelemetryClient telemetry)
public ShipmentHandler(Db.ChemContext db, IMapper mapper, UserResolver userResolver, UserService userService, IConfiguration config, MailSender mailSender, LoggerHelper loggerHelper)
{
this.db = db;
this.mapper = mapper;
Expand All @@ -38,7 +35,6 @@ public ShipmentHandler(Db.ChemContext db, IMapper mapper, UserResolver userResol
this.config = config;
this.mailSender = mailSender;
this.loggerHelper = loggerHelper;
this.telemetry = telemetry;
}

public IQueryable<Shipment> GetShipments()
Expand Down Expand Up @@ -692,7 +688,7 @@ private void UpdateEvaluationValues(Db.Shipment savedShipment, Shipment sourceSh
savedShipment.Updated = DateTime.Now;
await db.SaveChangesAsync();

loggerHelper.LogEvent(telemetry, user, sender, plant, operation, details, "ShipmentEvaluationSaved", shipment);
loggerHelper.LogEvent(user, sender, plant, operation, details, "ShipmentEvaluationSaved", shipment);
await SendShipmentChangedMail(shipment, initiator, operation, details, comment, attachment, user, null, savedShipment.Status, sender, plant);
}
return (await db.Shipments.ProjectTo<Shipment>(mapper.ConfigurationProvider).FirstOrDefaultAsync(ps => ps.Id == shipment.Id), null);
Expand Down Expand Up @@ -986,7 +982,7 @@ private void ValidatePlannedExecutionDatesIsSet(Shipment shipment, List<string>

await db.SaveChangesAsync();

loggerHelper.LogEvent(telemetry, user, sender, plant, operation, details, "ShipmentSaved", shipment);
loggerHelper.LogEvent(user, sender, plant, operation, details, "ShipmentSaved", shipment);

//TODO: Remove this code
await SendShipmentChangedMail(shipment, initiator, operation, details, comment, attachment, user, newChemicals, status, sender, plant);
Expand All @@ -1002,7 +998,7 @@ private async Task SendShipmentChangedMail(Shipment shipment, Initiator initiato
{
(var subject, var html, var plainText) = buildEmailContentForChemicalResponsible(initiator, sender, plant, user, newChemicals);
await mailSender.SendMail(to, subject, html);
loggerHelper.LogEvent(telemetry, user, sender, plant, operation, details, "EmailNotificationNewChemical", new { To = to, Subject = subject });
loggerHelper.LogEvent(user, sender, plant, operation, details, "EmailNotificationNewChemical", new { To = to, Subject = subject });
}

}
Expand All @@ -1017,7 +1013,7 @@ private async Task SendShipmentChangedMail(Shipment shipment, Initiator initiato
if (recipients != null && recipients.Any())
{
await mailSender.SendMail(recipients, subject, html);
loggerHelper.LogEvent(telemetry, user, plant, sender, operation, details, "EmailNotificationFromOnshore", new { To = recipients, Subject = subject });
loggerHelper.LogEvent(user, plant, sender, operation, details, "EmailNotificationFromOnshore", new { To = recipients, Subject = subject });

}
}
Expand All @@ -1027,7 +1023,7 @@ private async Task SendShipmentChangedMail(Shipment shipment, Initiator initiato
if (recipients != null && recipients.Any())
{
await mailSender.SendMail(recipients, subject, html);
loggerHelper.LogEvent(telemetry, user, sender, plant, operation, details, "EmailNotificationFromOffshore", new { To = recipients, Subject = subject });
loggerHelper.LogEvent(user, sender, plant, operation, details, "EmailNotificationFromOffshore", new { To = recipients, Subject = subject });
}
}
}
Expand Down
7 changes: 1 addition & 6 deletions src/ChemDec.Api/Infrastructure/Services/CommentsService.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
using AutoMapper;
using AutoMapper.QueryableExtensions;
using ChemDec.Api.Datamodel;
using ChemDec.Api.Infrastructure.Utils;
using ChemDec.Api.Model;
using Microsoft.ApplicationInsights;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
Expand All @@ -19,15 +16,13 @@ public class CommentsService : ICommentsService
private readonly LoggerHelper _loggerHelper;
private readonly UserService _userService;
private readonly IMapper _mapper;
private readonly TelemetryClient telemetry;

public CommentsService(ChemContext dbContext, UserService userService, IMapper mapper, LoggerHelper loggerHelper, TelemetryClient telemetryClient)
public CommentsService(ChemContext dbContext, UserService userService, IMapper mapper, LoggerHelper loggerHelper)
{
_dbContext = dbContext;
_loggerHelper = loggerHelper;
_userService = userService;
_mapper = mapper;
telemetry = telemetryClient;
}

//NOTE: Initial implementation of the project has lot of code smells and rookie errors.
Expand Down
15 changes: 10 additions & 5 deletions src/ChemDec.Api/Infrastructure/Utils/LoggerHelper.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
using ChemDec.Api.Model;
using Microsoft.ApplicationInsights;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
Expand All @@ -18,19 +18,24 @@ public LoggerHelper(ILogger<LoggerHelper> logger)
this.logger = logger;
}

public void LogEvent<T>(TelemetryClient telemetry, User user, PlantReference from, PlantReference to, Operation? operation, DetailedOperation? details, string eventName, T payload)

public void LogEvent<T>(User user, PlantReference from, PlantReference to, Operation? operation, DetailedOperation? details, string eventName, T payload)
{
try
{
var jPayload = (JObject)JToken.FromObject(payload);
var flattened = Flatten(jPayload, user, from, to, operation, details);
telemetry.TrackEvent(eventName, flattened);

var flattenedJson = JsonConvert.SerializeObject(flattened);

logger.LogInformation("Event: {EventName} | Flattened Data: {FlattenedData}", eventName, flattenedJson);
}
catch(Exception ex)
catch (Exception ex)
{
logger.LogError(new EventId(1), ex, "Tracking failed");
logger.LogError(new EventId(1), ex, "Tracking failed for event {EventName}", eventName);
}
}

public Dictionary<string, string> Flatten(JObject jsonObject, User user, PlantReference from, PlantReference to, Operation? operation, DetailedOperation? details)
{
var prefix = user == null ? null : user + ".";
Expand Down
8 changes: 5 additions & 3 deletions src/ChemDec.Api/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@
using System.Net.Http;
using ChemDec.Api;
using ChemDec.Api.Infrastructure.Services;
using Microsoft.ApplicationInsights.AspNetCore.Extensions;
using Azure.Extensions.AspNetCore.Configuration.Secrets;
using Azure.Identity;
using Azure.Security.KeyVault.Secrets;
Expand All @@ -31,6 +30,7 @@
using Quartz;
using ChemDec.Api.BackgroundJobs;
using ChemDec.Api.Infrastructure;
using Azure.Monitor.OpenTelemetry.AspNetCore;

var builder = WebApplication.CreateBuilder(args);
var configuration = builder.Configuration;
Expand Down Expand Up @@ -205,8 +205,10 @@

// The following line enables Application Insights telemetry collection.
var appinsightConnStr = configuration["ApplicationInsights:ConnectionString"];
var optionsAppInsight = new ApplicationInsightsServiceOptions { ConnectionString = configuration["ApplicationInsights:ConnectionString"] };
builder.Services.AddApplicationInsightsTelemetry(options: optionsAppInsight);
builder.Services.AddOpenTelemetry().UseAzureMonitor(options =>
{
options.ConnectionString = appinsightConnStr;
});

SwaggerSetup.ConfigureServices(builder.Configuration, builder.Services);

Expand Down

0 comments on commit 5cf7d5a

Please sign in to comment.