diff --git a/CHANGELOG.md b/CHANGELOG.md index 315ef10..c183972 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,11 @@ # Changelog +## Unreleased + +### Features + +- Add `Write-SentryLog` cmdlet, a native PowerShell API for sending structured logs (Sentry Logs) ([#131](https://github.com/getsentry/sentry-powershell/pull/131)) + ## 0.4.0 ### Fixes diff --git a/modules/Sentry/Sentry.psd1 b/modules/Sentry/Sentry.psd1 index 2e9abe4..66b0a46 100644 --- a/modules/Sentry/Sentry.psd1 +++ b/modules/Sentry/Sentry.psd1 @@ -38,7 +38,8 @@ 'Out-Sentry', 'Start-Sentry', 'Start-SentryTransaction', - 'Stop-Sentry' + 'Stop-Sentry', + 'Write-SentryLog' ) # 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. diff --git a/modules/Sentry/public/Write-SentryLog.ps1 b/modules/Sentry/public/Write-SentryLog.ps1 new file mode 100644 index 0000000..bc0943e --- /dev/null +++ b/modules/Sentry/public/Write-SentryLog.ps1 @@ -0,0 +1,38 @@ +function Write-SentryLog { + [CmdletBinding()] + param( + [Parameter(Mandatory, Position = 0, ValueFromPipeline = $true)] + [AllowEmptyString()] + [string] $Message, + + [Sentry.SentryLogLevel] $Level = [Sentry.SentryLogLevel]::Info, + + [object[]] $Parameters, + + [hashtable] $Attributes + ) + + process { + if (-not [Sentry.SentrySdk]::IsEnabled) { + try { + Write-Debug 'Sentry is not started: Write-SentryLog invocation ignored.' + } catch {} + return + } + + $values = if ($null -eq $Parameters) { [object[]]@() } else { [object[]]$Parameters } + $methodName = "Log$Level" + + if ($null -ne $Attributes -and $Attributes.Count -gt 0) { + $configureLog = [System.Action[Sentry.SentryLog]] { + param([Sentry.SentryLog]$log) + foreach ($key in $Attributes.Keys) { + $log.SetAttribute([string]$key, $Attributes[$key]) + } + } + [Sentry.SentrySdk]::Logger.$methodName($configureLog, $Message, $values) + } else { + [Sentry.SentrySdk]::Logger.$methodName($Message, $values) + } + } +} diff --git a/samples/README.md b/samples/README.md index 1e76dc3..1ac0e9f 100644 --- a/samples/README.md +++ b/samples/README.md @@ -9,4 +9,9 @@ pwsh ./dependencies/download.ps1 Then you can run the sample, for example: ```sh pwsh ./samples/locate-city.ps1 Toronto +``` + +Or send structured logs to Sentry (see the [Sentry Logs docs](https://docs.sentry.io/platforms/dotnet/logs/)): +```sh +pwsh ./samples/send-logs.ps1 ``` \ No newline at end of file diff --git a/samples/send-logs.ps1 b/samples/send-logs.ps1 new file mode 100644 index 0000000..9e5551a --- /dev/null +++ b/samples/send-logs.ps1 @@ -0,0 +1,53 @@ +<# +.SYNOPSIS + Demonstrates sending structured logs to Sentry from PowerShell. +.DESCRIPTION + Shows how to enable Sentry Logs (https://docs.sentry.io/platforms/dotnet/logs/) + in the PowerShell module and emit log messages at various severity levels, + including templated messages with structured parameters and custom attributes. +.EXAMPLE + PS> ./send-logs.ps1 +.LINK + https://docs.sentry.io/platforms/dotnet/logs/ +#> + +# Import the Sentry module. In your code, you would just use `Import-Module Sentry`. +Import-Module $PSScriptRoot/../modules/Sentry/Sentry.psd1 + +# Start the Sentry client. Set Experimental.EnableLogs = $true to opt in to Logs. +Start-Sentry { + $_.Dsn = 'https://997874440feaba4ecc65c1e25df7912b@o447951.ingest.us.sentry.io/4508073336176640' + $_.Debug = $true + $_.Experimental.EnableLogs = $true +} + +try { + # Each call sends one log record at the given severity. Level defaults to Info. + Write-SentryLog -Level Trace 'Trace from PowerShell' + Write-SentryLog -Level Debug 'Debug from PowerShell' + Write-SentryLog 'Info from PowerShell' + Write-SentryLog -Level Warning 'Warning from PowerShell' + Write-SentryLog -Level Error 'Error from PowerShell' + Write-SentryLog -Level Fatal 'Fatal from PowerShell' + + # Templated messages use positional placeholders ({0}, {1}, ...). Each value + # passed via -Parameters is captured as a structured attribute on the log + # record so you can search/filter on it in Sentry. + $user = $env:USER ?? $env:USERNAME + $hostName = [System.Net.Dns]::GetHostName() + $psVersion = $PSVersionTable.PSVersion.ToString() + Write-SentryLog -Level Info ` + -Message 'User {0} ran send-logs.ps1 on {1} (PowerShell {2})' ` + -Parameters $user, $hostName, $psVersion + + # -Attributes attaches arbitrary key/value pairs to the log record. + Write-SentryLog -Level Warning ` + -Message 'Disk usage on {0} is at {1}%' ` + -Parameters $hostName, 92 ` + -Attributes @{ region = 'us-east-1'; mount = '/var' } + + # Logs are buffered and flushed in the background. Give them a moment to send. + [Sentry.SentrySdk]::Flush([TimeSpan]::FromSeconds(5)) | Out-Null +} finally { + Stop-Sentry +} diff --git a/tests/write-sentrylog.tests.ps1 b/tests/write-sentrylog.tests.ps1 new file mode 100644 index 0000000..29ce475 --- /dev/null +++ b/tests/write-sentrylog.tests.ps1 @@ -0,0 +1,117 @@ +BeforeAll { + . "$PSScriptRoot/utils.ps1" + $global:SentryPowershellRethrowErrors = $true + + function StartSentryForLogTests { + Start-Sentry { + $_.Dsn = 'https://key@127.0.0.1/1' + $_.Experimental.EnableLogs = $true + $_.Experimental.SetBeforeSendLog([System.Func[Sentry.SentryLog, Sentry.SentryLog]] { + param([Sentry.SentryLog]$log) + $script:logs.Add($log) + return $null + }) + $_.Transport = [RecordingTransport]::new() + } + } + + # Logs go through a background batch processor; flush before asserting. + function FlushLogs { [Sentry.SentrySdk]::Flush([TimeSpan]::FromSeconds(5)) | Out-Null } +} + +AfterAll { + $global:SentryPowershellRethrowErrors = $false +} + +Describe 'Write-SentryLog' { + BeforeEach { + $script:logs = [System.Collections.Generic.List[Sentry.SentryLog]]::new() + StartSentryForLogTests + } + + AfterEach { + Stop-Sentry + } + + It 'sends an Info log by default' { + Write-SentryLog 'hello' + FlushLogs + + $script:logs.Count | Should -Be 1 + $script:logs[0].Level | Should -Be ([Sentry.SentryLogLevel]::Info) + $script:logs[0].Message | Should -Be 'hello' + $script:logs[0].Template | Should -Be 'hello' + } + + It 'accepts the message from the pipeline' { + 'piped message' | Write-SentryLog -Level Warning + FlushLogs + + $script:logs.Count | Should -Be 1 + $script:logs[0].Level | Should -Be ([Sentry.SentryLogLevel]::Warning) + $script:logs[0].Message | Should -Be 'piped message' + } + + It 'sends a log at each supported level' { + Write-SentryLog -Level Trace 'trace' + Write-SentryLog -Level Debug 'debug' + Write-SentryLog -Level Info 'info' + Write-SentryLog -Level Warning 'warning' + Write-SentryLog -Level Error 'error' + Write-SentryLog -Level Fatal 'fatal' + FlushLogs + + $script:logs.Count | Should -Be 6 + $script:logs[0].Level | Should -Be ([Sentry.SentryLogLevel]::Trace) + $script:logs[1].Level | Should -Be ([Sentry.SentryLogLevel]::Debug) + $script:logs[2].Level | Should -Be ([Sentry.SentryLogLevel]::Info) + $script:logs[3].Level | Should -Be ([Sentry.SentryLogLevel]::Warning) + $script:logs[4].Level | Should -Be ([Sentry.SentryLogLevel]::Error) + $script:logs[5].Level | Should -Be ([Sentry.SentryLogLevel]::Fatal) + } + + It 'substitutes parameters into the template' { + Write-SentryLog -Level Info -Message 'User {0} ran {1}' -Parameters 'alice', 'send-logs.ps1' + FlushLogs + + $script:logs.Count | Should -Be 1 + $script:logs[0].Template | Should -Be 'User {0} ran {1}' + $script:logs[0].Message | Should -Be 'User alice ran send-logs.ps1' + $script:logs[0].Parameters.Length | Should -Be 2 + } + + It 'attaches structured attributes' { + Write-SentryLog -Level Error -Message 'oops' -Attributes @{ user = 'bob'; retries = 3 } + FlushLogs + + $script:logs.Count | Should -Be 1 + $userValue = $null + $script:logs[0].TryGetAttribute('user', [ref] $userValue) | Should -Be $true + $userValue | Should -Be 'bob' + $retriesValue = $null + $script:logs[0].TryGetAttribute('retries', [ref] $retriesValue) | Should -Be $true + $retriesValue | Should -Be 3 + } + + It 'combines parameters and attributes in a single call' { + Write-SentryLog -Level Warning ` + -Message 'host {0} is at {1}%' ` + -Parameters 'web-1', 92 ` + -Attributes @{ region = 'us-east-1' } + FlushLogs + + $script:logs.Count | Should -Be 1 + $script:logs[0].Message | Should -Be 'host web-1 is at 92%' + $script:logs[0].Parameters.Length | Should -Be 2 + $regionValue = $null + $script:logs[0].TryGetAttribute('region', [ref] $regionValue) | Should -Be $true + $regionValue | Should -Be 'us-east-1' + } +} + +Describe 'Write-SentryLog when Sentry is not started' { + It 'is a no-op and does not throw' { + [Sentry.SentrySdk]::IsEnabled | Should -Be $false + { Write-SentryLog -Level Info 'should be ignored' } | Should -Not -Throw + } +}