Skip to content

Added an ApplicationInsights logger #5

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

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
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
9 changes: 9 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,15 @@ ipch/
# Guidance Automation Toolkit
*.gpState

# NuGet Packages
*.nupkg
# The packages folder can be ignored because of Package Restore
**/packages/*
# except build/, which is used as an MSBuild target.
!**/packages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/packages/repositories.config

# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
Expand Down
96 changes: 96 additions & 0 deletions ApplicationInsightsOutputSubscriber.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
// ReSharper disable MemberCanBePrivate.Global
// ReSharper disable UnusedMember.Global

using Microsoft.ApplicationInsights;
using Microsoft.ApplicationInsights.DataContracts;

namespace PSLogging
{
using System;
using System.IO;
using System.Management.Automation;

public class ApplicationInsightsOutputSubscriber : HostIOSubscriberBase
{
private readonly TelemetryClient client;

public ApplicationInsightsOutputSubscriber(string key, // Azure Application Insights "InstrumentationKey"
string dateTimeFormat = "r")
{
client = new TelemetryClient();
client.InstrumentationKey = key;
DateTimeFormat = dateTimeFormat;
}


#region Properties

public string DateTimeFormat { get; set; }

#endregion


public override void WriteDebug(string message)
{
if (string.IsNullOrEmpty(message))
{
return;
}

if (message.Trim() != String.Empty)
{
message = String.Format("{0,-29} - [D] {1}", DateTime.UtcNow.ToString(DateTimeFormat), message);
}

client.TrackTrace(message, SeverityLevel.Verbose);
}

public override void WriteError(string message)
{
if (string.IsNullOrEmpty(message))
{
return;
}

if (message.Trim() != String.Empty)
{
message = String.Format("{0,-29} - [E] {1}", DateTime.UtcNow.ToString(DateTimeFormat), message);
}

client.TrackTrace(message, SeverityLevel.Error);
}

public override void WriteVerbose(string message)
{
if (string.IsNullOrEmpty(message))
{
return;
}

if (message.Trim() != String.Empty)
{
message = String.Format("{0,-29} - [V] {1}", DateTime.UtcNow.ToString(DateTimeFormat), message);
}

client.TrackTrace(message, SeverityLevel.Verbose);
}

public override void WriteWarning(string message)
{
if (string.IsNullOrEmpty(message))
{
return;
}

if (message.Trim() != String.Empty)
{
message = String.Format("{0,-29} - [W] {1}", DateTime.UtcNow.ToString(DateTimeFormat), message);
}

client.TrackTrace(message, SeverityLevel.Warning);
}
}
}

// ReSharper restore MemberCanBePrivate.Global
// ReSharper restore UnusedMember.Global
26 changes: 26 additions & 0 deletions Commands/DisableApplicationInsightsCommand.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
// ReSharper disable MemberCanBePrivate.Global
// ReSharper disable UnusedAutoPropertyAccessor.Global
// ReSharper disable UnusedMember.Global

namespace PSLogging.Commands
{
using System.Management.Automation;

[Cmdlet(VerbsLifecycle.Disable, "ApplicationInsights")]
public class DisableApplicationInsightsCommand : PSCmdlet
{
[Parameter(Mandatory = true,
ValueFromPipeline = true,
Position = 0)]
public ApplicationInsightsOutputSubscriber InputObject { get; set; }

protected override void EndProcessing()
{
HostIOInterceptor.Instance.RemoveSubscriber(InputObject);
}
}
}

// ReSharper restore MemberCanBePrivate.Global
// ReSharper restore UnusedAutoPropertyAccessor.Global
// ReSharper restore UnusedMember.Global
68 changes: 68 additions & 0 deletions Commands/EnableApplicationInsightsCommand.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
// ReSharper disable MemberCanBePrivate.Global
// ReSharper disable UnusedAutoPropertyAccessor.Global
// ReSharper disable UnusedMember.Global

