Code Monkey home page Code Monkey logo

logging's Introduction

This repository is archived as I'm unable to work on the code anymore. If someone would like to become the new owner please contact me.

Powershell Logging Module

Powershell Logging logo

Master Build Status Develop Build Status Powershell gallery downloads Contributor Covenant

Introduction


Contributing

Please read CONTRIBUTING.md for details on how to contribute to the project. Take a look at the CODE_OF_CONDUCT.md to be a good user/contributor of the project.

Maintainers

License

This project is licensed under the MIT License


Special thanks to:

logging's People

Contributors

adessotorbensoenneckentest avatar awesomecogs avatar benclaussen avatar esoso avatar gahujipo avatar glober777 avatar itshorty avatar jangins101 avatar lookcloser avatar mabster avatar manualbashing avatar mcvic1rj avatar tadas avatar thesemicolon avatar trowt avatar zamelek avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

logging's Issues

WinEvent as logging target

I know it already exists separately in powershell, but in the interest of using a unified framework it may be nice to have the ability to specify WinEvent as logtarget as well.

Logging to specific target

Hello. I have two targets configured, File & Slack. Poking around it does not look as though you can target a specific Write-Log message to a particular Target. i.e I have some monitoring built into a script that should fire a Slack message only when certain criteria are met. I tried the setup specified in Issue #10 but All of the log messages got fired into the slack channel but were identified as the correct level.

Wondering if there are plans to allow this or if there is a different configuration along the lines of below that will allow only specific messages to hit the Slack channel.

Add-LoggingLevel -Level 5 -LevelName SLACK
Add-LoggingTarget -Name Slack -Configuration @{ServerUri='<slack channel url>'; Level='SLACK'}
Write-Log -Level SLACK -Message 'Bad Stuff Happening'

Thank you

Body writes System.Collections.hashtable

Problem: The argument for the -body is processed as System.Collections.Hashtable

Inputs:

Set-LoggingDefaultFormat -Format '[%{timestamp:+yyyy-MM-dd HH:mm:ss.zzz}][%{level:-7}][%{caller}][%{message}][%{lineno}] %{body}'

Write-Log -Level ERROR -Message 'Hello, {0}!' -Arguments 'World' -Body @{Server='srv01.contoso.com'}

Expected:
[2019-04-01 12:12:07.-05:00][ERROR ][Deploy-PowerShellAppV2.ps1][Hello, World!][1527] [server='srv01.contoso.com']

Result (error):
[2019-04-01 12:12:07.-05:00][ERROR ][Deploy-PowerShellAppV2.ps1][Hello, World!][1527] System.Collections.Hashtable

Help.

Move to Azure pipelines

I think it could be useful to move to Azure Pipelines to test the module against all major versions of Powershell

Add caller information as part of the log information

It would be nice to show the name of the function/script where the log was triggered from, so that the message format could be as follow:

[%{timestamp}] [%{level:-7}] [%{caller}] %{message}

This in turn could be passed down as separate entry field into json that gets sent to elasticsearch

I am already using a workaround on my module, using the Get-PSCallStack, which is formatting the message to include this information before calling the Write-Log cmdlet.

It still somewhat hacky, but it gets the job done and it could point into a possible solution to apply:

function Get-CallerFunction() 
{
	$var = (Get-PSCallStack).Command
	
	return $var[3]
}

Removing Module prevents the pending logs from writing.

IF you remove the module or close the powershell session, the events waiting to be written are not logged.

This comes up when using a scheduled task and the script finished before the running.

example:

if (!(Get-Command -Name Write-log))
{
Import-Module logging
}
$Logging.Targets += @{
File = @{
Path = "c:\logs%{+%Y%m%d}1.log" # Sets the file destination (eg. 'C:\Temp%{+%Y%m%d}.log')
}
}

foreach ( $a in 1..1000){Write-Log -Level DEBUG -Message $a}
Remove-Module logging

Ability to view output of Invoke-RestMethod in ElasticSearch target

Is there any way to get the output of invoke-restmethod in the ElasticSearch target? I can't seem to find a way to get anything out of that as it is a loaded script block. I've resorted to writing to a file for debugging from within a custom target. What's the recommended method of troubleshooting those calls?

