- 10 minutes to read

FAQ — Generate Exception Log Events (PowerShell 7)

This FAQ shows how to generate Nodinite Log Events 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

Use cases: Testing Nodinite v7's exception viewer, demo environments, training sessions, exception handling validation, and troubleshooting workflow testing.

PowerShell 7 required: This script uses PowerShell 7 features like improved JSON handling, better UTF-8 support, and cross-platform compatibility. Install PowerShell 7 if you haven't already.

Jump to section: Understanding Exception Logging | Exception Logging Script | Common Exception Scenarios | How v7 Displays Exceptions

Understanding Exception Logging

Nodinite 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 include it in the Body as a base64-encoded payload.

Why exception chains matter: Exception chains show the complete failure path from root cause to final error. The Log Views exception viewer in Nodinite v7 parses .NET exception structures automatically, making troubleshooting faster and more accurate.

Data structure: Nodinite 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)

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

Learn more: Log Event structure | JSON Log Event schema | Pickup Service overview | Install 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 Nodinite 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:

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

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

Verify PowerShell 7: Run $PSVersionTable.PSVersion to confirm you're using PowerShell 7.0 or later. Download 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.

#!/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 use Log API to send directly via HTTP POST. Then open the Log Event in Log Views to see the v7 exception viewer in action.

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

Tip: Always include the full exception chain with InnerException properties. Nodinite 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 Nodinite v7 Log Views, 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 - HResult, error codes, Source, and other .NET exception metadata
  • Contextual information - Order ID, retry attempts, and environment details in Context properties
  • Formula-based extraction - Use JsonPath('..Message', Context('ExtendedProperties/1.0#Exception')) to extract specific exception data for Search Fields

Exception Details in Log View
Screenshot of the exception details view in a Nodinite v7 Log View showing exception chain, stack trace, and properties.

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: If you want to send events directly to Log API rather than to Pickup Service, wrap the JSON with an HTTP POST using your API key and the Log API endpoint.
  • Exception structure: The exception payload structure shown mirrors .NET's Exception.ToString() serialization, which Nodinite 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 for how exceptions are automatically captured and formatted when using .Error(exception, message) with Nodinite sinks.

Next Step

Hello World C# Sample - Step-by-step guide to logging with .NET and NuGet
Serilog Overview - Production logging with Serilog sinks and automatic exception capture
View Exception Details - Learn how to use the exception viewer in Log Views

JSON Log Event - Log Event JSON schema reference
Context Options - Add custom context properties
Log Status Codes - Error, warning, and success codes
Log Views - Query and filter logged events
Search Fields - Extract business data from exceptions using Formula
Generate Batch Log Events - Create hundreds of order events for testing
Log Event - Understand the Log Event structure
Pickup Service - Configure asynchronous log event delivery
Log API - Send events directly via HTTP POST