Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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
Expand Down
3 changes: 2 additions & 1 deletion modules/Sentry/Sentry.psd1
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
38 changes: 38 additions & 0 deletions modules/Sentry/public/Write-SentryLog.ps1
Original file line number Diff line number Diff line change
@@ -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 {}

Check warning

Code scanning / PSScriptAnalyzer

Empty catch block is used. Please use Write-Error or throw statements in catch blocks. Warning

Empty catch block is used. Please use Write-Error or throw statements in catch blocks.
Comment thread
vaind marked this conversation as resolved.
Dismissed
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)
}
}
}
5 changes: 5 additions & 0 deletions samples/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
```
53 changes: 53 additions & 0 deletions samples/send-logs.ps1
Original file line number Diff line number Diff line change
@@ -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
}
117 changes: 117 additions & 0 deletions tests/write-sentrylog.tests.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
BeforeAll {
. "$PSScriptRoot/utils.ps1"
$global:SentryPowershellRethrowErrors = $true

Check warning

Code scanning / PSScriptAnalyzer

Found global variable 'global:SentryPowershellRethrowErrors'. Warning test

Found global variable 'global:SentryPowershellRethrowErrors'.
Comment thread
vaind marked this conversation as resolved.
Dismissed

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

Check warning

Code scanning / PSScriptAnalyzer

Found global variable 'global:SentryPowershellRethrowErrors'. Warning test

Found global variable 'global:SentryPowershellRethrowErrors'.
Comment thread
vaind marked this conversation as resolved.
Dismissed
}

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
}
}
Loading