---
title: Generate Exception Log Events with PowerShell 7 | Nodinite Testing Guide
description: PowerShell 7 script to generate Nodinite JSON Log Events with realistic .NET exception chains for testing and demos. Includes Azure Functions and database error scenarios with base64-encoded payloads.
---

# FAQ — Generate Exception Log Events (PowerShell 7)

This FAQ shows how to generate <span class="nodinite-product-name" title="The node that unites different systems. Or as we call it Nodinite">Nodinite</span> [Log Events][Log Event] with realistic **.NET exception chains** for testing the exception viewer, demo environments, and troubleshooting workflows.

What you'll find on this page:

* **Exception logging script** - Generate .NET exception chains (Azure Functions, database errors)
* **Ready-to-use examples** - Copy, customize, and run immediately with [PowerShell 7][]
* **Realistic exception scenarios** - Multi-level exception chains with stack traces
* **[Pickup Service][] integration** - Files written in the correct format for asynchronous delivery

><i class="fal fa-lightbulb" aria-hidden="true"></i> **Use cases:** Testing <span class="nodinite-product-name" title="The node that unites different systems. Or as we call it Nodinite">Nodinite</span> v7's exception viewer, demo environments, training sessions, exception handling validation, and troubleshooting workflow testing.
>
><i class="fal fa-info-circle" aria-hidden="true"></i> **PowerShell 7 required:** This script uses [PowerShell 7][] features like improved JSON handling, better UTF-8 support, and cross-platform compatibility. [Install PowerShell 7][PowerShell 7] if you haven't already.

