-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlogging.ps1
More file actions
840 lines (696 loc) · 30.2 KB
/
Copy pathlogging.ps1
File metadata and controls
840 lines (696 loc) · 30.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
<##
.SYNOPSIS
Generic logging module for myTech.Today PowerShell scripts.
.DESCRIPTION
Provides centralized logging functionality for all myTech.Today scripts.
Features:
- Centralized logging to platform-appropriate directories
- Windows: %USERPROFILE%\myTech.Today\logs\
- macOS: ~/Library/Logs/myTech.Today/
- Linux: ~/.local/share/myTech.Today/logs/
- Monthly log archiving (current: scriptname.jsonl, archived: scriptname.YYYY-MM.jsonl)
- Cyclical logging with 10MB size limit
- JSONL (JSON Lines) format for structured logging
- ASCII-only indicators (no emoji)
- Console output with color coding
- Windows Event Log integration under 'myTech.Today' root folder (Windows only)
- Enhanced Event Viewer messages with structured Problem/Context/Solution format
- Cross-platform support (Windows, macOS, Linux)
- Can be imported from GitHub URL
.NOTES
Name: logging.ps1
Author: myTech.Today
Version: 3.0.0
DateCreated: 2025-11-09
LastModified: 2026-02-01
Requires: PowerShell 5.1 or later (Windows), PowerShell 7.0+ (macOS/Linux)
Usage from GitHub:
$loggingUrl = 'https://raw.githubusercontent.com/mytech-today-now/scripts/refs/heads/main/logging.ps1'
Invoke-Expression (Invoke-WebRequest -Uri $loggingUrl -UseBasicParsing).Content
Usage from local path:
. "$PSScriptRoot\..\scripts\logging.ps1"
.EXAMPLE
# Initialize logging
Initialize-Log -ScriptName "MyScript" -ScriptVersion "1.0.0"
# Write log entries
Write-Log "Script started" -Level INFO
Write-Log "Operation completed successfully" -Level SUCCESS
Write-Log "Warning: Configuration file not found" -Level WARNING
Write-Log "Error: Failed to connect to server" -Level ERROR
# Get current log path
$logPath = Get-LogPath
Write-Host "Logging to: $logPath"
.LINK
https://github.com/mytech-today-now/PowerShellScripts
#>
#Requires -Version 5.1
# Script-scoped variables
$script:LogPath = $null
$script:CentralLogPath = "$env:USERPROFILE\myTech.Today\logs\"
$script:MaxLogSizeMB = 10
$script:ScriptName = $null
$script:ScriptVersion = $null
$script:SessionId = $null # GUID for tracking log entries in same session
# Windows Event Log integration (best-effort; failures do not block file logging)
$script:EnableEventLog = $true
$script:EventLogName = 'myTech.Today' # Root log in Applications and Services Logs
$script:EventSource = $null # Will be set to script name (source within the log)
function ConvertTo-JsonLogEntry {
<#
.SYNOPSIS
Converts log entry parameters to a hashtable for JSONL serialization.
.DESCRIPTION
Creates a structured hashtable containing all log entry fields including
timestamp, level, message, script metadata, system metadata, and optional
context/solution/component/error information.
.PARAMETER Message
The log message text.
.PARAMETER Level
The log level (DEBUG, INFO, SUCCESS, WARNING, ERROR).
.PARAMETER Context
Optional context information.
.PARAMETER Solution
Optional solution or recommended action.
.PARAMETER Component
Optional component name.
.PARAMETER ErrorRecord
Optional ErrorRecord object for error logging.
.OUTPUTS
System.Collections.Hashtable
A hashtable ready for JSON serialization.
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[string]$Message,
[Parameter(Mandatory = $true)]
[string]$Level,
[Parameter(Mandatory = $false)]
[string]$Context,
[Parameter(Mandatory = $false)]
[string]$Solution,
[Parameter(Mandatory = $false)]
[string]$Component,
[Parameter(Mandatory = $false)]
[System.Management.Automation.ErrorRecord]$ErrorRecord
)
try {
# Detect platform
$platform = if ($IsWindows -or $PSVersionTable.PSVersion.Major -le 5) {
"Windows"
} elseif ($IsMacOS) {
"macOS"
} elseif ($IsLinux) {
"Linux"
} else {
"Unknown"
}
# Get computer name (cross-platform)
$computerName = if ($env:COMPUTERNAME) {
$env:COMPUTERNAME
} elseif ($env:HOSTNAME) {
$env:HOSTNAME
} else {
try { hostname } catch { "Unknown" }
}
# Get username (cross-platform)
$userName = if ($env:USERNAME) {
$env:USERNAME
} elseif ($env:USER) {
$env:USER
} else {
"Unknown"
}
# Build base log entry
$logEntry = @{
timestamp = (Get-Date).ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ss.fffffffZ')
level = $Level
message = $Message
script = @{
name = $script:ScriptName
version = $script:ScriptVersion
}
system = @{
computer = $computerName
user = $userName
platform = $platform
psVersion = $PSVersionTable.PSVersion.ToString()
}
metadata = @{
processId = $PID
threadId = [System.Threading.Thread]::CurrentThread.ManagedThreadId
sessionId = $script:SessionId
logPath = $script:LogPath
}
}
# Add optional fields
if ($Context) { $logEntry['context'] = $Context }
if ($Solution) { $logEntry['solution'] = $Solution }
if ($Component) { $logEntry['component'] = $Component }
# Add error details if present
if ($ErrorRecord) {
$logEntry['error'] = @{
message = $ErrorRecord.Exception.Message
type = $ErrorRecord.Exception.GetType().FullName
stackTrace = $ErrorRecord.ScriptStackTrace
}
if ($ErrorRecord.Exception.InnerException) {
$logEntry['error']['innerException'] = $ErrorRecord.Exception.InnerException.Message
}
if ($ErrorRecord.Exception.HResult) {
$logEntry['error']['hResult'] = $ErrorRecord.Exception.HResult
}
}
return $logEntry
}
catch {
# Fallback to minimal valid entry if conversion fails
return @{
timestamp = (Get-Date).ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ss.fffffffZ')
level = $Level
message = $Message
script = @{ name = "Unknown"; version = "0.0.0" }
system = @{ computer = "Unknown"; user = "Unknown"; platform = "Unknown"; psVersion = "Unknown" }
metadata = @{ processId = $PID; threadId = 0; sessionId = "unknown"; logPath = "" }
}
}
}
function Write-JsonLogEntry {
<#
.SYNOPSIS
Writes a hashtable as a JSONL entry to the log file.
.DESCRIPTION
Converts a hashtable to JSON and appends it as a single line to the log file.
Implements fallback handling if JSON serialization fails.
.PARAMETER LogEntry
The hashtable to serialize and write.
.OUTPUTS
None
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[hashtable]$LogEntry
)
try {
# Convert to JSON (compressed, single line)
$jsonLine = $LogEntry | ConvertTo-Json -Depth 10 -Compress -ErrorAction Stop
# Append to log file
Add-Content -Path $script:LogPath -Value $jsonLine -ErrorAction SilentlyContinue
}
catch {
# Fallback: write a minimal JSON entry
try {
$fallbackEntry = @{
timestamp = (Get-Date).ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ss.fffffffZ')
level = "ERROR"
message = "Failed to serialize log entry: $($_.Exception.Message)"
script = @{ name = $script:ScriptName; version = $script:ScriptVersion }
}
$fallbackJson = $fallbackEntry | ConvertTo-Json -Compress -ErrorAction SilentlyContinue
Add-Content -Path $script:LogPath -Value $fallbackJson -ErrorAction SilentlyContinue
}
catch {
# Complete failure - silently continue (logging must never break scripts)
}
}
}
function Initialize-MyTechTodayEventLog {
<#
.SYNOPSIS
Initializes Windows Event Log integration for the current script.
.DESCRIPTION
Creates (if necessary) the 'myTech.Today' Event Log in Applications and Services Logs
and registers the script as an event source within that log.
Event Viewer Structure:
Applications and Services Logs
└─ myTech.Today (event log)
├─ Bookmarks-Manager (event source)
├─ AppInstaller (event source)
└─ ... (other scripts as sources)
If creation fails (for example, due to insufficient privileges), file
logging continues to work and event logging is silently disabled.
.PARAMETER ScriptName
The logical name of the script (used as the event source name).
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[string]$ScriptName
)
try {
# Set the event source to the script name
$script:EventSource = $ScriptName
# Check if the source already exists
if (-not [System.Diagnostics.EventLog]::SourceExists($script:EventSource)) {
# Create the event source under the 'myTech.Today' log
# This will automatically create the log if it doesn't exist
New-EventLog -LogName $script:EventLogName -Source $script:EventSource -ErrorAction Stop
# Ensure the log has a File path configured in the registry
# This is required for events to be written to the log
$logRegPath = "HKLM:\SYSTEM\CurrentControlSet\Services\EventLog\$($script:EventLogName)"
$fileProperty = Get-ItemProperty -Path $logRegPath -Name "File" -ErrorAction SilentlyContinue
if (-not $fileProperty -or [string]::IsNullOrWhiteSpace($fileProperty.File)) {
# Set the file path for the log
$logFileName = $script:EventLogName -replace '\.', '' # Remove dots for filename
Set-ItemProperty -Path $logRegPath -Name "File" -Value "%SystemRoot%\System32\Winevt\Logs\$logFileName.evtx" -ErrorAction Stop
# Restart the Event Log service to apply the changes
Restart-Service -Name EventLog -Force -ErrorAction Stop
}
# Configure the event source to use PowerShell's message file
# This prevents "The description for Event ID cannot be found" warnings in Event Viewer
$sourceRegPath = "$logRegPath\$script:EventSource"
$messageFile = "%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe"
Set-ItemProperty -Path $sourceRegPath -Name "EventMessageFile" -Value $messageFile -ErrorAction SilentlyContinue
Set-ItemProperty -Path $sourceRegPath -Name "CategoryMessageFile" -Value $messageFile -ErrorAction SilentlyContinue
Set-ItemProperty -Path $sourceRegPath -Name "ParameterMessageFile" -Value $messageFile -ErrorAction SilentlyContinue
}
else {
# Verify the source is registered to the correct log
$existingLog = [System.Diagnostics.EventLog]::LogNameFromSourceName($script:EventSource, '.')
if ($existingLog -ne $script:EventLogName) {
# Source exists but is registered to a different log - disable event logging
Write-Warning "Event source '$script:EventSource' is already registered to log '$existingLog'. Event logging disabled."
$script:EnableEventLog = $false
}
else {
# Source exists and is registered to the correct log
# Update the message files to prevent "description cannot be found" warnings
$sourceRegPath = "$logRegPath\$script:EventSource"
$messageFile = "%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe"
Set-ItemProperty -Path $sourceRegPath -Name "EventMessageFile" -Value $messageFile -ErrorAction SilentlyContinue
Set-ItemProperty -Path $sourceRegPath -Name "CategoryMessageFile" -Value $messageFile -ErrorAction SilentlyContinue
Set-ItemProperty -Path $sourceRegPath -Name "ParameterMessageFile" -Value $messageFile -ErrorAction SilentlyContinue
}
}
}
catch {
# If event log registration fails (e.g. non-admin), disable event logging
$script:EnableEventLog = $false
}
}
function Initialize-Log {
<#
.SYNOPSIS
Initializes logging for a script.
.DESCRIPTION
Creates the log directory if needed, sets up monthly log rotation,
and creates a log file with markdown header.
.PARAMETER ScriptName
Name of the script (used in log file name).
.PARAMETER ScriptVersion
Version of the script (included in log header).
.PARAMETER LogPath
Optional custom log path. If not specified, uses %USERPROFILE%\myTech.Today\logs\
.PARAMETER MaxLogSizeMB
Maximum log file size in MB before rotation. Default is 10MB.
.OUTPUTS
System.String
Returns the path to the log file.
.EXAMPLE
Initialize-Log -ScriptName "MyScript" -ScriptVersion "1.0.0"
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[string]$ScriptName,
[Parameter(Mandatory = $false)]
[string]$ScriptVersion = "1.0.0",
[Parameter(Mandatory = $false)]
[string]$LogPath = $null,
[Parameter(Mandatory = $false)]
[ValidateRange(1, 100)]
[int]$MaxLogSizeMB = 10
)
try {
# Set script-scoped variables
$script:ScriptName = $ScriptName
$script:ScriptVersion = $ScriptVersion
$script:MaxLogSizeMB = $MaxLogSizeMB
# Generate session ID (GUID for this script execution)
if (-not $script:SessionId) {
$script:SessionId = [guid]::NewGuid().ToString()
}
# Initialize Windows Event Log integration (best-effort)
Initialize-MyTechTodayEventLog -ScriptName $ScriptName
# Determine log directory (cross-platform)
if ($LogPath) {
$script:CentralLogPath = Split-Path $LogPath -Parent
} else {
# Use platform-appropriate log directory
$platform = if ($IsWindows -or $PSVersionTable.PSVersion.Major -le 5) {
"Windows"
} elseif ($IsMacOS) {
"macOS"
} elseif ($IsLinux) {
"Linux"
} else {
"Windows" # Default to Windows
}
$script:CentralLogPath = switch ($platform) {
"Windows" { Join-Path $env:USERPROFILE "myTech.Today\logs" }
"macOS" { Join-Path $HOME "Library/Logs/myTech.Today" }
"Linux" { Join-Path $HOME ".local/share/myTech.Today/logs" }
default { Join-Path $env:USERPROFILE "myTech.Today\logs" }
}
}
# Create log directory if it doesn't exist
if (-not (Test-Path $script:CentralLogPath)) {
New-Item -ItemType Directory -Path $script:CentralLogPath -Force | Out-Null
}
# Calculate log file name (format: scriptname.jsonl, lowercase)
$logFileName = "$($ScriptName.ToLower()).jsonl"
$script:LogPath = Join-Path $script:CentralLogPath $logFileName
# Check if log file exists and needs monthly archiving
if (Test-Path $script:LogPath) {
$logFile = Get-Item $script:LogPath
$logLastWriteMonth = $logFile.LastWriteTime.ToString('yyyy-MM')
$currentMonth = Get-Date -Format 'yyyy-MM'
# If the log file is from a previous month, archive it
if ($logLastWriteMonth -ne $currentMonth) {
$archiveName = "$($ScriptName.ToLower()).$logLastWriteMonth.jsonl"
$archivePath = Join-Path $script:CentralLogPath $archiveName
# Only archive if the archive doesn't already exist
if (-not (Test-Path $archivePath)) {
Move-Item -Path $script:LogPath -Destination $archivePath -Force -ErrorAction SilentlyContinue
Write-Host "[INFO] Previous month's log archived: $archivePath" -ForegroundColor Cyan
}
else {
# Archive already exists, just delete the old log
Remove-Item -Path $script:LogPath -Force -ErrorAction SilentlyContinue
}
}
else {
# Same month - check if log file needs size-based rotation
$sizeMB = $logFile.Length / 1MB
if ($sizeMB -gt $script:MaxLogSizeMB) {
# Archive the log with timestamp
$timestamp = Get-Date -Format 'yyyyMMdd_HHmmss'
$archiveName = "$($ScriptName.ToLower())_archived_$timestamp.jsonl"
$archivePath = Join-Path $script:CentralLogPath $archiveName
Move-Item -Path $script:LogPath -Destination $archivePath -Force -ErrorAction SilentlyContinue
Write-Host "[INFO] Log file size limit exceeded. Archived to: $archivePath" -ForegroundColor Cyan
}
}
}
# Create empty JSONL log file if it doesn't exist
if (-not (Test-Path $script:LogPath)) {
# JSONL files don't need headers - just create empty file
New-Item -Path $script:LogPath -ItemType File -Force -ErrorAction Stop | Out-Null
}
Write-Host "[INFO] Logging initialized: $script:LogPath" -ForegroundColor Cyan
return $script:LogPath
}
catch {
Write-Warning "Failed to initialize logging: $($_.Exception.Message)"
return $null
}
}
function Build-EnhancedEventMessage {
<#
.SYNOPSIS
Builds a structured, descriptive event message for Windows Event Viewer.
.DESCRIPTION
Creates a well-formatted event message with clear sections for Problem,
Context, Solution, and Resources. This helps administrators quickly
understand and resolve issues from Event Viewer.
.PARAMETER Message
The primary message describing what happened.
.PARAMETER Level
The log level (DEBUG, INFO, SUCCESS, WARNING, ERROR).
.PARAMETER Indicator
The display indicator for the level (e.g., [WARN], [ERROR]).
.PARAMETER Timestamp
The formatted timestamp string.
.PARAMETER Solution
Optional recommended action or solution.
.PARAMETER Context
Optional additional context about what was happening.
.PARAMETER Component
Optional component or feature name.
.OUTPUTS
System.String
A formatted event message string.
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[string]$Message,
[Parameter(Mandatory = $true)]
[string]$Level,
[Parameter(Mandatory = $true)]
[string]$Indicator,
[Parameter(Mandatory = $true)]
[string]$Timestamp,
[Parameter(Mandatory = $false)]
[string]$Solution,
[Parameter(Mandatory = $false)]
[string]$Context,
[Parameter(Mandatory = $false)]
[string]$Component
)
# Build the base message with script metadata
$sb = [System.Text.StringBuilder]::new()
# Header section with script identification
[void]$sb.AppendLine("=============================================================")
[void]$sb.AppendLine(" $($script:ScriptName) - Event Log Entry")
[void]$sb.AppendLine("=============================================================")
[void]$sb.AppendLine("")
# Event metadata
[void]$sb.AppendLine("EVENT DETAILS")
[void]$sb.AppendLine("-------------------------------------------------------------")
[void]$sb.AppendLine(" Timestamp: $Timestamp")
[void]$sb.AppendLine(" Level: $Indicator")
[void]$sb.AppendLine(" Script: $($script:ScriptName)")
[void]$sb.AppendLine(" Version: $($script:ScriptVersion)")
[void]$sb.AppendLine(" Computer: $env:COMPUTERNAME")
[void]$sb.AppendLine(" User: $env:USERNAME")
if ($Component) {
[void]$sb.AppendLine(" Component: $Component")
}
[void]$sb.AppendLine("")
# Message section with appropriate header based on level
$messageHeader = switch ($Level) {
'ERROR' { "ERROR DESCRIPTION" }
'WARNING' { "WARNING DESCRIPTION" }
'SUCCESS' { "SUCCESS DETAILS" }
'DEBUG' { "DEBUG INFORMATION" }
default { "INFORMATION" }
}
[void]$sb.AppendLine($messageHeader)
[void]$sb.AppendLine("-------------------------------------------------------------")
[void]$sb.AppendLine(" $Message")
[void]$sb.AppendLine("")
# Context section (if provided)
if ($Context) {
[void]$sb.AppendLine("CONTEXT")
[void]$sb.AppendLine("-------------------------------------------------------------")
[void]$sb.AppendLine(" $Context")
[void]$sb.AppendLine("")
}
# Solution/Action section (if provided, especially important for warnings/errors)
if ($Solution) {
$solutionHeader = switch ($Level) {
'ERROR' { "RECOMMENDED ACTION" }
'WARNING' { "SUGGESTED ACTION" }
'DEBUG' { "ADDITIONAL NOTES" }
default { "NOTES" }
}
[void]$sb.AppendLine($solutionHeader)
[void]$sb.AppendLine("-------------------------------------------------------------")
[void]$sb.AppendLine(" $Solution")
[void]$sb.AppendLine("")
}
# Resources section
[void]$sb.AppendLine("RESOURCES")
[void]$sb.AppendLine("-------------------------------------------------------------")
[void]$sb.AppendLine(" Log File: $($script:LogPath)")
[void]$sb.AppendLine(" Log Folder: $($script:CentralLogPath)")
[void]$sb.AppendLine("")
[void]$sb.AppendLine("=============================================================")
return $sb.ToString()
}
function Write-Log {
<#
.SYNOPSIS
Writes a log entry to console and file.
.DESCRIPTION
Writes formatted log messages to console with color coding and to file
in markdown table format. Uses ASCII indicators only (no emoji).
Supports enhanced event logging with Solution, Context, and Component
parameters for more descriptive Windows Event Viewer messages.
.PARAMETER Message
The message to log.
.PARAMETER Level
The log level: DEBUG, INFO, SUCCESS, WARNING, or ERROR. Default is INFO.
.PARAMETER Solution
Optional. Recommended action or solution for warnings/errors.
Used to create more helpful Event Viewer messages.
.PARAMETER Context
Optional. Additional context about what was happening when this event occurred.
Used to create more descriptive Event Viewer messages.
.PARAMETER Component
Optional. The component or feature affected (e.g., 'Browser Detection', 'Favicon Fetch').
Helps categorize events in Event Viewer.
.EXAMPLE
Write-Log "Script started" -Level INFO
Write-Log "Operation completed" -Level SUCCESS
Write-Log "Warning message" -Level WARNING
Write-Log "Error occurred" -Level ERROR
.EXAMPLE
# Enhanced logging with context and solution
Write-Log "No browser profiles found" -Level WARNING `
-Context "Scanning for Chromium browser profiles" `
-Solution "Install a supported browser (Chrome, Edge, Brave) or verify browser data exists" `
-Component "Browser Detection"
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[string]$Message,
[Parameter(Mandatory = $false)]
[ValidateSet('DEBUG', 'INFO', 'SUCCESS', 'WARNING', 'ERROR')]
[string]$Level = 'INFO',
[Parameter(Mandatory = $false)]
[string]$Solution,
[Parameter(Mandatory = $false)]
[string]$Context,
[Parameter(Mandatory = $false)]
[string]$Component
)
# Check if Initialize-Log was called
if (-not $script:LogPath) {
Write-Warning "Logging not initialized. Call Initialize-Log first."
return
}
# Check log rotation before writing
Test-LogRotation
# Format timestamp for console
$timestamp = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'
# Map level to ASCII indicator and color
$levelConfig = @{
'DEBUG' = @{ Indicator = '[DBG]'; Color = 'Gray' }
'INFO' = @{ Indicator = '[INFO]'; Color = 'Cyan' }
'SUCCESS' = @{ Indicator = '[OK]'; Color = 'Green' }
'WARNING' = @{ Indicator = '[WARN]'; Color = 'Yellow' }
'ERROR' = @{ Indicator = '[ERROR]'; Color = 'Red' }
}
$config = $levelConfig[$Level]
# Write to console with color
Write-Host "[$timestamp] $($config.Indicator) $Message" -ForegroundColor $config.Color
# Write to file in JSONL format
try {
# Convert to structured log entry
$logEntryHash = ConvertTo-JsonLogEntry -Message $Message -Level $Level `
-Context $Context -Solution $Solution -Component $Component
# Write as JSONL
Write-JsonLogEntry -LogEntry $logEntryHash
}
catch {
# Silently continue if file logging fails
}
# Also write to Windows Event Log (best-effort)
if ($script:EnableEventLog -and $script:EventLogName -and $script:EventSource) {
try {
$entryType = switch ($Level) {
'SUCCESS' { [System.Diagnostics.EventLogEntryType]::Information }
'INFO' { [System.Diagnostics.EventLogEntryType]::Information }
'DEBUG' { [System.Diagnostics.EventLogEntryType]::Information }
'WARNING' { [System.Diagnostics.EventLogEntryType]::Warning }
'ERROR' { [System.Diagnostics.EventLogEntryType]::Error }
default { [System.Diagnostics.EventLogEntryType]::Information }
}
$eventId = switch ($Level) {
'SUCCESS' { 1001 }
'INFO' { 1000 }
'DEBUG' { 1000 }
'WARNING' { 2000 }
'ERROR' { 3000 }
default { 1000 }
}
# Build enhanced event message using helper function
$eventMessage = Build-EnhancedEventMessage -Message $Message -Level $Level `
-Indicator $config.Indicator -Timestamp $timestamp `
-Solution $Solution -Context $Context -Component $Component
# Write event to the myTech.Today log
Write-EventLog -LogName $script:EventLogName -Source $script:EventSource -EntryType $entryType -EventId $eventId -Message $eventMessage -ErrorAction SilentlyContinue
}
catch {
# If event log write fails, disable further event logging to avoid repeated errors
$script:EnableEventLog = $false
}
}
}
function Get-LogPath {
<#
.SYNOPSIS
Returns the current log file path.
.DESCRIPTION
Returns the path to the current log file, or $null if logging is not initialized.
.OUTPUTS
System.String
The path to the current log file.
.EXAMPLE
$logPath = Get-LogPath
Write-Host "Logging to: $logPath"
#>
[CmdletBinding()]
param()
return $script:LogPath
}
function Test-LogRotation {
<#
.SYNOPSIS
Checks if log rotation is needed and performs it if necessary.
.DESCRIPTION
Internal function that checks the current log file size and month,
archiving it if it exceeds the maximum size limit or if the month has changed.
#>
[CmdletBinding()]
param()
if (-not $script:LogPath -or -not (Test-Path $script:LogPath)) {
return
}
try {
$logFile = Get-Item $script:LogPath
$logLastWriteMonth = $logFile.LastWriteTime.ToString('yyyy-MM')
$currentMonth = Get-Date -Format 'yyyy-MM'
# Check if month has changed - archive to previous month's file
if ($logLastWriteMonth -ne $currentMonth) {
$archiveName = "$($script:ScriptName.ToLower()).$logLastWriteMonth.jsonl"
$archivePath = Join-Path $script:CentralLogPath $archiveName
# Only archive if the archive doesn't already exist
if (-not (Test-Path $archivePath)) {
Move-Item -Path $script:LogPath -Destination $archivePath -Force -ErrorAction SilentlyContinue
Write-Host "[INFO] Month changed. Previous month's log archived: $archivePath" -ForegroundColor Cyan
}
else {
# Archive already exists, just delete the old log
Remove-Item -Path $script:LogPath -Force -ErrorAction SilentlyContinue
}
# Create new empty JSONL file
New-Item -Path $script:LogPath -ItemType File -Force -ErrorAction SilentlyContinue | Out-Null
}
else {
# Same month - check size-based rotation
$sizeMB = $logFile.Length / 1MB
if ($sizeMB -gt $script:MaxLogSizeMB) {
# Archive the log with timestamp
$timestamp = Get-Date -Format 'yyyyMMdd_HHmmss'
$archiveName = "$($script:ScriptName.ToLower())_archived_$timestamp.jsonl"
$archivePath = Join-Path $script:CentralLogPath $archiveName
Move-Item -Path $script:LogPath -Destination $archivePath -Force -ErrorAction SilentlyContinue
# Create new empty JSONL file
New-Item -Path $script:LogPath -ItemType File -Force -ErrorAction SilentlyContinue | Out-Null
Write-Host "[INFO] Log file size limit exceeded. Archived to: $archivePath" -ForegroundColor Cyan
}
}
}
catch {
# Silently continue if rotation fails
}
}
# Note: When dot-sourcing this script, all functions are automatically available.
# Export-ModuleMember is not needed for .ps1 scripts (only for .psm1 modules).