Skip to content

Commit

Permalink
Code tidy-up
Browse files Browse the repository at this point in the history
  • Loading branch information
Robert McCabe committed Apr 24, 2020
1 parent 37a733d commit 7f5677d
Show file tree
Hide file tree
Showing 6 changed files with 236 additions and 99 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -254,3 +254,4 @@ paket-files/
/src/Tests/coverage.opencover.xml
/src/ConsoleApp1
/src/WebApplication1
Cloud.Core*.xml
128 changes: 52 additions & 76 deletions src/Cloud.Core.Telemetry.AzureAppInsights/AppInsights.cs
Original file line number Diff line number Diff line change
@@ -1,17 +1,4 @@
// ***********************************************************************
// Assembly : Cloud.Core.Telemetry.AzureAppInsights
// Author : rmccabe
// Created : 04-19-2020
//
// Last Modified By : rmccabe
// Last Modified On : 04-19-2020
// ***********************************************************************
// <copyright file="AppInsights.cs" company="Robert McCabe">
// Cloud.Core.Telemetry.AzureAppInsights
// </copyright>
// <summary></summary>
// ***********************************************************************
namespace Cloud.Core.Telemetry.AzureAppInsights
namespace Cloud.Core.Telemetry.AzureAppInsights
{
using Diagnostics = System.Diagnostics;
using System;
Expand Down Expand Up @@ -108,11 +95,12 @@ public IDisposable BeginScope<T>(T state)
}