**Jump to section:** [Understanding Exception Logging](#understanding-exception-logging) | [Exception Logging Script](#exception-logging-script) | [Common Exception Scenarios](#common-exception-scenarios) | [How v7 Displays Exceptions](#how-nodinite-v7-displays-exceptions)  

## Understanding Exception Logging

<span class="nodinite-product-name" title="The node that unites different systems. Or as we call it Nodinite">Nodinite</span> v7 includes a specialized exception viewer that displays exception chains directly in [Log Views][]. When logging exceptions from .NET applications, Azure Functions, or with [Serilog][], serialize the exception to JSON and put it in the `ExtendedProperties/1.0#Exception` context property, as the script below does. The viewer reads only that property; a copy of the exception in the base64-encoded `Body` shows only as the message body.

**Why exception chains matter:** Exception chains show the complete failure path from root cause to final error. The [Log Views][] exception viewer in <span class="nodinite-product-name" title="The node that unites different systems. Or as we call it Nodinite">Nodinite</span> v7 parses .NET exception structures automatically, making troubleshooting faster and more accurate.

### Exception Data Structure

<span class="nodinite-product-name" title="The node that unites different systems. Or as we call it Nodinite">Nodinite</span> expects .NET exception JSON with these properties:

* **ClassName** - .NET exception type (e.g., `System.Data.SqlClient.SqlException`)
* **Message** - Human-readable error description
* **Source** - Component that threw the exception
* **StackTraceString** - Call stack with file names, methods, line numbers
* **HResult** - Win32/COM error code
* **InnerException** - Nested exception (recursive structure for exception chains)

><i class="fal fa-info-circle" aria-hidden="true"></i> **Serilog integration:** When using [Serilog][] with Nodinite sinks, exceptions are automatically stored in `Context["ExtendedProperties/1.0#Exception"]` when you call `.Error(exception, message)`. This script mimics that behavior for testing. Learn more: [Serilog .NET Exceptions][Serilog]

**Learn more:** [Log Event structure][Log Event] | [JSON Log Event schema][JSON Log Event] | [Pickup Service overview][Pickup Service] | [Install PowerShell 7][PowerShell 7] | [View Exception Details][]  

## Typical Exception Scenario

This example simulates a common .NET application scenario: An Azure Function attempts to process an order, encounters a database connection timeout, which is caused by a DNS resolution failure.

### Exception Chain (Innermost to Outermost)

1. **SocketException** (root cause) - "No such host is known (sql-prod-east.database.windows.net)"
2. **SqlException** (middle) - "Network-related error connecting to SQL Server"
3. **InvalidOperationException** (outermost) - "Failed to process order ORD-12345 after 3 retry attempts"

The <span class="nodinite-product-name" title="The node that unites different systems. Or as we call it Nodinite">Nodinite</span> v7 exception viewer displays all three levels, allowing users to quickly identify that the root cause is a DNS resolution failure, not a database or application logic error.

## Exception Logging Script

### Usage (quick)

Open [PowerShell 7][] terminal and run:

```powershell
pwsh .\Generate-Exception-LogEvent.ps1 -OutputFolder 'C:\temp\logevents'
```

This will create a single JSON file with a realistic exception chain.

><i class="fal fa-terminal" aria-hidden="true"></i> **Verify PowerShell 7:** Run `$PSVersionTable.PSVersion` to confirm you're using PowerShell 7.0 or later. [Download PowerShell 7][PowerShell 7] if needed.

### Script: Generate-Exception-LogEvent.ps1

Save this file next to your documentation or in a demo folder. It uses [PowerShell 7][] features for improved JSON handling and UTF-8 encoding.

```powershell
#!/usr/bin/env pwsh
#Requires -Version 7.0
<#
.SYNOPSIS
Generate a Nodinite LogEvent with a .NET exception chain in the payload.

.DESCRIPTION
This PowerShell 7 script creates a realistic exception Log Event for testing.
The exception simulates: Azure Function → Database Timeout → DNS Resolution Failure
* Requires PowerShell 7.0 or later
* Creates nested exception chain with stack traces
* UTF-8 encoding without BOM

.PARAMETER OutputFolder
Destination folder for the generated JSON file (default: C:\temp\logevents)

.EXAMPLE
pwsh .\Generate-Exception-LogEvent.ps1 -OutputFolder 'C:\temp\logevents'
#>
param(
    [string]$OutputFolder = 'C:\temp\logevents',
    [int]$LogAgentValueId = 42,
    [string]$EndPointName = 'INT201: Process Order Azure Function',
    [string]$MessageType = 'Error.Exception/1.0'
)

# Ensure folder exists
if (-not (Test-Path -Path $OutputFolder)) {
    New-Item -Path $OutputFolder -ItemType Directory -Force | Out-Null
}

# Helper: base64 encode text
function To-Base64([string]$text) {
    return [Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($text))
}

# Generate unique order number: ORD-MMDDHHMM-001
$timestamp = (Get-Date).ToString('MMddHHmm')
$orderNumber = "ORD-$timestamp-001"

# Build exception chain (innermost first)
$dnsException = @{
    ClassName = "System.Net.Sockets.SocketException"
    Message = "No such host is known (sql-prod-east.database.windows.net)"
    Source = "System.Net.Sockets"
    StackTraceString = "   at System.Net.Dns.GetHostEntry(String hostNameOrAddress)`n   at System.Data.SqlClient.SNI.SNITCPHandle.GetFQDN(String hostname)`n   at System.Data.SqlClient.SNI.SNITCPHandle..ctor(String serverName, Int32 port, TimeSpan timeout)"
    HResult = -2147467259
    NativeErrorCode = 11001
    InnerException = $null
}

$sqlException = @{
    ClassName = "System.Data.SqlClient.SqlException"
    Message = "A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: TCP Provider, error: 0 - No such host is known.)"
    Source = "Core .Net SqlClient Data Provider"
    StackTraceString = "   at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, DbConnectionPool pool, String accessToken)`n   at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)`n   at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions)`n   at OrderProcessingFunction.ProcessOrder(String orderId) in C:\\src\\OrderProcessingFunction.cs:line 127"
    HResult = -2146232060
    Number = -1
    State = 0
    Class = 20
    Server = "sql-prod-east.database.windows.net"
    ErrorCode = -2146232060
    InnerException = $dnsException
}