How to use Set-LoggingDefaultLevel?

Hi,

I might be using this wrong, but I can't seem to get the default level set. My understanding is that if I call Set-LoggingDefaultLevel, then I shouldn't need to specify Level on calls to Write-Log, however Level is a mandatory parameter on Write-Log. I would expect Write-Log to be interrogating the default value I'm setting, and use that on all subsequent calls.

Or is my understanding incorrect?

Mike.

Message being lost with -Wait-Logging flag

I have a script that does tasks in different threads and I noticed that some messages were being lost. I used the following script to test:

function Config-Logging {
    Set-LoggingDefaultLevel -Level 'INFO'
    Add-LoggingTarget -Name File -Configuration @{Path = 'C:\Temp\example_%{+%Y%m%d}2.csv'}
}
$Level = 'DEBUG', 'INFO', 'WARNING', 'ERROR'

$LoggingDemo = {
    Config-Logging
    foreach ($i in 1..100) {
        Write-Log -Level ($Level | Get-Random) -Message 'Message n. {0} , Job{1} ' -Arguments @($i, $_)
        Start-Sleep -Milliseconds (Get-Random -Min 100 -Max 150)
    }

    Wait-Logging
}

1..5 | Start-RSJob -ScriptBlock $LoggingDemo -ModulesToImport 'Logging', 'PoshRSJob' -VariablesToImport 'Level' -FunctionsToImport 'Config-Logging'

The script above spawns 5 concurrent threads, each one logging 100 message to the log file.

Expected result: 500 lines written to example CSV file
Actual result: Number of lines written varies. May need to try different times.

Note: I'm using PoshRSJob for multithreading.

Set-LoggingDefaultFormat Ignored

It seems a custom logging format is ignored, but still acts as if it is set when you call Get-LoggingDefaultFormat. It does not make a difference if I set the default format before or after adding a target

PS C:\> Get-LoggingDefaultFormat
[%{timestamp:+%Y-%m-%d %T%Z}] [%{level:-7}] %{message}

PS C:\> Add-LoggingTarget -Name Console
PS C:\> Write-Log -Level INFO -Message "Test"
[2019-09-04 16:47:09-04] [INFO   ] Test

PS C:\> Set-LoggingDefaultFormat -Format "%{timestamp:+yyyy-MM-dd HH:mm:ss.fff},%{level},%{message}"
PS C:\> Write-Log -Level INFO -Message "Test"
[2019-09-04 16:47:28-04] [INFO   ] Test

PS C:\> Set-LoggingDefaultFormat -Format "%{+yyyy-MM-dd HH:mm:ss.fff},%{level},%{message}"
PS C:\> Write-Log -Level INFO -Message "Test"
[2019-09-04 16:47:43-04] [INFO   ] Test

PS C:\> Write-Log -Level ERROR -Message "Test"
[2019-09-04 16:47:56-04] [ERROR  ] Test

PS C:\> Get-LoggingDefaultFormat
%{+yyyy-MM-dd HH:mm:ss.fff},%{level},%{message}

PS C:\> Set-LoggingDefaultFormat -Format "[%{timestamp:+%Y-%m-%d}] [%{level}] %{message}"
PS C:\> Write-Log -Level ERROR -Message "Test"
[2019-09-04 16:53:43-04] [ERROR  ] Test

PS C:\> Get-LoggingDefaultFormat
[%{timestamp:+%Y-%m-%d}] [%{level}] %{message}

The pester tests all pass for Replace-Token so I think it has something to do with the formatting of the message in the Write-Log function. I haven't been able to dig into the source yet.

I am running:

  • PS v5.1.17763.503
  • Windows 10 1809 x64 Enterprise
  • Logging module version 4.2.3

Trying the TL;DR example as stated fails with multiple errors

Following the TL;DR basic example explicitly (literally copy pasta) from https://logging.readthedocs.io/en/latest/ fails with the following errors:

