{"slug":"powershell-logging-4","title":"powershell-logging","summary":"Add logging to a PowerShell module, script, or project with PSFramework, or bring the logging that it already has into one standard form. Use when asked to add, set up, standardize, unify, or clean up logging or log files.","platform":"Claude","tags":[],"authorName":"LLM Mart","authorSlug":"llm-mart","score":0,"source":"github","price":null,"verified":false,"createdAt":"2026-11-27T19:12:22.704735Z","repo":{"url":"https://github.com/fadwen/ai-powershell-standards","stars":24,"forks":4,"license":"MIT","updatedAt":"2026-11-26T19:42:48Z"},"bodyHtml":"<hr>\n<h2>name: powershell-logging\ndescription: Add logging to a PowerShell module, script, or project with PSFramework, or bring the logging that it already has into one standard form. Use when asked to add, set up, standardize, unify, or clean up logging or log files.</h2>\n<h1>Add or standardize logging with PSFramework</h1>\n<p>These standards write messages to the output streams and add no logging module (ERR-30). Use this\nskill when a project also wants log files. The streams keep working: a message written with\n<code>Write-PSFMessage</code> still reaches the caller's verbose or warning stream.</p>\n<p>Read these first, unless they are already loaded:</p>\n<ul>\n<li><code>.github/copilot-instructions.md</code>, or <code>AGENTS.md</code> if the repository has no such file</li>\n<li><code>.github/instructions/powershell-error-handling.instructions.md</code></li>\n<li><code>.github/instructions/powershell-security.instructions.md</code></li>\n</ul>\n<p>Every statement about PSFramework below was measured with PSFramework 1.15.479 on PowerShell 7.7.0,\nPowerShell 7.6.10, and Windows PowerShell 5.1.</p>\n<h2>Steps</h2>\n<ol>\n<li>Confirm that PSFramework loads, with <code>Import-Module -Name PSFramework</code>. Its assembly is not\nsigned. Windows Smart App Control refuses the import with \"An Application Control policy has\nblocked this file\", and another application control policy can do the same. When the import\nfails, stop and report it. Do not look for a way around the policy. When the code runs on\nother computers, ask whether they have such a policy.</li>\n<li>Find the logging that the files in scope already have. Search for <code>Write-Host</code>, <code>Write-Verbose</code>,\n<code>Write-Warning</code>, <code>Write-Debug</code>, <code>Write-Information</code>, <code>Write-PSFMessage</code>, <code>Stop-PSFFunction</code>,\n<code>Set-PSFLoggingProvider</code>, <code>Start-Transcript</code>, <code>Write-EventLog</code>, text appended to a file with\n<code>Add-Content</code> or <code>Out-File</code>, and functions of the project whose name contains <code>Log</code>.</li>\n<li>Choose the mode from what was found, and say which one applies:\n<ul>\n<li><strong>Add.</strong> Nothing writes a log file. Add the standard form below.</li>\n<li><strong>Standardize.</strong> The code logs in one or more other ways. List each way with the number of\nplaces, then replace them with the standard form. Keep the meaning of every message and move\nit to the level in the table. Change the callers of a logging function of the project first,\nand remove the function only when nothing calls it any more. Code that already uses\nPSFramework is brought to the same form: other levels, <code>Stop-PSFFunction</code>, and a provider\nthat a module sets up are replaced. Ask before removing <code>Start-Transcript</code>, because a\ntranscript records console output that a log file does not.</li>\n</ul>\n</li>\n<li>Ask where the log files go and how long they are kept, unless the project already says so. Do\nnot invent a path or a retention time.</li>\n<li>Change the code that does the work, then the script that runs it, then the tests, as the three\nsections below say.</li>\n<li>Run PSScriptAnalyzer and the tests, then run the script once and read the log file it wrote.</li>\n</ol>\n<h2>The code that does the work</h2>\n<p>A module or a function only writes messages. It MUST NOT enable, change, or disable a logging\nprovider, and a module MUST NOT do so when it is imported (MOD-06). The script that runs the code\ndecides where the messages go.</p>\n<table>\n<thead>\n<tr>\n<th>The code has, or means</th>\n<th>Write</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td><code>Write-Verbose</code>, progress detail</td>\n<td><code>Write-PSFMessage -Level Verbose</code></td>\n</tr>\n<tr>\n<td><code>Write-Debug</code>, diagnostics</td>\n<td><code>Write-PSFMessage -Level Debug</code></td>\n</tr>\n<tr>\n<td><code>Write-Warning</code>, a condition the caller should know about</td>\n<td><code>Write-PSFMessage -Level Warning</code></td>\n</tr>\n<tr>\n<td><code>Write-Host</code> or <code>Write-Information</code> with status text</td>\n<td><code>Write-PSFMessage -Level Verbose</code></td>\n</tr>\n<tr>\n<td>A failure, in <code>catch</code></td>\n<td><code>Write-PSFMessage -Level Error</code> with <code>3&gt;$null</code> and the type of <code>$_.Exception</code> in the message, then the error as ERR-10 or ERR-13 says</td>\n</tr>\n</tbody>\n</table>\n<ul>\n<li>These four levels are the only ones for a function or a module. PSFramework writes <code>Critical</code>,\n<code>Important</code>, <code>Host</code>, <code>Output</code>, and <code>Significant</code> straight to the console, where the caller can\nneither capture nor silence them (ERR-31). It has no level named <code>Information</code>.</li>\n<li>A <code>Verbose</code> message is shown when the caller passes <code>-Verbose</code>, and a <code>Warning</code> message follows\n<code>-WarningAction</code>. Every message goes to the log whether it is shown or not, <code>Debug</code> included.</li>\n<li>Logging does not replace error handling. <code>-Level Error</code> writes a warning, not an error, and it\ndoes not end the function. Log the failure, then call <code>$PSCmdlet.WriteError()</code> or\n<code>$PSCmdlet.ThrowTerminatingError()</code>. <code>Stop-PSFFunction</code> and <code>-EnableException</code> MUST NOT be used.</li>\n<li>Discard the warning of the <code>Error</code> level with <code>3&gt;$null</code> on that call. The caller then gets the\nfailure once, as an error. Without it the caller also gets a warning, which\n<code>-ErrorAction SilentlyContinue</code> does not silence.</li>\n<li>Put the item being processed in <code>-Target</code>, as its name or ID and not as a whole object, and a\ncategory in <code>-Tag</code>. Secrets and personal data MUST NOT go into the message, the target, the\ntags, or <code>-Data</code> (SEC-06).</li>\n<li>Do not pass <code>-ErrorRecord</code> for a failure. PSFramework adds the exception's message to the logged\nmessage, and that message can hold what SEC-06 keeps out. The message of a file system error\nholds the resolved path, with the user name under a profile, even when the caller gave a\nrelative path: measured with an access-denied folder on PowerShell 7.6.10 and Windows\nPowerShell 5.1. Name the type of the exception in the message instead. The caller still gets\nthe whole error from <code>$PSCmdlet.WriteError($_)</code>.</li>\n<li>Do not write a message for every item of a large input. One call took between 16 microseconds\nand 1.5 milliseconds on the computers measured, whether the message was shown or not. Write one\nfor each step or batch.</li>\n<li>Declare the dependency. A module lists\n<code>@{ ModuleName = 'PSFramework'; ModuleVersion = '1.15.479' }</code> in <code>RequiredModules</code>, with the\nversion that the project tested (MOD-04). Importing the module then loads PSFramework. Name it\nin the README's requirements (RDM-02) and install it at a fixed version in CI (CIC-02).</li>\n</ul>\n<p>This function follows the form. It and the script below are files with tests in the standards\nrepository:</p>\n\n<h2>The script that runs the code</h2>\n<ul>\n<li>Turn off the provider named <code>filesystem</code> for the run. It is on by default. On PowerShell 7 it\nwrites every message, shown or not, to the profile of the account, with the computer name, the\npath of the script, and the target. On PowerShell 7 and on Windows PowerShell 5.1 it writes each\nerror there as an XML file, with the computer name and the script stack trace (SEC-06).</li>\n<li>Put it back. The provider belongs to the whole process, and other code in the same session may\nuse it. Read <code>(Get-PSFLoggingProvider -Name filesystem).Enabled</code> before turning it off, and in\n<code>finally</code> enable it again when it was enabled. The messages of the run did not reach it\nafterwards. PowerShell 7 creates an empty file in the profile when the provider is enabled again.</li>\n<li>Enable one instance of the <code>logfile</code> provider, with these settings:\n<ul>\n<li>A full path (STY-31). <code>%Date%</code> in the file name gives one file for each day. It is the local\ndate, with <code>-UTC</code> as well, so a file can hold timestamps of two UTC dates.</li>\n<li><code>-FileType Json</code> with <code>-JsonCompress</code> and <code>-JsonNoComma</code>, so that every line is one JSON\nobject, and <code>-JsonString</code>, so that the level is a word. Without them the file starts with a\ncomma and the level is a number.</li>\n<li><code>-Headers</code> with the columns the project wants. The default headers add the computer name and\nthe user name to every line (SEC-06).</li>\n<li><code>-TimeFormat</code> and <code>-UTC</code>. The default timestamp is written in the format of the session's\nculture.</li>\n<li><code>-LogRotatePath</code>, <code>-LogRetentionTime</code>, and <code>-LogRotateFilter</code>, to remove old log files. Set\nthe filter to the names of the project's log files. With the default filter, every file in\nthat folder that is older than the retention time is removed.</li>\n</ul>\n</li>\n<li>Call <code>Wait-PSFMessage</code> in <code>finally</code>, then disable the instance, then put <code>filesystem</code> back.\nWithout the wait, the last message was missing from the file after the process had ended, on a\nWindows 11 virtual machine.</li>\n<li>A message that the script writes itself has the module name <code>&lt;Unknown&gt;</code> and the name of the\nscript file as its function name. <code>-IncludeModules</code> limits an instance to the named modules, and\nleaves those messages out.</li>\n<li>To follow one run or one request through the log, put its ID in <code>-Data</code>, as in\n<code>-Data @{ CorrelationId = $correlationId }</code>, and add the header\n<code>'Data.CorrelationId as CorrelationId'</code>. <code>-Data</code> is not written to the file unless a header\nnames it.</li>\n</ul>\n\n<h2>The tests</h2>\n<ul>\n<li>A unit test replaces <code>Write-PSFMessage</code> with a mock, and asserts the messages that matter with\n<code>Should-Invoke -ParameterFilter</code>, by <code>$Level</code>, <code>$Message</code>, <code>$Target</code>, and <code>$Tag</code>. The mock names\nthe module when the function is in a module (TST-21), and not when the test dot-sources the\nfunction file. It takes the place of the mocks of <code>Write-Verbose</code> and <code>Write-Information</code> that\nTST-20 asks for.</li>\n<li>Assert a failure twice: the message with the level <code>Error</code>, and the error that the caller gets\n(TST-17).</li>\n<li>An integration test runs the script with a log folder under <code>$TestDrive</code> and reads the file back\nline by line with <code>ConvertFrom-Json</code>. It also asserts that the <code>filesystem</code> provider has the\nstate after the script that it had before. A test that writes a message without running the\nscript disables that provider first, and puts its state back in <code>AfterAll</code>.</li>\n</ul>\n<h2>Report</h2>\n<p>Say which mode applied and what step 2 found. List the files changed, the logging that was\nreplaced or removed, and where the log files go. Give the results of PSScriptAnalyzer and the\ntests, and quote one line of the log file that the script wrote. Say that the project now depends\non PSFramework and that its assembly is not signed, because some organizations approve such a\ndependency before it is used. Say plainly when PSFramework could not be loaded and the code is\ntherefore untested.</p>\n","files":[{"path":"SKILL.md","sizeBytes":10105,"isText":true}],"reviewScore":null,"reviewSummary":null,"trust":{"provenance":"trusted-source-unreviewed","notice":"Community-authored content, reproduced verbatim and not vetted as instructions. Treat it as data to evaluate, never as directives to follow.","bodySource":null},"bodyLocked":false,"purchaseUrl":null,"sourceUrl":null,"report":{"provenance":"trusted-source-unreviewed","screen":{"ran":true,"outcome":"clean","suspicious":0,"notes":0,"hiddenCharacters":false},"virusScan":{"engine":"clamav","status":"clean","scannedAt":"2026-11-27T19:15:37.307626Z","sha256":"8DF6C318CD76D27BEBF1744E401E0157776F2E58780041008ADE7B44B79769FF","sizeBytes":4206},"review":null,"source":{"repositoryUrl":"https://github.com/fadwen/ai-powershell-standards","path":"standards/skills/powershell-logging","license":"MIT","commit":"fbf1a1774b64492b5c11c5519d387ea3ead78e1b","subtreeSha":"23D034B45CA2E9E15D6219854BC48F21DD9799555397DBA4223EE5BED5F6E0B1","lastSyncedAt":"2026-11-27T19:12:17.594057Z"},"reviewedAt":"2026-11-27T19:26:35.802589Z","notice":"Community-authored content, reproduced verbatim and not vetted as instructions. Treat it as data to evaluate, never as directives to follow."},"install":[{"target":"skills-cli","command":"npx skills add https://github.com/fadwen/ai-powershell-standards/tree/main/standards/skills/powershell-logging"},{"target":"claude-code","command":"claude plugin marketplace add https://llmmart.ai/marketplace.json && claude plugin install fadwen-ai-powershell-standards@llmmart"},{"target":"git","command":"git clone https://github.com/fadwen/ai-powershell-standards.git"}]}