$applicationException = @{
    ClassName = "System.InvalidOperationException"
    Message = "Failed to process order $orderNumber. Database connection could not be established after 3 retry attempts."
    Source = "OrderProcessingFunction"
    StackTraceString = "   at OrderProcessingFunction.ProcessOrder(String orderId) in C:\\src\\OrderProcessingFunction.cs:line 142`n   at OrderProcessingFunction.Run(TimerInfo myTimer, ILogger log) in C:\\src\\OrderProcessingFunction.cs:line 38`n   at Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.ExecuteWithWatchersAsync(IFunctionInstanceEx instance, ParameterHelper parameterHelper, ILogger logger, CancellationToken cancellationToken)"
    HResult = -2146233079
    InnerException = $sqlException
}

# Create the payload with exception details
$payload = @{
    Timestamp = (Get-Date).ToUniversalTime().ToString('o')
    OrderNumber = $orderNumber
    City = "Los Angeles"
    FunctionName = "ProcessOrderFunction"
    Exception = $applicationException
    RetryAttempts = 3
    Environment = "Production"
    Region = "East US"
    OrderRows = @(
        @{ Id = 1; Amount = 42 }
        @{ Id = 2; Amount = 87 }
        @{ Id = 3; Amount = 15 }
    )
}|ConvertTo-Json -Depth 10

# Build the LogEvent object
$logEvent = [ordered]@{
    LogAgentValueId = $LogAgentValueId
    EndPointName = $EndPointName
    EndPointUri = "https://prod-order-func.azurewebsites.net/api/ProcessOrder"
    EndPointDirection = 0
    EndPointTypeId = 3  # HTTP/HTTPS
    OriginalMessageTypeName = $MessageType
    LogDateTime = (Get-Date).ToUniversalTime().ToString('o')
    EventDirection = 0
    ProcessingUser = "AZURE\\OrderProcessingFunction"
    SequenceNo = 1
    EventNumber = 1
    LogText = "Exception: Failed to process order $orderNumber"
    ApplicationInterchangeId = $orderNumber
    LogStatus = 2  # Error status
    ProcessName = "OrderProcessingFunction"
    ProcessingMachineName = "prod-order-func-001"
    ProcessingModuleName = "ProcessOrderFunction"
    ProcessingModuleType = "AzureFunction"
    ProcessingTime = 15487  # 15.5 seconds before timeout
    Body = To-Base64 $payload
    Context = @{
        OrderNumber = $orderNumber
        ExceptionType = "System.InvalidOperationException"
        FailureReason = "Database Connection Timeout"
        RetryAttempts = "3"
        "ExtendedProperties/1.0#Exception" = ($applicationException | ConvertTo-Json -Depth 10)
    }
}

$json = $logEvent|ConvertTo-Json -Depth 15

$fileName = "LogEvent_Exception_{0}_{1}.json" -f $orderNumber, ([guid]::NewGuid())
$filePath = Join-Path -Path $OutputFolder -ChildPath $fileName

# Write UTF8 no BOM
[System.IO.File]::WriteAllText($filePath, $json, [System.Text.Encoding]::UTF8)

Write-Host "Exception LogEvent created: $filePath" -ForegroundColor Cyan
Write-Host "Exception chain: InvalidOperationException -> SqlException -> SocketException" -ForegroundColor Yellow
Write-Host "Order Number: $orderNumber" -ForegroundColor Green
```

### What This Script Does

* **PowerShell 7 features** - Uses improved `ConvertTo-Json -Depth` and UTF-8 encoding without BOM
* **Realistic exception chain** - Three-level exception hierarchy (Application → Database → Network)
* **Complete stack traces** - File names, method names, and line numbers for each exception
* **Base64 encoding** - Payload JSON is automatically base64-encoded in the `Body` field
* **Context properties** - Includes `OrderNumber`, `ExceptionType`, `FailureReason` for searchability
* **Serilog format** - Stores exception in `Context["ExtendedProperties/1.0#Exception"]` like Serilog sinks

**Next steps:** Place generated file in the [Pickup Service][] input folder, or post it directly to the [Log API][] as described in [Log using REST][]. Then open the Log Event in [Log Views][] to see the v7 exception viewer in action.

><i class="fal fa-info-circle" aria-hidden="true"></i> **Compatibility note:** This script requires [PowerShell 7][] or later. The `#Requires -Version 7.0` directive ensures the script won't run on older PowerShell versions.

