Skip to content

Commit

Permalink
Merge branch 'main' into tilee/test_net8
Browse files Browse the repository at this point in the history
  • Loading branch information
TimothyMothra authored Nov 17, 2023
2 parents 8727328 + de66d67 commit c7e4d54
Show file tree
Hide file tree
Showing 5 changed files with 89 additions and 15 deletions.
2 changes: 1 addition & 1 deletion .props/_GlobalStaticVersion.props
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
<SemanticVersionMajor>2</SemanticVersionMajor>
<SemanticVersionMinor>22</SemanticVersionMinor> <!-- If changing the Minor version, also update the Date value. -->
<SemanticVersionPatch>0</SemanticVersionPatch>
<PreReleaseMilestone>beta3</PreReleaseMilestone> <!--Valid values: beta1, beta2, EMPTY for stable -->
<PreReleaseMilestone>beta4</PreReleaseMilestone> <!--Valid values: beta1, beta2, EMPTY for stable -->
<PreReleaseMilestone Condition="'$(Redfield)' == 'True'">redfield</PreReleaseMilestone>
<PreReleaseMilestone Condition="'$(NightlyBuild)' == 'True'">nightly</PreReleaseMilestone> <!-- Overwrite this property for nightly builds from the DEVELOP branch. -->
<!--
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
namespace Microsoft.ApplicationInsights.Extensibility.Implementation.Tracing.SelfDiagnostics
{
using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

[TestClass]
public class SelfDiagnosticsConfigRefresherTest
Expand Down Expand Up @@ -36,7 +40,8 @@ public void SelfDiagnosticsConfigRefresher_OmitAsConfigured()

// The event was omitted
Assert.AreEqual('\0', (char)actualBytes[MessageOnNewFile.Length]);
}}
}
}
finally
{
CleanupConfigFile();
Expand Down Expand Up @@ -74,6 +79,42 @@ public void SelfDiagnosticsConfigRefresher_CaptureAsConfigured()
}
}

[TestMethod]
public void SelfDiagnosticsConfigRefresher_ReadFromEnviornmentVar()
{
var key = "APPLICATIONINSIGHTS_LOG_DIAGNOSTICS";
var val = @"C:\home\LogFiles\SelfDiagnostics";
Environment.SetEnvironmentVariable(key, val);

try
{
CreateConfigFile(false, val);
using (var configRefresher = new SelfDiagnosticsConfigRefresher())
{
// Emitting event of EventLevel.Error
CoreEventSource.Log.InvalidOperationToStopError();
var filePath = configRefresher.CurrentFilePath;

int bufferSize = 512;
byte[] actualBytes = ReadFile(filePath, bufferSize);
string logText = Encoding.UTF8.GetString(actualBytes);
Assert.IsTrue(logText.StartsWith(MessageOnNewFileString));

// The event was captured
string logLine = logText.Substring(MessageOnNewFileString.Length);
string logMessage = ParseLogMessage(logLine);
string expectedMessage = "Operation to stop does not match the current operation. Telemetry is not tracked.";
Assert.IsTrue(logMessage.StartsWith(expectedMessage));
}
}
finally
{
Environment.SetEnvironmentVariable(key, null);
Platform.PlatformSingleton.Current = null; // Force reinitialization in future tests so that new environment variables will be loaded.
CleanupConfigFile();
}
}

private static string ParseLogMessage(string logLine)
{
int timestampPrefixLength = "2020-08-14T20:33:24.4788109Z:".Length;
Expand All @@ -91,20 +132,38 @@ private static byte[] ReadFile(string filePath, int byteCount)
}
}

private static void CreateConfigFile()
private void CreateConfigFile(bool userDefinedLogDirectory = true, string envVarVal = "")
{
string configJson = @"{
""LogDirectory"": ""."",
""FileSize"": 1024,
""LogLevel"": ""Error""
}";
ConfigFileObj configFileObj = new()
{
FileSize = 1024,
LogLevel = "Error"
};

if (userDefinedLogDirectory)
{
configFileObj.LogDirectory = ".";
}
else
{
configFileObj.LogDirectory = envVarVal;
}

string configJson = JsonConvert.SerializeObject(configFileObj);
using (FileStream file = File.Open(ConfigFilePath, FileMode.Create, FileAccess.Write))
{
byte[] configBytes = Encoding.UTF8.GetBytes(configJson);
file.Write(configBytes, 0, configBytes.Length);
}
}

private class ConfigFileObj
{
public int FileSize { get; set; }
public string LogLevel { get; set; }
public string LogDirectory { get; set; }
};

private static void CleanupConfigFile()
{
try
Expand All @@ -116,4 +175,4 @@ private static void CleanupConfigFile()
}
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,16 @@
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using Microsoft.ApplicationInsights.Extensibility.Implementation.Platform;

internal class SelfDiagnosticsConfigParser
{
public const string ConfigFileName = "ApplicationInsightsDiagnostics.json";
private const int FileSizeLowerLimit = 1024; // Lower limit for log file size in KB: 1MB
private const int FileSizeUpperLimit = 128 * 1024; // Upper limit for log file size in KB: 128MB

private const string LogDiagnosticsEnvironmentVariable = "APPLICATIONINSIGHTS_LOG_DIAGNOSTICS";

/// <summary>
/// ConfigBufferSize is the maximum bytes of config file that will be read.
/// </summary>
Expand Down Expand Up @@ -40,16 +43,23 @@ public bool TryGetConfiguration(out string logDirectory, out int fileSizeInKB, o
{
var configFilePath = ConfigFileName;

// First check using current working directory
if (!File.Exists(configFilePath))
// First, check whether the enviornment variable was set.
if (PlatformSingleton.Current.TryGetEnvironmentVariable(LogDiagnosticsEnvironmentVariable, out string logDiagnosticsPath))
{
configFilePath = Path.Combine(logDiagnosticsPath, ConfigFileName);
logDirectory = logDiagnosticsPath;
}

// Second, check using current working directory.
else if (!File.Exists(configFilePath))
{
#if NET452
configFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, ConfigFileName);
#else
configFilePath = Path.Combine(AppContext.BaseDirectory, ConfigFileName);
#endif

// Second check using application base directory
// Third, check using application base directory.
if (!File.Exists(configFilePath))
{
return false;
Expand All @@ -67,7 +77,8 @@ public bool TryGetConfiguration(out string logDirectory, out int fileSizeInKB, o

file.Read(buffer, 0, buffer.Length);
string configJson = Encoding.UTF8.GetString(buffer);
if (!TryParseLogDirectory(configJson, out logDirectory))

if (logDirectory == null && !TryParseLogDirectory(configJson, out logDirectory))
{
return false;
}
Expand Down
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

## VNext


## Version 2.22.0-beta4
- [Added support to read diagnostics config from the path defined in environment variable.](https://github.com/microsoft/ApplicationInsights-dotnet/pull/2769)

## Version 2.22.0-beta3
- [Do not report CosmosDB transport-level calls](https://github.com/microsoft/ApplicationInsights-dotnet/pull/2789)
- [Fixed an adaptive sampling issue that caused incorrect item count when an `Activity` Recorded flags were modified externally, when enabled side-by-side with OpenTelemetry or other solutions.](https://github.com/microsoft/ApplicationInsights-dotnet/issues/2742)
Expand Down
4 changes: 2 additions & 2 deletions examples/ConsoleApp/ConsoleApp.csproj
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Azure.Identity" Version="1.6.0" />
<PackageReference Include="Azure.Identity" Version="1.10.2" />
</ItemGroup>

<ItemGroup>
Expand Down

0 comments on commit c7e4d54

Please sign in to comment.