Skip to content

Commit

Permalink
Add logging module
Browse files Browse the repository at this point in the history
  • Loading branch information
jvlflame committed Sep 1, 2020
1 parent cbc6860 commit ea91770
Show file tree
Hide file tree
Showing 36 changed files with 1,595 additions and 197 deletions.
132 changes: 132 additions & 0 deletions src/Javinizer/External/Logging/Logging.psd1
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
#
# Module manifest for module 'PSGet_Logging'
#
# Generated by: Massimo Bonvicini
#
# Generated on: 10/01/2017
#

@{

# Script module or binary module file associated with this manifest.
RootModule = 'Logging.psm1'

# Version number of this module.
ModuleVersion = '4.4.0'

# Supported PSEditions
# CompatiblePSEditions = @()

# ID used to uniquely identify this module
GUID = '25a60f1d-85dd-4ad6-9efc-35fd3894f6c1'

# Author of this module
Author = 'Massimo Bonvicini'

# Company or vendor of this module
CompanyName = 'Unknown'

# Copyright statement for this module
Copyright = '(c) 2015 Massimo Bonvicini. All rights reserved.'

# Description of the functionality provided by this module
Description = 'Powershell Logging Module'

# Minimum version of the Windows PowerShell engine required by this module
# PowerShellVersion = ''

# Name of the Windows PowerShell host required by this module
# PowerShellHostName = ''

# Minimum version of the Windows PowerShell host required by this module
# PowerShellHostVersion = ''

# Minimum version of Microsoft .NET Framework required by this module. This prerequisite is valid for the PowerShell Desktop edition only.
# DotNetFrameworkVersion = ''

# Minimum version of the common language runtime (CLR) required by this module. This prerequisite is valid for the PowerShell Desktop edition only.
# CLRVersion = ''

# Processor architecture (None, X86, Amd64) required by this module
# ProcessorArchitecture = ''

# Modules that must be imported into the global environment prior to importing this module
# RequiredModules = @()

# Assemblies that must be loaded prior to importing this module
# RequiredAssemblies = @()

# Script files (.ps1) that are run in the caller's environment prior to importing this module.
# ScriptsToProcess = @()

# Type files (.ps1xml) to be loaded when importing this module
# TypesToProcess = @()

# Format files (.ps1xml) to be loaded when importing this module
# FormatsToProcess = @()

# Modules to import as nested modules of the module specified in RootModule/ModuleToProcess
# NestedModules = @()

# Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export.
FunctionsToExport = @('Add-LoggingLevel','Add-LoggingTarget','Get-LoggingAvailableTarget','Get-LoggingCallerScope','Get-LoggingDefaultFormat','Get-LoggingDefaultLevel','Get-LoggingTarget','Set-LoggingCallerScope','Set-LoggingCustomTarget','Set-LoggingDefaultFormat','Set-LoggingDefaultLevel','Wait-Logging','Write-Log')

# Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export.
CmdletsToExport = @()

# Variables to export from this module
# VariablesToExport = @()

# Aliases to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no aliases to export.
AliasesToExport = @()

# DSC resources to export from this module
# DscResourcesToExport = @()

# List of all modules packaged with this module
# ModuleList = @()

# List of all files packaged with this module
# FileList = @()

# Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell.
PrivateData = @{

PSData = @{

# Tags applied to this module. These help with module discovery in online galleries.
Tags = 'Logging','Log','Console','File','ElasticSearch','Slack','Email', 'Windows'

# A URL to the license for this module.
LicenseUri = 'https://github.com/EsOsO/Logging/blob/master/docs/LICENSE'

# A URL to the main website for this project.
ProjectUri = 'https://github.com/EsOsO/Logging'

# A URL to an icon representing this module.
IconUri = 'https://github.com/EsOsO/Logging/blob/static/img/logo.svg'

# ReleaseNotes of this module
ReleaseNotes = ''

# External dependent modules of this module
# ExternalModuleDependencies = ''

} # End of PSData hashtable

} # End of PrivateData hashtable

# HelpInfo URI of this module
HelpInfoURI = 'https://logging.readthedocs.io'

# Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix.
# DefaultCommandPrefix = ''

}







22 changes: 22 additions & 0 deletions src/Javinizer/External/Logging/Logging.psm1
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
$ScriptPath = Split-Path $MyInvocation.MyCommand.Path
$PSModule = $ExecutionContext.SessionState.Module
$PSModuleRoot = $PSModule.ModuleBase