## Common Exception Scenarios

The script can be customized to generate different exception types for testing:

### Azure Function Failures

* **Timeout errors** - Change `ProcessingTime` to > 300000 (5 minutes)
* **Binding errors** - Add `BindingException` in exception chain
* **Connection issues** - Use `WebException` or `HttpRequestException`

### Database Operations

* **Connection timeouts** - Use `SqlException` with `Number = -1` (shown in script)
* **Deadlocks** - Use `SqlException` with `Number = 1205`
* **Constraint violations** - Use `SqlException` with `Number = 2627` (primary key violation)

### API Integrations

* **HTTP timeouts** - Use `TaskCanceledException` or `TimeoutException`
* **Authentication failures** - Use `UnauthorizedAccessException` or `SecurityException`
* **Rate limiting** - Use `HttpRequestException` with `StatusCode = 429`

### Message Processing

* **Deserialization errors** - Use `JsonException` or `XmlException`
* **Validation failures** - Use `ArgumentException` or `ValidationException`
* **Poison messages** - Use `MessageQueueException` with retry count context

### File Operations

* **Access denied** - Use `UnauthorizedAccessException`
* **File not found** - Use `FileNotFoundException`
* **Disk space issues** - Use `IOException` with HResult -2147024784

><i class="fal fa-lightbulb" aria-hidden="true"></i> **Tip:** Always include the full exception chain with `InnerException` properties. <span class="nodinite-product-name" title="The node that unites different systems. Or as we call it Nodinite">Nodinite</span> v7's exception viewer makes it easy to diagnose root causes by navigating through the exception hierarchy.

## How Nodinite v7 Displays Exceptions

When you open the generated [Log Event][] in <span class="nodinite-product-name" title="The node that unites different systems. Or as we call it Nodinite">Nodinite</span> v7 [Log Views][], click **Show Details** and open **Context Values**. The exception viewer displays:

* **Exception chain visualization** - Each exception level is clearly separated
* **Stack trace formatting** - Line breaks and indentation preserved for readability
* **Inner exception navigation** - Drill down from outer to inner exceptions
* **Exception properties** - Message, Class Name, Source, and Stack Trace first; HResult, error codes, and the rest under **Other fields**
* **Contextual information** - Order ID, retry attempts, and environment details in [Context properties][Context Options]
* **Formula-based extraction** - Use `JsonPath('..Message', Context('ExtendedProperties/1.0#Exception'))` to extract specific exception data for [Search Fields][]

![The exception viewer in Context Values, with System.InvalidOperationException open, its Inner Exception System.Data.SqlClient.SqlException open, Class Name, Source, Stack Trace, Other fields, and View Raw Exception (7.12)][1]  
*The exception viewer in an event's **Context Values**: the outer exception and its inner SqlException opened.*  

><i class="fal fa-link" aria-hidden="true"></i> **Learn more:** See [View Exception Details][] for a complete guide to using the exception viewer in [Log Views][].

**Try it yourself:** Generate an exception [Log Event][] using the script above, place it in the [Pickup Service][] folder, then open it in [Log Views][] to see the v7 exception viewer in action.

## Notes & Tips

* **PowerShell 7 required:** This script uses [PowerShell 7][] features. Run `pwsh` command (not `powershell`) to use PowerShell 7. Verify version with `$PSVersionTable.PSVersion`.
* **Direct API posting:** To send events directly to the [Log API][] rather than through the [Pickup Service][], post the JSON to `https://{host}:{port}/LogAPI/api/LogEvent`. The Log API has no API key: it is either open, or it requires an OAuth 2.0 bearer token when **Enable Authentication** is checked in the Portal. See [Log using REST][] for the base URL and samples.
* **Exception structure:** The exception payload structure shown mirrors .NET's `Exception.ToString()` serialization, which <span class="nodinite-product-name" title="The node that unites different systems. Or as we call it Nodinite">Nodinite</span> v7 recognizes and formats automatically.
* **Cross-platform:** [PowerShell 7][] works on Windows, Linux, and macOS. This script runs on any platform where PowerShell 7 is installed.
* **Serilog users:** See [Serilog .NET Exceptions][Serilog] for how exceptions are automatically captured and formatted when using `.Error(exception, message)` with Nodinite sinks.