Exception calling ".ctor" with "1" argument(s): "Cannot process argument because the value of argument
"validValues" is out of range. Change argument "validValues" to a value that is within range.
Parameter name: validValues
Actual value was System.String[]."
At C:\Program Files\WindowsPowerShell\Modules\Logging\private\New-LoggingDynamicParam.ps1:80 char:5
$validateSetAttribute = [System.Management.Automation.ValidateSet ...
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : PSArgumentOutOfRangeException

Exception calling ".ctor" with "1" argument(s): "Cannot process argument because the value of argument
"validValues" is out of range. Change argument "validValues" to a value that is within range.
Parameter name: validValues
Actual value was System.String[]."
At C:\Program Files\WindowsPowerShell\Modules\Logging\private\New-LoggingDynamicParam.ps1:80 char:5
$validateSetAttribute = [System.Management.Automation.ValidateSet ...
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : PSArgumentOutOfRangeException

Level not a valid integer or a valid string:
Level not a valid integer or a valid string:
.
.
.
i stopped execution but i would be met with 98 more of the same "Level not a valid integer or a valid string:"

below is the code:

`Import-Module Logging

Set-LoggingDefaultLevel -Level 'WARNING'
Add-LoggingTarget -Name Console
Add-LoggingTarget -Name File -Configuration @{Path = 'C:\Temp\example_%{+%Y%m%d}.log'}

$Level = 'DEBUG', 'INFO', 'WARNING', 'ERROR'
foreach ($i in 1..100) {
Write-Log -Level ($Level | Get-Random) -Message 'Message n. {0}' -Arguments $i
Start-Sleep -Milliseconds (Get-Random -Min 100 -Max 1000)
}

Wait-Logging # See Note`

this was run from PowerGUI. i am met with same from console or ISE.

Write-log no simple call

Hello,
I tested your module on Windows 10 , PS 5.1 , is very famous!

But I can call Write-Log without Level parameter, on documentation , it's possible. Can you give me an exemple ?
If I give a level each time, it's fine. But it's not very beautiful when you read code.

KR
Damien

Add-LoggingTarget fails to load custom targets when multipe processes are running.

I opened a issue about this before but I was 100% sure how to reproduce the issue. I believe that the path or files set in "Set-LoggingCustomTarget" are locked when multiple PowerShell processes are using the logging module. I have created a test custom target that you can test with. Test-Logging.

If you download the example I created above, you can run the following command to test. But, to have a failure you will need to be running this command in two separate consoles. I have also included a screenshot of the error in the repo.
'1 .. 100 |% { powershell -file "C:\scripts\Test-Logging\test.ps1"}'.

Thanks so much for your help!

Encoding in log file

Hi

Cannot seem to select encoding for the log file.

My log file output is in swedish and I would like to be able to select encoding when the log file iss created.

Remove Start-Sleep from Logging.psm1

Inside Logging.psm1 the consumer of the message queue only consumes messages every 10ms.
L 109 : Start-Sleep -Milliseconds 10

This leads to two problems :

  1. Unecessary cpu usage
  2. Missing messages
    2.1 Partly resolved through Wait-Logging => Enforces unecessary delay

Request :
Proper Producer-Consumer with Wait and Pulse. (Thread only works when new messages are laid into the queue)

Memory leak in version 2.10.0

I always use the latest version of the module and since 4 days my build was slow as hell and even failed.
I tried everything to fix it, but nothing worked.

I saw that the memory of the powershell.exe process grew to 7 GB and more and i checked all modules and saw that 2.10.0 was released 4 days ago :)

After downgrade to module version 2.9.1 my build worked as before and no significat memory increase was observed.
So there might be a problem in module version 2.10.0

LoggingTarget Console not working as expected

In the latest versions of this powershell logging library I am getting unexpected behavior.

Install-Module Logging
Import-Module Logging

Add-LoggingTarget -Name Console
Add-LoggingTarget -Name File -Configuration @{
    Path = "C:/Temp/%{+%Y.%m.%d}.log"
    Append = $false
}

Write-Log "Test"

With the code above while running through the PowerShell ISE "Test" does not get logged into the console, however it does get logged into the File location. I went back a version and the same thing occurred, finally I went back to 4.1.1 and the above code was working as expected.

I am not sure if there has been a functional change, but it is not reflected in the wiki here on github.

Cannot process argument because the value of argument "validValues" is out of range

The first time I call Add-LoggingTarget, I receive this sequence of errors:


New-Object : Exception calling ".ctor" with "1" argument(s): "Cannot process argument because the value of argument "validValues" is out of range. Change argument "validValues" to  a value that is
within range.
Parameter name: validValues
Actual value was System.String[]."
At C:\Program Files\WindowsPowerShell\Modules\Logging\2.4.3\Logging.psm1:321 char:33
+ ... Attribute = New-Object System.Management.Automation.ValidateSetAttrib ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [New-Object], MethodInvocationException
    + FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand

New-Object : Exception calling ".ctor" with "1" argument(s): "Cannot process argument because the value of argument "validValues" is out of range. Change argument "validValues" to  a value that is
within range.
Parameter name: validValues
Actual value was System.String[]."
At C:\Program Files\WindowsPowerShell\Modules\Logging\2.4.3\Logging.psm1:321 char:33
+ ... Attribute = New-Object System.Management.Automation.ValidateSetAttrib ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [New-Object], MethodInvocationException
    + FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand

Cannot index into a null array.
At C:\Program Files\WindowsPowerShell\Modules\Logging\2.4.3\Logging.psm1:302 char:13
+         if ($TargetConf.Configuration[$Conf] -and $Configuration[$Con ...
+             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : NullArray

Here's the relevant section of the script using this module:

if (Import-Module -Name 'Logging' -ErrorAction SilentlyContinue -PassThru) {
    Set-LoggingDefaultLevel -Level INFO
    Add-LoggingTarget -Name Console -Configuration @{}
    Add-LoggingTarget -Name File -Configuration @{
        Path  = $logFile
    }
}

The script stack trace points to the third line in the above snippet (the first call to Add-LoggingTarget) as the line that caused this error.

The strange thing is that after receiving this error once, I can't replicate it - running exactly the same script does not generate the error. I'm wondering if it's some sort of load order issue.

Logging.psm1:321 is this line:

$ValidateSetAttribute = New-Object System.Management.Automation.ValidateSetAttribute($LogTargets.Keys)

I've confirmed this issue using PowerShell 5.0 on Win7 x64 as well as PowerShell 4.0 on Server 2012R2.

Let me know if I can provide any additional info. Thanks for all the work on this!

Send Message to Specific Target (Slack)

Hello,

I have downloaded the latest version of the Logging module and it seems to have broken (or fixed ๐Ÿ˜› ) the method I used (Issue #33). Digging around it seems like most of the previous plumbing of the Logging.psm1 file has changed. Anytime I use Write-Log now the message goes to all targets. My goal is to send more verbose logs to File and send only major errors to slack, otherwise it gets very noisy in the slack channel.

Is there different way to achieve the same result with the newer versions?

Thank you

Writing extended ascii to text file

If I attempt to write this character "โ€”" in the Write-Log function, it will send to console out properly. however, it will output a "?" to the log file.

In my current logging function I am able to write that character. EsOsO Logging solution is much more clean and elegant so I would like to use it in my project.

can you see any way around this?

Loglevel is ignored

Add-LoggingTarget -Name Console
Set-LoggingDefaultLevel -Level WARNING
Write-Log -Level INFO -Message 'Test'
[2019-07-01 23:28:19+02] [INFO   ] Test

Set-LoggingCustomTarget throws error

When setting a custom logging target, I get the following error. I am using PowerShell 5.1 and version 4.2.13. I'm pretty certain that the event will be removed once the runspace is removed anyways. I don't think it needs to be unregistered from my local testing.

This is the script I used to test. Test-Logging.

Set-LoggingCustomTarget : Cannot bind argument to parameter 'SubscriptionId' because it is null..

Thanks so much for your help!

Incompatibility with ErrorAction=Stop and Set-StrictMode -Version 2.0

Steps to reproduce

We run our automation modules with Set-StrictMode -Version 2.0 and ErrorActionPreference=Stop.
After multiple different calls to the logging consumer, single methods seem to be in an undefined state resulting in a terminating error.
image

Error arises from Replace-Token ($var).

Changes to be applied

  • Fix methods to never allow an undefined variable (inconsistency)
  • Determine the exact reason behind the MethodNotFoundException resulting from terminating errors
  • Rework Replace-Token

Target Level not honored

All messages send to a target gets logged.

> $Logging.Level = 'ERROR'
> $Logging.Targets = @{Console = $null}
> Write-Log -Level DEBUG -Message 'Test'
[2016-04-26 13:53:17+02] [DEBUG  ] Test

Intermittent issue with Logging module

Hi,

I'm trying to implement your logging module, but seeing some intermittent strange behavior. An example, I run a script and get the following error:

Replace-Token : The term 'Replace-Token' is not recognized as the name of a cmdlet, function, script file, or operable 
program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At C:\Program Files\WindowsPowerShell\Modules\Logging\4.1.1\targets\File.ps1:24 char:17
         $Text = Replace-Token -String $Configuration.Format -Source $ ...
                 ~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (Replace-Token:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

I can immediately run the same script again and it works without error.

Any ideas on what may be causing this?

Name                           Value
----                           -----
PSVersion                      5.1.14409.1018
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.14409.1018
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1

Thanks,
David

Add-LoggingTarget randomly fails to load custom targets

I have been troubleshooting a issue where sometimes Add-LoggingTarget randomly fails to load custom targets. However, if I add my custom target into the Target folder for the module, I do not have this issue. I used Get-LoggingTargetAvailable to test to see if the target was loaded, and it was. The issue is very intermittent.

This is the error:

powershell.exe : Add-LoggingTarget : Cannot validate argument on parameter 'Name'. The argument 
At line:3 char:5
+     & powershell -NonInteractive -executionpolicy bypass -file C:\scr ...
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (Add-LoggingTarg.... The argument :String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError
 
"Gelf" does not belong to the set "Email,Console,ElasticSearch,File,Slack" 
specified by the ValidateSet attribute. Supply an argument that is in the set 
and then try the command again.
At C:\scripts\Test-Import\Test-Import.ps1:22 char:29
+     Add-LoggingTarget -Name Gelf -Configuration @{
+                             ~~~~
    + CategoryInfo          : InvalidData: (:) [Add-LoggingTarget], ParentCont 
   ainsErrorRecordException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Add-LoggingTarg 
   et

Custom prompt gets splitted during output

During output my prompt gets splitted by the logged message:

bonvicini@vclientad04 ๎‚ฐ ~\Documents\dev ๎‚ฐ ๎‚  master [+1] ๎‚ฐ $ ๎‚ฐ foreach ($i in 1..100) {Write-Log -level DEBUG $i}
[2016-09-13 10:51:01+02] [DEBUG  ] 1
[2016-09-13 10:51:01+02] [DEBUG  ] 2
[2016-09-13 10:51:01+02] [DEBUG  ] 3
[2016-09-13 10:51:01+02] [DEBUG  ] 4
[2016-09-13 10:51:01+02] [DEBUG  ] 5
[2016-09-13 10:51:01+02] [DEBUG  ] 6
[2016-09-13 10:51:01+02] [DEBUG  ] 7
[2016-09-13 10:51:01+02] [DEBUG  ] 8
[2016-09-13 10:51:01+02] [DEBUG  ] 9
 bonvicini@vclientad04 ๎‚ฐ ~\Documents\dev [2016-09-13 10:51:01+02] [DEBUG  ] 10
[2016-09-13 10:51:01+02] [DEBUG  ] 11
[2016-09-13 10:51:01+02] [DEBUG  ] 12
[2016-09-13 10:51:01+02] [DEBUG  ] 13
[2016-09-13 10:51:01+02] [DEBUG  ] 14
๎‚ฐ ๎‚  master [+1] ๎‚ฐ $ ๎‚ฐ[2016-09-13 10:51:01+02] [DEBUG  ] 15
 [2016-09-13 10:51:01+02] [DEBUG  ] 16

PS. the unrecognized characters are from Source Code Pro to get a Powerline like prompt
2016-09-13 11_03_10-clipboard

New line in body of Teams message

Hi

How can I write a new line in the body of a Teams message?

No matter what I tried so far, I always ended up getting one long string in the body of the Teams message. Any ideas / suggestions?

Thanks

Target WinEventLog gives "Level not a valid integer or a valid string:"

Running the following code snipped does not work for me:

import-module logging
New-EventLog -LogName "Application" -Source "testsource"
Add-LoggingTarget -Name WinEventLog -Configuration @{
	LogName = "Application"             
	Source  = "testsource"   
}
Write-Log -Message "test" -Level WARNING

It gives me

Level not a valid integer or a valid string:

Is there something I missed?

ElasticSearch target does not work

Hello.
I am trying to add logs to ElasticSearch using your module, but nothing happend. I do not get any errors and do not see new messages in ElasticSearch index.
Here is my code.

Set-LoggingDefaultLevel -Level 'WARNING'
Add-LoggingTarget -Name ElasticSearch -Configuration @{
    ServerName  = 'localhost'
    ServerPort  = 9200
    Index       = 'powershell-2018-05-10'
    Type        = 'doc'
    #Level       = <NOTSET>          # <Not required> Sets the logging format for this target
}

$Json = '{"source" : "Logging","datetime" : "' + (Get-Date).ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ss') + '","message" : "Add message from powershell"}'
Write-Log -Level 'WARNING' -Message $Json

Wait-Logging        # See Note

I have successfully sent messages with Invoke-RestMethod cmdlet with parameters from example, but can't force to work your module.

Rewrite build pipeline

Right now the module is stuck at 4.2.13 cause the build process on appveyor fails with an exception.
I need help in reworking the pipeline and finally build 4.2.14 with the console hang fix.

I'd really like to carry on the project but right now I'm short on spare time but understand that the pending fix is a lot valuable for daily usage of the module.

To anyone who wants to contribute I can give contributor access to the repo.

Error when running sample code from TL;DR

Hello,

Trying to use the TL;DR from Logging.psd1 results in some errors. First the code being run:

Set-LoggingDefaultLevel -Level 'WARNING'
Add-LoggingTarget -Name Console
Add-LoggingTarget -Name File -Configuration @{Path = 'C:\my\path\example_%{+%Y%m%d}.log'}

$Level = 'DEBUG', 'INFO', 'WARNING', 'ERROR'
foreach ($i in 1..100) {
    Write-Log -Level ($Level | Get-Random) ('Message n.{0}' -f $i)
    Start-Sleep -Milliseconds (Get-Random -Min 100 -Max 1000)
}

Wait-Logging        # See Note

And the errors:

New-Object : Exception calling ".ctor" with "1" argument(s): "Cannot process argument because the value of argument 
"validValues" is out of range. Change argument "validValues" to  a value that is within range.
Parameter name: validValues
Actual value was System.String[]."
At C:\Users\<user>\OneDrive - <tenant>\WindowsPowerShell\Modules\Logging\Logging.psm1:307 char:33
+ ... Attribute = New-Object System.Management.Automation.ValidateSetAttrib ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [New-Object], MethodInvocationException
    + FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand
 
New-Object : Exception calling ".ctor" with "1" argument(s): "Cannot process argument because the value of argument 
"validValues" is out of range. Change argument "validValues" to  a value that is within range.
Parameter name: validValues
Actual value was System.String[]."
At C:\Users\<user>\OneDrive - <tenant>\WindowsPowerShell\Modules\Logging\Logging.psm1:307 char:33
+ ... Attribute = New-Object System.Management.Automation.ValidateSetAttrib ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [New-Object], MethodInvocationException
    + FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand
 
Cannot index into a null array.
At C:\Users\<user>\OneDrive - <tenant>\WindowsPowerShell\Modules\Logging\Logging.psm1:290 char:13
+         if ($TargetConf.Configuration[$Conf] -and $Configuration[$Con ...
+             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : NullArray

Rework Replace-Token

This function is heavily used across the module. Better tune it for max efficiency.

Wait-Logging after running background jobs losing log messages

I am unsure if I am placing it in the correct location but am basing it off the wiki info. I currently have a Powershell script that is starting roughly 5 different jobs using the Start-Job cmdlet. Within the jobs I am using the Write-Log cmdlet and after a Wait-Job -Job $jobs I wait for all the jobs to be completed and then call Wait-Logging so the script looks something like this -

$jobs =@()
foreach($item in list){
    $jobs += Start-Job -Name $item.Name -ScriptBlock { Write-Log -Message "This is from inside." }
}

Wait-Job -Job $jobs
Wait-Logging

Yet no log messages from inside the jobs actually get written to console or file. I have tried placing the Wait-Logging in a few different locations and nothing has changed.

Am I understanding the Wait-Logging cmdlet incorrectly?

edit:
After a bit more research it appears within the Start-Job process it doesn't contain the Write-Log cmdlet, I can try to figure that out on my own. However if I configure the logging targets outside of the job from within the job I have to re-specify the file, is there any way for the system to automatically detect to write to the file it has been writing to?

Slack Logging

Is Slack logging still compatible? I'm having trouble logging messages to Slack. I've verified my URI is proper as I can send a manual Invoke-WebRequest command to Slack, but not from this Logging module.

Create a timestamputc format

It would be useful if there was a timestamputc format that would output the time in UTC (using [DateTime] ToUniversalTime() method.

Allow passing Icon into Write-Log for Slack Target

  • As a user I would like to be able to pass in a custom icon into the Slack Target to override the existing ones.

  • Today there is no way to send a message to one target vs another that I can see. I have created a Specific Logging Level that handles the SLACK messages and that is working. The problem is the Slack target module supplies the ๐Ÿ”ฅ โš ๏ธ โ—๏ธ icons based on logging value so all of my slack messages are coming in with FIRE icon since I made the logging level 50

  • Would be nice to allow passing in an icon from my slack org for each message that I am sending

  • I tried setting three new Logging-Levels (25 -SLACKINFO, 35 -SLACKWARN, 50- SLACKERROR) but since the -Level param for the Slack target is a String and that is how I am targeting the Slack logging target no messages were being sent. I could be doing this wrong as well.

Allow Write-Log to pass in -Icon ':<insert icon name here>:'

Support for powershell core

powershell core does not support apartment states.

Checking for powershell edition -eq Desktop prior to setting the Apartment state would prevent this error.

The property 'ApartmentState' cannot be found on this object. Verify that the property exists and can be set.
At /Users/jason.chester/.local/share/powershell/Modules/Logging/4.0.3/private/Start-LoggingManager.ps1:19 char:5
+     $initialState.ApartmentState = 'MTA'
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : PropertyAssignmentException

in Start-LoggingManager.ps1 @ Line 18

    $initialState = [InitialSessionState]::CreateDefault()
    if($PSEdition -eq 'Desktop') {
        $initialState.ApartmentState = 'MTA'
    }

Add-LoggingTarget : Cannot validate argument on parameter 'Name' for "WinEventLog"

This is happening intermittently in a script that runs as a scheduled task. Sometimes the task starts up and logs fine. Sometimes it throws this error. (PSVersion 5.1.14393.2430, Logging version 4.2.11)

Code that errors

Import-Module Logging
Add-LoggingTarget -Name WinEventLog -Configuration @{
  LogName="$($evt.log)"
  Source ="$($evt.source)"
}

Error message

Add-LoggingTarget : Cannot validate argument on parameter 'Name'. The argument "WinEventLog" does not belong to the 
    set "Email,ElasticSearch,Console,Slack,File,Seq" specified by the ValidateSet attribute. Supply an argument that is in 
    the set and then try the command again.

I'd guess AV or over-provisioned hosting or something else is causing Start-LoggingManager to take longer than 500ms to do its work

From Logging.psm1

Start-LoggingManager

# Let the runspace spinup and generate all the available targets
Start-Sleep -Milliseconds 500 

What would it take to change this from a fixed interval to a loop that checks status every 100ms and either returns when ready or times out with an error?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.