Most of what I’ve written about logging this month has been about getting it wrong. The OrphanedSid series had One Run, One Log File, where a run’s log ended up split across two files, and Half the Time Went to Logs Nobody Read, where formatting log lines nobody would see cost more than the work. That module rolls its own logger, and every bug in those posts lived in code I’d written to do something a logging module already does.
I built this skill because I usually end up hand-rolling logging and forgetting about PSFramework, and it’s just so mature that I kick myself each time. It’s for adapting an existing script’s logging or fleshing out a new one.
My PowerShell standards for AI agents (ai-powershell-standards) had an answer for this before version 2.0: a section on PSFramework. When I tested it, it didn’t work. It passed a level that Write-PSFMessage rejects, and it put the correlation ID somewhere the file log never writes it. An agent that followed it faithfully would have produced logging that failed on the first call.
The new powershell-logging skill replaces that section. It adds log files to a module or a script with PSFramework, or takes the logging a project already has and brings it into one form. Every statement in it was measured with PSFramework 1.15.479 on PowerShell 7.7.0, 7.6.10 and Windows PowerShell 5.1. I’ll walk through what it tells an agent to do, and why each piece is there.
What the old guidance said
This was the setup function the standards handed to agents:
| |
And the wrapper every function was meant to call:
| |
Read with what the skill now knows, almost every line has a problem:
- PSFramework has no level named
Information. The wrapper’sValidateSetallowed it, and the guide’s own examples passed-Level Informationin four places. -Level HostandCriticalgo straight to the console, where a caller can’t capture or silence them.- The module turned on providers when it initialized. A module that does that decides where the output of every other script in the session goes.
- The correlation ID went into
-Data. The file log doesn’t write-Dataunless a header names it, so every line was missing the one field that was supposed to tie a run together.
Twenty lines held all of that, and they sat in a rule file that agents loaded for every .ps1.
The streams stay the default
Before any of that, you decide whether you need the skill at all. The error handling rules send messages to PowerShell’s own streams and add no logging module. ERR-30 says it:
That stays the rule for every project. The skill is for when you ask for log files. When you do, you keep the streams, because a message written with Write-PSFMessage still reaches the caller’s verbose or warning stream. If you call the function with -Verbose, you see what you always saw.
One note under ERR-30 came with the skill, so the review skill doesn’t undo the logging skill’s work. A project that requires PSFramework, in its manifest or a #requires -Modules line, has made that choice, and an agent reviewing your code shouldn’t turn its Write-PSFMessage calls back into Write-Verbose.
Add, or standardize
The skill starts by looking. An agent searches the files in scope for every way they might already log: Write-Host, the four Write-* stream cmdlets, Write-PSFMessage, Stop-PSFFunction, Set-PSFLoggingProvider, Start-Transcript, Write-EventLog, Add-Content or Out-File appending to a file, and any function of the project with Log in its name.
Then it picks a mode and tells you which one applies. Add is for code where nothing writes a log file yet. Standardize is for code that logs some other way, or several other ways. The agent lists each way with the number of places it shows up, then replaces them. A homegrown Write-Log function gets its callers changed first, and the function goes away only when nothing calls it.
The agent stops and asks you before it removes Start-Transcript, because a transcript records console output that a log file doesn’t. It also asks where your log files go and how long you keep them, unless the project already says. The skill is explicit: don’t invent a path or a retention time.
Levels in a function
The code that does the work, a module or a function, only writes messages. It never enables, changes or disables a logging provider, and a module never does it on import (MOD-06). The script that runs the code decides where messages go.
This is the mapping the skill gives:
| The code has, or means | Write |
|---|---|
Write-Verbose, progress detail | Write-PSFMessage -Level Verbose |
Write-Debug, diagnostics | Write-PSFMessage -Level Debug |
Write-Warning, a condition the caller should know about | Write-PSFMessage -Level Warning |
Write-Host or Write-Information with status text | Write-PSFMessage -Level Verbose |
A failure, in catch | Write-PSFMessage -Level Error with 3>$null and the type of $_.Exception in the message, then the error as ERR-10 or ERR-13 says |
Those four levels are the only ones a function gets. PSFramework writes Critical, Important, Host, Output and Significant to the console directly, and that breaks ERR-31 the same way Write-Host would. A Verbose message shows when the caller passes -Verbose, a Warning follows -WarningAction, and every message goes to the log whether it’s shown or not. Debug included.
A failure gets logged once and raised once
The skill’s example function is Get-FolderSize, a real file in standards/examples with its own tests. Its catch block:
| |
-Level Error doesn’t write an error. It writes a warning, and it doesn’t end the function either. Logging isn’t error handling. The function logs the failure and then reports it the way the error rules say to: $PSCmdlet.WriteError() for one item that failed, $PSCmdlet.ThrowTerminatingError() for a failure that ends the function.
The 3>$null throws away that warning on this one call. Without it you get the failure twice as the caller, once as a warning and once as an error, and -ErrorAction SilentlyContinue silences only the error. The script’s tests check both halves:
| |
Stop-PSFFunction and -EnableException are out. They’re PSFramework’s own way of ending a function, and they’d replace the error handling the rest of the standards depend on.
Targets, tags, and what stays out
The item being processed goes in -Target, as its name or ID. A category goes in -Tag. Secrets and personal data stay out of the message, the target, the tags and -Data (SEC-06).
That rule is why the failure above names the exception’s type and leaves out -ErrorRecord. Pass the error record and PSFramework adds the exception’s message to the logged message. The message of a file system error holds the resolved path, so a folder under your profile puts your user name in the log, even when the caller gave a relative path. The caller still gets the whole error from $PSCmdlet.WriteError($_).
The skill also puts a number on cost. One Write-PSFMessage call took between 16 microseconds and 1.5 milliseconds on the machines measured, whether the message was shown or not. On a large input, that adds up, so a function writes one message for each step or batch, and skips the per-item ones.
I put this one in after the OrphanedSid log problem, where fixing it sped that project up a lot.
Finally the dependency gets declared. A module lists PSFramework in RequiredModules at the version the project tested:
| |
Importing the module then loads PSFramework. The README names it under requirements (RDM-02), and CI installs it at a fixed version (CIC-02).
The script decides where messages go
The other example is Invoke-FolderSizeReport.ps1, the script that runs Get-FolderSize and owns the log file. Most of what’s interesting is in the splat it builds:
| |
Every setting there answers a default that surprised somebody. Out of the box, a JSON log file starts with a comma and writes the level as a number. -JsonCompress and -JsonNoComma together give one JSON object per line, so the file reads back with Get-Content | ConvertFrom-Json. -JsonString makes the level a word.
The default headers include the computer name and the user name on every line. That’s personal data in a file that might get attached to a ticket, so the script names its columns.
The default timestamp is written in the format of the session’s culture, so two of your machines with different settings write two different formats into logs you mean to read together. The script fixes the format and writes UTC.
%Date% in the file name gives one file per day. It’s the local date, even with -UTC, so one file can hold timestamps from two UTC dates. The skill says that out loud, so you don’t find it at midnight.
Then the rotation filter. -LogRotatePath and -LogRetentionTime remove old files, and with the default filter that means every file in the folder older than the retention time, the project’s or not. Point your log at a shared folder without the filter and it takes other people’s old files with it.
One line of the file, from a run against a folder named reports:
| |
PSFramework’s own log
PSFramework has a provider named filesystem, and it’s on by default. On PowerShell 7 it writes every message, shown or not, to the profile of the account, with the computer name, the path of the script and the target. On PowerShell 7 and Windows PowerShell 5.1 it writes each error there as an XML file with the computer name and the script stack trace.
You get a second log nobody asked for, in a place nobody looks, holding the details the first log was careful to leave out. The script turns it off for the run.
My first version of the example did exactly that and left it off. The second version is in the repo for a reason. The provider belongs to the whole process, so in a session that runs other code, every module using PSFramework lost its log after the script ended. The script now reads the state first and puts it back:
| |
The setup sits inside try so a failure there gets put right too. The order in finally comes from measurement. Wait-PSFMessage goes first, because without it the last message was missing from the file after the process ended, on a Windows 11 virtual machine. Then the run’s own provider goes off, then filesystem comes back.
The skill also records what happens once PSFramework’s own log comes back on: the run’s messages don’t reach it, and PowerShell 7 creates an empty file in your profile at that moment.
Following one run through the log
A message the script writes itself comes out with the module name <Unknown> and the script’s file name as its function name. -IncludeModules limits an instance to named modules, and it leaves those messages out with everything else, so if your script filters that way, you lose its own lines.
For a correlation ID, the old guidance got half of it right. The ID goes in -Data, and a header names it:
| |
| |
An unsigned assembly
PSFramework’s assembly isn’t signed. Windows Smart App Control refuses to load it, with “An Application Control policy has blocked this file”, and other application control policies can do the same. The first step of the skill is to import the module and stop if the import fails:
When the import fails, stop and report it. Do not look for a way around the policy.
An agent that hits a block tells you about it and stops there. When the code runs on other machines, the agent asks you whether those machines have such a policy. And the final report always says the project now depends on PSFramework and that its assembly isn’t signed, because some organizations approve that kind of dependency before anyone uses it.
I put that step in because Smart App Control blocked PSFramework on my own machine until I turned it off.
The repo’s own tests handle it the same way. They try the import in BeforeDiscovery and skip the tests that write through the real module when it fails:
CI installs PSFramework at 1.15.479, so those tests run on every pull request on Windows, Linux and macOS.
Testing code that logs
The skill covers unit tests and integration tests. A unit test replaces Write-PSFMessage with a mock and asserts the messages that matter by $Level, $Message, $Target and $Tag, with Should-Invoke -ParameterFilter. The mock names the module when the function lives in one (TST-21), and not when the test dot-sources the function file. A failure gets asserted twice: the Error message, and the error the caller receives (TST-17).
An integration test runs the script with a log folder under $TestDrive and reads the file back line by line. These are from the example’s tests:
| |
And it checks that the script left the process the way it found it:
The tests themselves turn filesystem off in BeforeAll and restore it in AfterAll, for the same reason the script does, so running the suite doesn’t leave a trail in your profile.
What the agent reports
The skill ends with a report: which mode applied and what the search found, the files changed, the logging replaced or removed, where the log files go, the results of PSScriptAnalyzer and the tests, and one quoted line of the log file the script wrote. Plus the dependency note on the unsigned assembly. If PSFramework couldn’t load, the report says plainly that the code is untested.
With the quoted log line in the report, an agent can’t claim the logging works without having run the script and read the file it wrote.