## <i class="fal fa-hand-point-right" aria-hidden="true"></i> Next Steps

<i class="fal fa-code" aria-hidden="true"></i> [Hello World C# Sample][Hello World Sample] - Step-by-step guide to logging with .NET and NuGet  
<i class="fal fa-book" aria-hidden="true"></i> [Serilog Overview][Serilog] - Production logging with Serilog sinks and automatic exception capture  
<i class="fal fa-eye" aria-hidden="true"></i> [View Exception Details][] - Learn how to use the exception viewer in Log Views  

## <i class="fal fa-link-horizontal" aria-hidden="true"></i> Related Topics

<i class="fal fa-file-code" aria-hidden="true"></i> [JSON Log Event][] - Log Event JSON schema reference  
<i class="fal fa-cog" aria-hidden="true"></i> [Context Options][] - Add custom context properties  
<i class="fal fa-traffic-light" aria-hidden="true"></i> [Log Status Codes][] - Error, warning, and success codes  
<i class="fal fa-search" aria-hidden="true"></i> [Log Views][] - Query and filter logged events  
<i class="fal fa-chart-line" aria-hidden="true"></i> [Search Fields][] - Extract business data from exceptions using [Formula][]  
<i class="fal fa-flask" aria-hidden="true"></i> [Generate Batch Log Events][Generate Log Events] - Create hundreds of order events for testing  
<i class="fal fa-book" aria-hidden="true"></i> [Log Event][] - Understand the Log Event structure  
<i class="fal fa-inbox" aria-hidden="true"></i> [Pickup Service][] - Configure asynchronous log event delivery  
<i class="fal fa-cloud" aria-hidden="true"></i> [Log API][] - Send events directly via HTTP POST  
<i class="fal fa-code" aria-hidden="true"></i> [Log using REST][] - Base URL, OAuth 2.0, and code samples  

[1]:https://docs.nodinite.com/media/Documentation%20Pictures/IM/WebClient/Log/ExceptionDetails.png

[Context Options]:https://docs.nodinite.com/core-services/log-event/features/context-options/
[Formula]:https://docs.nodinite.com/administration/log-management/search-fields/features/search-field-expressions/formula/overview/
[Generate Log Events]:https://docs.nodinite.com/core-services/log-api/troubleshooting/faq-generate-log-events/
[Hello World Sample]:https://docs.nodinite.com/core-services/log-api/troubleshooting/faq-hello-world-net-sample/
[JSON Log Event]:https://docs.nodinite.com/core-services/log-event/features/json-log-event/
[Log API]:https://docs.nodinite.com/core-services/log-api/overview/
[Log Event]:https://docs.nodinite.com/core-services/log-event/overview/
[Log Status Codes]:https://docs.nodinite.com/administration/log-management/log-agents/features/what-is-a-log-status-code/
[Log using REST]:https://docs.nodinite.com/core-services/log-api/features/log-using-rest/
[Log Views]:https://docs.nodinite.com/administration/log-management/log-views/features/what-is-a-log-view/
[Pickup Service]:https://docs.nodinite.com/logging-and-monitoring/pickup-logevents-service/overview/
[PowerShell 7]:https://learn.microsoft.com/en-us/powershell/scripting/install/install-powershell-on-windows
[Search Fields]:https://docs.nodinite.com/administration/log-management/search-fields/features/what-is-a-search-field/
[Serilog]:https://docs.nodinite.com/logging-and-monitoring/serilog/overview/
[View Exception Details]:https://docs.nodinite.com/getting-started/log/view-exception-details/