# Dot source public/private functions
$PublicFunctions = @(Get-ChildItem -Path "$SCriptPath\public" -Filter *.ps1 -Recurse -ErrorAction SilentlyContinue)
$PrivateFunctions = @(Get-ChildItem -Path "$SCriptPath\private" -Filter *.ps1 -Recurse -ErrorAction SilentlyContinue)

$AllFunctions = $PublicFunctions + $PrivateFunctions
foreach ($Function in $AllFunctions) {
try {
. $Function.FullName
} catch {
throw ('Unable to dot source {0}' -f $Function.FullName)
}
}

Export-ModuleMember -Function $PublicFunctions.BaseName

Set-LoggingVariables

Start-LoggingManager
10 changes: 10 additions & 0 deletions src/Javinizer/External/Logging/private/Get-LevelName.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
function Get-LevelName {
[CmdletBinding()]
param(
[int] $Level
)

$l = $Script:LevelNames[$Level]
if ($l) {return $l}
else {return ('Level {0}' -f $Level)}
}
9 changes: 9 additions & 0 deletions src/Javinizer/External/Logging/private/Get-LevelNumber.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
function Get-LevelNumber {
[CmdletBinding()]
param(
$Level
)
if ($Level -is [int] -and $Level -in $Script:LevelNames.Keys) {return $Level}
elseif ([string] $Level -eq $Level -and $Level -in $Script:LevelNames.Keys) {return $Script:LevelNames[$Level]}
else {throw ('Level not a valid integer or a valid string: {0}' -f $Level)}
}
6 changes: 6 additions & 0 deletions src/Javinizer/External/Logging/private/Get-LevelsName.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
Function Get-LevelsName {
[CmdletBinding()]
param()

return $Script:LevelNames.Keys | Where-Object {$_ -isnot [int]} | Sort-Object
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
function Initialize-LoggingTarget {
param()

$targets = @()
$targets += Get-ChildItem "$ScriptRoot\targets" -Filter '*.ps1'

if ((![String]::IsNullOrWhiteSpace($Script:Logging.CustomTargets)) -and (Test-Path -Path $Script:Logging.CustomTargets -PathType Container)) {
$targets += Get-ChildItem -Path $Script:Logging.CustomTargets -Filter '*.ps1'
}

foreach ($target in $targets) {
$module = . $target.FullName
$Script:Logging.Targets[$module.Name] = @{
Init = $module.Init
Logger = $module.Logger
Description = $module.Description
Defaults = $module.Configuration
ParamsRequired = $module.Configuration.GetEnumerator() | Where-Object {$_.Value.Required -eq $true} | Select-Object -ExpandProperty Name | Sort-Object
}
}
}
29 changes: 29 additions & 0 deletions src/Javinizer/External/Logging/private/Merge-DefaultConfig.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
function Merge-DefaultConfig {
param(
[string] $Target,
[hashtable] $Configuration
)

$DefaultConfiguration = $Script:Logging.Targets[$Target].Defaults
$ParamsRequired = $Script:Logging.Targets[$Target].ParamsRequired

$result = @{}

foreach ($Param in $DefaultConfiguration.Keys) {
if ($Param -in $ParamsRequired -and $Param -notin $Configuration.Keys) {
throw ('Configuration {0} is required for target {1}; please provide one of type {2}' -f $Param, $Target, $DefaultConfiguration[$Param].Type)
}

if ($Configuration.ContainsKey($Param)) {
if ($Configuration[$Param] -is $DefaultConfiguration[$Param].Type) {
$result[$Param] = $Configuration[$Param]
} else {
throw ('Configuration {0} has to be of type {1} for target {2}' -f $Param, $DefaultConfiguration[$Param].Type, $Target)
}
} else {
$result[$Param] = $DefaultConfiguration[$Param].Default
}
}

return $result
}
88 changes: 88 additions & 0 deletions src/Javinizer/External/Logging/private/New-LoggingDynamicParam.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
<#
.SYNOPSIS
Creates the param used inside the DynamicParam{}-Block
.DESCRIPTION
New-LoggingDynamicParam creates (or appends) a RuntimeDefinedParameterDictionary
with a parameter whos value is validated through a dynamic validate set.
.PARAMETER Name
displayed parameter name
.PARAMETER Level
Constructs the validate set out of the currently configured logging level names.
.PARAMETER Target
Constructs the validate set out of the currently configured logging targets.
.PARAMETER DynamicParams
Dictionary to be appended. (Useful for multiple dynamic params)
.PARAMETER Mandatory
Controls if parameter is mandatory for call. Defaults to $true
.EXAMPLE
DynamicParam{
New-LoggingDynamicParam -Name "Level" -Level -DefaultValue 'Verbose'
}
DynamicParam{
$dictionary = New-LoggingDynamicParam -Name "Level" -Level
New-LoggingDynamicParam -Name "Target" -Target -DynamicParams $dictionary
}
#>

function New-LoggingDynamicParam {
[OutputType([System.Management.Automation.RuntimeDefinedParameterDictionary])]
[CmdletBinding(DefaultParameterSetName = "DynamicTarget")]
param(
[Parameter(Mandatory = $true, ParameterSetName = "DynamicLevel")]
[Parameter(Mandatory = $true, ParameterSetName = "DynamicTarget")]
[String]
$Name,
[Parameter(Mandatory = $true, ParameterSetName = "DynamicLevel")]
[switch]
$Level,
[Parameter(Mandatory = $true, ParameterSetName = "DynamicTarget")]
[switch]
$Target,
[boolean]
$Mandatory = $true,
[System.Management.Automation.RuntimeDefinedParameterDictionary]
$DynamicParams
)

if (!$DynamicParams) {
$DynamicParams = [System.Management.Automation.RuntimeDefinedParameterDictionary]::new()
}

$attributeCollection = [System.Collections.ObjectModel.Collection[System.Attribute]]::new()
$attribute = [System.Management.Automation.ParameterAttribute]::new()

$attribute.ParameterSetName = '__AllParameterSets'
$attribute.Mandatory = $Mandatory
$attribute.Position = 1

$attributeCollection.Add($attribute)


[String[]] $allowedValues = @()

switch ($PSCmdlet.ParameterSetName) {
"DynamicTarget" {
$allowedValues += $Script:Logging.Targets.Keys
}
"DynamicLevel" {
$allowedValues += Get-LevelsName
}
}

$validateSetAttribute = [System.Management.Automation.ValidateSetAttribute]::new($allowedValues)
$attributeCollection.Add($validateSetAttribute)

$dynamicParam = [System.Management.Automation.RuntimeDefinedParameter]::new($Name, [string], $attributeCollection)

$DynamicParams.Add($Name, $dynamicParam)

return $DynamicParams
}
49 changes: 49 additions & 0 deletions src/Javinizer/External/Logging/private/Replace-Token.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
function Replace-Token {
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseApprovedVerbs', '')]
[CmdletBinding()]
param(
[string] $String,
[object] $Source
)

[string] $result = $String
[regex] $tokenMatcher = '%{(?<token>\w+?)?(?::?\+(?<datefmtU>(?:%[ABCDGHIMRSTUVWXYZabcdeghjklmnprstuwxy].*?)+))?(?::?\+(?<datefmt>(?:.*?)+))?(?::(?<padding>-?\d+))?}'
$tokenMatches = @()
$tokenMatches += $tokenMatcher.Matches($String)

[array]::Reverse($tokenMatches)

foreach ($match in $tokenMatches) {
$formattedEntry = [string]::Empty
$tokenContent = [string]::Empty

$token = $match.Groups["token"].value
$datefmt = $match.Groups["datefmt"].value
$datefmtU = $match.Groups["datefmtU"].value
$padding = $match.Groups["padding"].value

[hashtable] $dateParam = @{ }
if (-not [string]::IsNullOrWhiteSpace($token)) {
$tokenContent = $Source.$token
$dateParam["Date"] = $tokenContent
}

if (-not [string]::IsNullOrWhiteSpace($datefmtU)) {
$formattedEntry = Get-Date @dateParam -UFormat $datefmtU
}
elseif (-not [string]::IsNullOrWhiteSpace($datefmt)) {
$formattedEntry = Get-Date @dateParam -Format $datefmt
}
else {
$formattedEntry = $tokenContent
}

if ($padding) {
$formattedEntry = "{0,$padding}" -f $formattedEntry
}

$result = $result.Substring(0, $match.Index) + $formattedEntry + $result.Substring($match.Index + $match.Length)
}

return $result
}
Loading

0 comments on commit ea91770

Please sign in to comment.