namespace PSLogging.Commands
{
using System.Management.Automation;

[Cmdlet(VerbsLifecycle.Enable, "ApplicationInsights")]
public class EnableApplicationInsightsCommand : PSCmdlet
{
private ApplicationInsightsOutputSubscriber inputObject;
private string key;
private string dateTimeFormat = "r";

#region Parameters

[Parameter(ParameterSetName = "AttachExisting",
Mandatory = true,
Position = 0,
ValueFromPipeline = true)]
public ApplicationInsightsOutputSubscriber InputObject
{
get { return inputObject; }
set { inputObject = value; }
}

[Parameter(Mandatory = true,
Position = 0,
ParameterSetName = "New")]
public string Key
{
get { return key; }
set { key = value; }
}

[Parameter(ParameterSetName = "New")]
public string DateTimeFormat
{
get { return dateTimeFormat; }
set { dateTimeFormat = value; }
}

#endregion

protected override void EndProcessing()
{
ApplicationInsightsOutputSubscriber subscriber;

if (ParameterSetName == "New")
{
subscriber = new ApplicationInsightsOutputSubscriber(key, dateTimeFormat);
WriteObject(subscriber);
}
else
{
subscriber = inputObject;
}

HostIOInterceptor.Instance.AttachToHost(Host);
HostIOInterceptor.Instance.AddSubscriber(subscriber);
}
}
}

// ReSharper restore MemberCanBePrivate.Global
// ReSharper restore UnusedAutoPropertyAccessor.Global
// ReSharper restore UnusedMember.Global
23 changes: 20 additions & 3 deletions PSLogging.csproj
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
Expand All @@ -9,7 +9,7 @@
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>PSLogging</RootNamespace>
<AssemblyName>PowerShellLoggingModule</AssemblyName>
<TargetFrameworkVersion>v2.0</TargetFrameworkVersion>
<TargetFrameworkVersion>v4.6.1</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<TargetFrameworkProfile>
</TargetFrameworkProfile>
Expand All @@ -22,6 +22,7 @@
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
Expand All @@ -30,15 +31,26 @@
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<ItemGroup>
<Reference Include="Microsoft.ApplicationInsights, Version=2.6.4.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>packages\Microsoft.ApplicationInsights.2.6.4\lib\net46\Microsoft.ApplicationInsights.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Diagnostics.DiagnosticSource, Version=4.0.2.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>packages\System.Diagnostics.DiagnosticSource.4.4.0\lib\net46\System.Diagnostics.DiagnosticSource.dll</HintPath>
</Reference>
<Reference Include="System.Management.Automation, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\..\..\..\..\Program Files (x86)\Reference Assemblies\Microsoft\WindowsPowerShell\v1.0\System.Management.Automation.dll</HintPath>
</Reference>
<Reference Include="System.Net.Http" />
</ItemGroup>
<ItemGroup>
<Compile Include="ApplicationInsightsOutputSubscriber.cs" />
<Compile Include="Commands\DisableApplicationInsightsCommand.cs" />
<Compile Include="Commands\EnableApplicationInsightsCommand.cs" />
<Compile Include="Commands\EnableOutputSubscriberCommand.cs" />
<Compile Include="Commands\DisableLogFileCommand.cs" />
<Compile Include="Commands\DisableOutputSubscriberCommand.cs" />
Expand All @@ -60,12 +72,17 @@
<SubType>Designer</SubType>
</Content>
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Import Project=".\targets\PowerShellLoggingModule.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
-->
<Target Name="AfterBuild">
<CallTarget Targets="CopyModuleToBinDir" />
</Target>
-->
</Project>
5 changes: 5 additions & 0 deletions packages.config
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Microsoft.ApplicationInsights" version="2.6.4" targetFramework="net461" />
<package id="System.Diagnostics.DiagnosticSource" version="4.4.0" targetFramework="net461" />
</packages>
23 changes: 23 additions & 0 deletions targets/PowerShellLoggingModule.targets
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">

<PropertyGroup>
<PowershellModuleDir>$(SolutionDir)Module\PowerShellLogging\</PowershellModuleDir>
<ProjectBin>$(SolutionDir)bin\$(Configuration)\</ProjectBin>
</PropertyGroup>


<Target Name="CopyModuleToBinDir">

<ItemGroup>
<moduleFiles Include="$(PowershellModuleDir)PowerShellLogging.ps*" />
</ItemGroup>

<Message Importance="high" Text="CopyModuleToBinDir. Copy modules. SOURCE: $(PowershellModuleDir)PowerShellLogging.ps* DESTINATION: $(ProjectBin) " />

<Copy SourceFiles="@(moduleFiles)"
DestinationFolder="$(ProjectBin)"
Condition="Exists('$(PowershellModuleDir)PowerShellLogging.psm1')" />

</Target>

</Project>