/// <inheritdoc />
public void Log<T>(LogLevel logLevel, EventId eventId, T state, Exception exception,
Func<T, Exception, string> formatter)
public void Log<T>(LogLevel logLevel, EventId eventId, T state, Exception exception, Func<T, Exception, string> formatter)
{
if (!IsEnabled(logLevel))
{
return;
}

var message = formatter != null ? formatter(state, exception) : state.ToString();

Expand Down Expand Up @@ -154,38 +142,30 @@ public void Log<T>(LogLevel logLevel, EventId eventId, T state, Exception except

/// <inheritdoc />
public void LogVerbose(string message, Dictionary<string, string> properties = null,
[CallerMemberName] string callerMemberName = "", [CallerFilePath] string callerFilePath = "",
[CallerLineNumber] int callerLineNumber = -1)
[CallerMemberName] string callerMemberName = "", [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1)
{
CreateTelemetryEvent(LogLevel.Information, message, properties, callerMemberName, callerFilePath,
callerLineNumber);
CreateTelemetryEvent(LogLevel.Information, message, properties, callerMemberName, callerFilePath, callerLineNumber);
}

/// <inheritdoc />
public void LogInformation(string message, Dictionary<string, string> properties = null,
[CallerMemberName] string callerMemberName = "", [CallerFilePath] string callerFilePath = "",
[CallerLineNumber] int callerLineNumber = -1)
[CallerMemberName] string callerMemberName = "", [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1)
{
CreateTelemetryEvent(LogLevel.Information, message, properties, callerMemberName, callerFilePath,
callerLineNumber);
CreateTelemetryEvent(LogLevel.Information, message, properties, callerMemberName, callerFilePath, callerLineNumber);
}

/// <inheritdoc />
public void LogCritical(string message, Dictionary<string, string> properties = null,
[CallerMemberName] string callerMemberName = "", [CallerFilePath] string callerFilePath = "",
[CallerLineNumber] int callerLineNumber = -1)
[CallerMemberName] string callerMemberName = "", [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1)
{
CreateTelemetryEvent(LogLevel.Information, message, properties, callerMemberName, callerFilePath,
callerLineNumber);
CreateTelemetryEvent(LogLevel.Information, message, properties, callerMemberName, callerFilePath, callerLineNumber);
}

/// <inheritdoc />
public void LogCritical(Exception ex, Dictionary<string, string> properties = null,
[CallerMemberName] string callerMemberName = "", [CallerFilePath] string callerFilePath = "",
[CallerLineNumber] int callerLineNumber = -1)
[CallerMemberName] string callerMemberName = "", [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1)
{
CreateTelemetryException(LogLevel.Critical, ex?.GetBaseException().Message, ex, properties, callerMemberName, callerFilePath,
callerLineNumber);
CreateTelemetryException(LogLevel.Critical, ex?.GetBaseException().Message, ex, properties, callerMemberName, callerFilePath, callerLineNumber);
}

/// <summary>
Expand All @@ -197,11 +177,9 @@ public void LogCritical(Exception ex, Dictionary<string, string> properties = nu
/// <param name="callerFilePath">The caller file path.</param>
/// <param name="callerLineNumber">The caller line number.</param>
public void LogDebug(string message, Dictionary<string, string> properties = null,
[CallerMemberName] string callerMemberName = "", [CallerFilePath] string callerFilePath = "",
[CallerLineNumber] int callerLineNumber = -1)
[CallerMemberName] string callerMemberName = "", [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1)
{
CreateTelemetryEvent(LogLevel.Debug, message, properties, callerMemberName, callerFilePath,
callerLineNumber);
CreateTelemetryEvent(LogLevel.Debug, message, properties, callerMemberName, callerFilePath, callerLineNumber);
}

/// <summary>
Expand All @@ -213,34 +191,28 @@ public void LogDebug(string message, Dictionary<string, string> properties = nul
/// <param name="callerFilePath">The caller file path.</param>
/// <param name="callerLineNumber">The caller line number.</param>
public void LogDebug(Exception ex, Dictionary<string, string> properties = null,
[CallerMemberName] string callerMemberName = "", [CallerFilePath] string callerFilePath = "",
[CallerLineNumber] int callerLineNumber = -1)
[CallerMemberName] string callerMemberName = "", [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1)
{
CreateTelemetryException(LogLevel.Debug, ex?.GetBaseException().Message, ex, properties, callerMemberName, callerFilePath,
callerLineNumber);
CreateTelemetryException(LogLevel.Debug, ex?.GetBaseException().Message, ex, properties, callerMemberName, callerFilePath, callerLineNumber);
}

/// <inheritdoc />
public void LogWarning(string message, Dictionary<string, string> properties = null,
[CallerMemberName] string callerMemberName = "", [CallerFilePath] string callerFilePath = "",
[CallerLineNumber] int callerLineNumber = -1)
[CallerMemberName] string callerMemberName = "", [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1)
{
CreateTelemetryEvent(LogLevel.Warning, message, properties, callerMemberName, callerFilePath,
callerLineNumber);
CreateTelemetryEvent(LogLevel.Warning, message, properties, callerMemberName, callerFilePath, callerLineNumber);
}

/// <inheritdoc />
public void LogWarning(Exception ex, Dictionary<string, string> properties = null,
[CallerMemberName] string callerMemberName = "", [CallerFilePath] string callerFilePath = "",
[CallerLineNumber] int callerLineNumber = -1)
[CallerMemberName] string callerMemberName = "", [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1)
{
CreateTelemetryException(LogLevel.Warning, ex?.GetBaseException().Message, ex, properties, callerMemberName, callerFilePath, callerLineNumber);
}

/// <inheritdoc />
public void LogError(string message, Dictionary<string, string> properties = null,
[CallerMemberName] string callerMemberName = "", [CallerFilePath] string callerFilePath = "",
[CallerLineNumber] int callerLineNumber = -1)
[CallerMemberName] string callerMemberName = "", [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1)
{
var telemetryEx = new TelemetryException(message);

Expand All @@ -249,32 +221,28 @@ public void LogError(string message, Dictionary<string, string> properties = nul

/// <inheritdoc />
public void LogError(Exception ex, Dictionary<string, string> properties = null,
[CallerMemberName] string callerMemberName = "", [CallerFilePath] string callerFilePath = "",
[CallerLineNumber] int callerLineNumber = -1)
[CallerMemberName] string callerMemberName = "", [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1)
{
CreateTelemetryException(LogLevel.Error, ex?.GetBaseException().Message, ex, properties, callerMemberName, callerFilePath, callerLineNumber);
}

/// <inheritdoc />
public void LogError(Exception ex, string message, Dictionary<string, string> properties = null,
[CallerMemberName] string callerMemberName = "", [CallerFilePath] string callerFilePath = "",
[CallerLineNumber] int callerLineNumber = -1)
[CallerMemberName] string callerMemberName = "", [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1)
{
CreateTelemetryException(LogLevel.Error, message, ex, properties, callerMemberName, callerFilePath, callerLineNumber);
}

/// <inheritdoc />
public void LogMetric(string metricName, double metricValue,
[CallerMemberName] string callerMemberName = "", [CallerFilePath] string callerFilePath = "",
[CallerLineNumber] int callerLineNumber = -1)
[CallerMemberName] string callerMemberName = "", [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1)
{
CreateTelemetryMetric(LogLevel.Information, metricName, metricValue, null, callerMemberName, callerFilePath, callerLineNumber);
}

/// <inheritdoc />
public void LogMetric(string metricName, double metricValue, Dictionary<string, string> properties,
[CallerMemberName] string callerMemberName = "", [CallerFilePath] string callerFilePath = "",
[CallerLineNumber] int callerLineNumber = -1)
[CallerMemberName] string callerMemberName = "", [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1)
{
CreateTelemetryMetric(LogLevel.Information, metricName, metricValue, properties, callerMemberName, callerFilePath, callerLineNumber);
}
Expand All @@ -289,22 +257,27 @@ public void LogMetric(string metricName, double metricValue, Dictionary<string,
/// <param name="callerLineNumber">The caller line number.</param>
/// <returns>Dictionary&lt;System.String, System.String&gt;.</returns>
private Dictionary<string, string> SetDefaultProperties(LogLevel logLevel,
Dictionary<string, string> properties,
string callerMemberName, string callerFilePath, int callerLineNumber)
Dictionary<string, string> properties, string callerMemberName, string callerFilePath, int callerLineNumber)
{
// If properties were not set, initialise now and add default properties.
var output = properties == null ? new Dictionary<string, string>() : new Dictionary<string, string>(properties);

output.Add("Telemetry.LogLevel", logLevel.ToString());

if (!string.IsNullOrEmpty(callerMemberName) && !output.ContainsKey("Telemetry.SummaryMessage"))
{
output.Add("Telemetry.MemberName", callerMemberName);
}

if (!string.IsNullOrEmpty(callerFilePath) && !output.ContainsKey("Telemetry.SummaryMessage"))
{
output.Add("Telemetry.FilePath", System.IO.Path.GetFileName(callerFilePath));
}

if (callerLineNumber > 0 && !output.ContainsKey("Telemetry.SummaryMessage"))
{
output.Add("Telemetry.LineNumber", callerLineNumber.ToString());
}

return output;
}
Expand All @@ -318,23 +291,28 @@ private Dictionary<string, string> SetDefaultProperties(LogLevel logLevel,
/// <param name="callerMemberName">Name of the caller member.</param>
/// <param name="callerFilePath">The caller file path.</param>
/// <param name="callerLineNumber">The caller line number.</param>
private void CreateTelemetryEvent(LogLevel level, string message, Dictionary<string, string> properties,
private void CreateTelemetryEvent(LogLevel level, string message, Dictionary<string, string> properties,
string callerMemberName, string callerFilePath, int callerLineNumber)
{
if (!IsEnabled(level))
{
return;
}

var telemetry = new EventTelemetry(message);

var output = SetDefaultProperties(level, properties, callerMemberName, callerFilePath, callerLineNumber);

if (!string.IsNullOrEmpty(message) && !telemetry.Properties.ContainsKey("Telemetry.SummaryMessage"))
{
telemetry.Properties.Add("Telemetry.SummaryMessage", message);
}

foreach (var property in output)
{
if (!telemetry.Properties.ContainsKey(property.Key))
{
telemetry.Properties.Add(property);
}
}

Client.TrackEvent(telemetry);
Expand All @@ -357,13 +335,11 @@ private void CreateTelemetryException(LogLevel level, string message, Exception
return;

var telemetry = new ExceptionTelemetry(ex) { Message = message };

var output = SetDefaultProperties(level, properties, callerMemberName, callerFilePath, callerLineNumber);

if (ex != null)
{
if (!string.IsNullOrEmpty(ex.Message) &&
!telemetry.Properties.ContainsKey("Telemetry.ExceptionMessage"))
if (!string.IsNullOrEmpty(ex.Message) && !telemetry.Properties.ContainsKey("Telemetry.ExceptionMessage"))
{
telemetry.Properties.Add("Telemetry.ExceptionMessage", ex.Message);
}
Expand All @@ -372,7 +348,9 @@ private void CreateTelemetryException(LogLevel level, string message, Exception
foreach (var property in output)
{
if (!telemetry.Properties.ContainsKey(property.Key))
{
telemetry.Properties.Add(property);
}
}

Client.TrackException(telemetry);
Expand Down Expand Up @@ -424,20 +402,18 @@ public static T GetCustomDimensions<T>(string apiKey, string appInsightsId, stri
{
var URL = "http://api.applicationinsights.io/v1/apps/{0}/query?query={1}";

using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(
new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("x-api-key", apiKey);
var req = string.Format(URL, appInsightsId, query);
var responseMessage = client.GetAsync(req).Result;
using var client = new HttpClient();

client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("x-api-key", apiKey);
var req = string.Format(URL, appInsightsId, query);
var responseMessage = client.GetAsync(req).Result;

var result = responseMessage.Content.ReadAsStringAsync().Result;
var queryResult = JsonConvert.DeserializeObject<BaseLogEntry>(result);
var result = responseMessage.Content.ReadAsStringAsync().Result;
var queryResult = JsonConvert.DeserializeObject<BaseLogEntry>(result);

var customDimensionIndex = queryResult.Tables[0].Columns.FindIndex(log => log.Name == "customDimensions");
return JsonConvert.DeserializeObject<T>(queryResult.Tables[0].Rows[0][customDimensionIndex].ToString());
}
var customDimensionIndex = queryResult.Tables[0].Columns.FindIndex(log => log.Name == "customDimensions");
return JsonConvert.DeserializeObject<T>(queryResult.Tables[0].Rows[0][customDimensionIndex].ToString());
}

// The following are classes to allow us to deserialize the Json returned from the Http request for GetCustomDimensions.
Expand All @@ -450,7 +426,7 @@ private class Column
/// Gets the name.
/// </summary>
/// <value>The name.</value>
public string Name { get; }
public string Name { get; set; }
}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

<PropertyGroup>
<TargetFramework>netstandard2.1</TargetFramework>
<Company>Robert McCabe</Company>
<Company>Aylesbury Solutions Ltd</Company>
<IsPackable>true</IsPackable>
<PackageId>Cloud.Core.Telemetry.AzureAppInsights</PackageId>
<GeneratePackageOnBuild>false</GeneratePackageOnBuild>
Expand All @@ -14,13 +14,13 @@
<PackageIconUrl>https://cloud1core.blob.core.windows.net/icons/CC.png</PackageIconUrl>
<Authors>Robert McCabe</Authors>
<ProjectGuid>{b4c1dc56-307f-4daa-92de-5f3269d9d358}</ProjectGuid>
<RepositoryUrl>https://github.com/rmccabe24/Cloud.Core.Telemetry.AzureAppInsights</RepositoryUrl>
<RepositoryUrl>Cloud.Core.Telemetry.AzureAppInsights</RepositoryUrl>
<RepositoryType>Private</RepositoryType>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Cloud.Core" Version="2.1.3513.106" />
<PackageReference Include="Cloud.Core.Telemetry.Logging" Version="3.1.3513.114" />
<PackageReference Include="Cloud.Core" Version="3.1.3517.260" />
<PackageReference Include="Cloud.Core.Telemetry.Logging" Version="3.1.3518.266" />
<PackageReference Include="Microsoft.ApplicationInsights" Version="2.13.1" />
<PackageReference Include="Microsoft.Extensions.Logging.Configuration" Version="3.1.3" />
<PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
using Logging;

/// <summary>
/// Class ServiceCollectionExtensions.
/// Class Service Collection extensions.
/// </summary>
public static class ServiceCollectionExtensions
{
Expand All @@ -25,7 +25,9 @@ public static IServiceCollection AddAppInsightsTelemetry(this IServiceCollection
var key = LoggingBuilderExtension.GetInstrumentationKeyFromConfig(config);

if (key.IsNullOrEmpty())
{
throw new InvalidOperationException("Could not find \"InstrumentationKey\" in configuration");
}

var defaultLevel = config.GetValue<string>("Logging:LogLevel:Default");
var telemetryLevel = config.GetValue<string>("Logging:LogLevel:Telemetry");
Expand All @@ -37,10 +39,10 @@ public static IServiceCollection AddAppInsightsTelemetry(this IServiceCollection
}

/// <summary>
/// Adds the application insights telemetry singlton (ITelemetry).
/// Adds the application insights telemetry singleton (ITelemetry).
/// </summary>
/// <param name="services">The service collection to extend.</param>
/// <param name="insturmentationKey">The insturmentation key.</param>
/// <param name="insturmentationKey">The instrumentation key.</param>
/// <returns>IServiceCollection.</returns>
public static IServiceCollection AddAppInsightsTelemetry(this IServiceCollection services, string insturmentationKey)
{
Expand Down
Loading

0 comments on commit 7f5677d

Please sign in to comment.