<# --------------------------------------------------------------------------- Module......: Logging.psm1 Projekt.....: Veeam Enterprise Installer Version.....: 2.0.0 Beschreibung Zentrales Logging-Modul. Funktionen • Textlog • Transcript • Konsolenausgabe • Farbige Statusmeldungen • Logrotation • Archivierung • Debug Logging • Fehlerprotokollierung • Veeam Setup Log Kopie ---------------------------------------------------------------------------#> Set-StrictMode -Version Latest #region Script Variablen $Script:LogFile = $null $Script:TranscriptFile = $null $Script:LogLevel = "INFO" #endregion ############################################################ # Initialize-Logging ############################################################ function Initialize-Logging { <# .SYNOPSIS Initialisiert das Logging. #> $Paths = Get-ProjectPaths $Script:LogFile = $Paths.LogFile $Script:TranscriptFile = $Paths.Transcript if (!(Test-Path $Paths.Logs)) { New-Item -Path $Paths.Logs -ItemType Directory -Force | Out-Null } if (!(Test-Path $Script:LogFile)) { New-Item -Path $Script:LogFile -ItemType File -Force | Out-Null } } ############################################################ # Get-TimeStamp ############################################################ function Get-TimeStamp { Get-Date -Format "yyyy-MM-dd HH:mm:ss" } ############################################################ # Write-Log ############################################################ function Write-Log { param( [Parameter(Mandatory)] [string]$Message, [ValidateSet("INFO","WARN","ERROR","SUCCESS","DEBUG")] [string]$Level = "INFO" ) $Time = Get-TimeStamp $Entry = "[{0}] [{1}] {2}" -f $Time,$Level,$Message Add-Content ` -Path $Script:LogFile ` -Value $Entry switch($Level) { "INFO" { Write-Host $Entry -ForegroundColor White } "WARN" { Write-Host $Entry -ForegroundColor Yellow } "ERROR" { Write-Host $Entry -ForegroundColor Red } "SUCCESS" { Write-Host $Entry -ForegroundColor Green } "DEBUG" { Write-Host $Entry -ForegroundColor Cyan } } } ############################################################ # Write-Info ############################################################ function Write-Info { param([string]$Message) Write-Log ` -Message $Message ` -Level INFO } ############################################################ # Write-Success ############################################################ function Write-Success { param([string]$Message) Write-Log ` -Message $Message ` -Level SUCCESS } #Beginn PART 2 ############################################################ # Write-Warning ############################################################ function Write-WarningLog { <# .SYNOPSIS Schreibt eine Warnung. #> param( [Parameter(Mandatory)] [string]$Message ) Write-Log ` -Message $Message ` -Level WARN } ############################################################ # Write-Error ############################################################ function Write-ErrorLog { <# .SYNOPSIS Schreibt einen Fehler. #> param( [Parameter(Mandatory)] [string]$Message ) Write-Log ` -Message $Message ` -Level ERROR } ############################################################ # Write-Debug ############################################################ function Write-DebugLog { <# .SYNOPSIS Schreibt Debugmeldungen. #> param( [Parameter(Mandatory)] [string]$Message ) if($Script:LogLevel -eq "DEBUG") { Write-Log ` -Message $Message ` -Level DEBUG } } ############################################################ # Write-Separator ############################################################ function Write-Separator { Write-Host "" Write-Host ("-" * 70) Add-Content ` -Path $Script:LogFile ` -Value ("-" * 70) } ############################################################ # Write-Section ############################################################ function Write-Section { param( [Parameter(Mandatory)] [string]$Title ) Write-Separator Write-Info $Title Write-Separator } ############################################################ # Write-Banner ############################################################ function Write-Banner { Write-Host "" Write-Host "===============================================================" -ForegroundColor Cyan Write-Host " Veeam Enterprise Installer v2.0" -ForegroundColor Cyan Write-Host "===============================================================" -ForegroundColor Cyan Write-Host "" Add-Content ` -Path $Script:LogFile ` -Value "===============================================================" Add-Content ` -Path $Script:LogFile ` -Value "Veeam Enterprise Installer gestartet" Add-Content ` -Path $Script:LogFile ` -Value "===============================================================" } ############################################################ # Start-TranscriptLogging ############################################################ function Start-TranscriptLogging { <# .SYNOPSIS Startet PowerShell Transcript. #> try { if(Test-Path $Script:TranscriptFile) { Remove-Item ` $Script:TranscriptFile ` -Force } Start-Transcript ` -Path $Script:TranscriptFile ` -Force | Out-Null Write-Success "Transcript gestartet." } catch { Write-WarningLog ` "Transcript konnte nicht gestartet werden." } } ############################################################ # Stop-TranscriptLogging ############################################################ function Stop-TranscriptLogging { <# .SYNOPSIS Beendet das Transcript. #> try { Stop-Transcript | Out-Null } catch { # Bereits beendet } } #Beginn PART3 ############################################################ # Rotate-Logs ############################################################ function Rotate-Logs { <# .SYNOPSIS Löscht alte Logdateien. #> param( [int]$RetentionDays = 30 ) $Paths = Get-ProjectPaths Write-Info "Prüfe Logrotation..." Get-ChildItem ` -Path $Paths.Logs ` -Filter "*.log" ` -ErrorAction SilentlyContinue | Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-$RetentionDays) } | ForEach-Object { Write-Info "Lösche alte Logdatei: $($_.Name)" Remove-Item ` $_.FullName ` -Force ` -ErrorAction SilentlyContinue } } ############################################################ # Archive-Logs ############################################################ function Archive-Logs { <# .SYNOPSIS Verschiebt Logs in ein Archiv. #> $Paths = Get-ProjectPaths $ArchiveFolder = Join-Path ` $Paths.Logs ` "Archive" if(!(Test-Path $ArchiveFolder)) { New-Item ` -Path $ArchiveFolder ` -ItemType Directory ` -Force | Out-Null } $TimeStamp = Get-Date -Format "yyyyMMdd_HHmmss" $Destination = Join-Path ` $ArchiveFolder ` "Logs_$TimeStamp" New-Item ` -Path $Destination ` -ItemType Directory ` -Force | Out-Null Get-ChildItem ` $Paths.Logs ` -Filter "*.log" | Where-Object { $_.Name -notmatch "Transcript" } | Copy-Item ` -Destination $Destination ` -Force Write-Success "Logs archiviert." } ############################################################ # Compress-Logs ############################################################ function Compress-Logs { <# .SYNOPSIS Erstellt ZIP Archiv. #> $Paths = Get-ProjectPaths $ArchiveFolder = Join-Path ` $Paths.Logs ` "Archive" $ZipFile = Join-Path ` $ArchiveFolder ` ("Logs_{0}.zip" -f (Get-Date -Format "yyyyMMdd_HHmmss")) Add-Type ` -AssemblyName ` System.IO.Compression.FileSystem [System.IO.Compression.ZipFile]::CreateFromDirectory( $Paths.Logs, $ZipFile ) Write-Success "ZIP Archiv erstellt." } ############################################################ # Clear-Logs ############################################################ function Clear-Logs { <# .SYNOPSIS Löscht alle Logdateien. #> $Paths = Get-ProjectPaths Get-ChildItem ` $Paths.Logs ` -Filter "*.log" | Remove-Item ` -Force ` -ErrorAction SilentlyContinue Write-Success "Logdateien gelöscht." } ############################################################ # Copy-VeeamSetupLogs ############################################################ function Copy-VeeamSetupLogs { <# .SYNOPSIS Kopiert die Veeam Setup Logs. #> $Source = "C:\ProgramData\Veeam\Setup\Temp" if(!(Test-Path $Source)) { Write-WarningLog ` "Keine Veeam Setup Logs gefunden." return } $Destination = Join-Path ` (Get-ProjectPaths).Logs ` "VeeamSetup" if(!(Test-Path $Destination)) { New-Item ` $Destination ` -ItemType Directory ` -Force | Out-Null } Copy-Item ` "$Source\*" ` $Destination ` -Recurse ` -Force Write-Success ` "Veeam Setup Logs kopiert." } #Beginn PART 4 ############################################################ # Write-ExceptionLog ############################################################ function Write-ExceptionLog { <# .SYNOPSIS Schreibt eine Exception vollständig ins Log. #> param( [Parameter(Mandatory)] [System.Exception]$Exception ) $Message = @" Exception: ----------- Message : $($Exception.Message) Type : $($Exception.GetType().FullName) StackTrace : $($Exception.StackTrace) "@ Write-EnterpriseLog ` -Message $Message ` -Level ERROR } ############################################################ # Write-ProgressLog ############################################################ function Write-ProgressLog { <# .SYNOPSIS Schreibt Fortschritt einer Aktion. #> param( [Parameter(Mandatory)] [string]$Action, [Parameter(Mandatory)] [string]$Status ) Write-Log ` -Message "$Action : $Status" ` -Level INFO } ############################################################ # Start-OperationTimer ############################################################ function Start-OperationTimer { <# .SYNOPSIS Startet Zeitmessung. #> param( [string]$Name = "Operation" ) $Timer = [System.Diagnostics.Stopwatch]::StartNew() return [PSCustomObject]@{ Name = $Name Timer = $Timer Start = Get-Date } } ############################################################ # Stop-OperationTimer ############################################################ function Stop-OperationTimer { <# .SYNOPSIS Beendet Zeitmessung. #> param( [Parameter(Mandatory)] $TimerObject ) $TimerObject.Timer.Stop() $Elapsed = $TimerObject.Timer.Elapsed Write-Success ( "{0} abgeschlossen. Dauer: {1}" -f $TimerObject.Name, $Elapsed ) return $Elapsed } ############################################################ # Write-ModuleHeader ############################################################ function Write-ModuleHeader { <# .SYNOPSIS Schreibt Modulstart. #> param( [Parameter(Mandatory)] [string]$ModuleName ) Write-Section ` "Starte Modul: $ModuleName" } ############################################################ # Write-ModuleFooter ############################################################ function Write-ModuleFooter { <# .SYNOPSIS Schreibt Modulende. #> param( [Parameter(Mandatory)] [string]$ModuleName, [string]$Status = "OK" ) Write-Success ( "Modul beendet: {0} Status: {1}" -f $ModuleName, $Status ) Write-Separator } ############################################################ # Write-ConfigurationValue ############################################################ function Write-ConfigurationValue { <# .SYNOPSIS Protokolliert Konfigurationswerte. #> param( [string]$Name, [string]$Value ) if([string]::IsNullOrWhiteSpace($Value)) { $Value = "" } Write-DebugLog ( "{0} = {1}" -f $Name, $Value ) } #Beginn PART 5 ############################################################ # Set-LogLevel ############################################################ function Set-LogLevel { <# .SYNOPSIS Setzt den Detailgrad des Loggings. #> param( [ValidateSet( "INFO", "DEBUG" )] [string]$Level = "INFO" ) $Script:LogLevel = $Level Write-Info ` "Log-Level gesetzt: $Level" } ############################################################ # Get-LogLevel ############################################################ function Get-LogLevel { return $Script:LogLevel } ############################################################ # Enable-DebugLogging ############################################################ function Enable-DebugLogging { Set-LogLevel ` -Level DEBUG } ############################################################ # Disable-DebugLogging ############################################################ function Disable-DebugLogging { Set-LogLevel ` -Level INFO } ############################################################ # Invoke-ErrorHandler ############################################################ function Invoke-ErrorHandler { <# .SYNOPSIS Zentrale Fehlerbehandlung. #> param( [Parameter(Mandatory)] [System.Management.Automation.ErrorRecord] $ErrorRecord ) $Message = @" Unbehandelter Fehler Message: $($ErrorRecord.Exception.Message) Kategorie: $($ErrorRecord.CategoryInfo) Position: $($ErrorRecord.InvocationInfo.PositionMessage) "@ Write-Log ` -Message $Message ` -Level ERROR } ############################################################ # Register-GlobalErrorHandler ############################################################ function Register-GlobalErrorHandler { <# .SYNOPSIS Aktiviert globale Fehlerbehandlung. #> $Script:PreviousErrorActionPreference = $ErrorActionPreference $ErrorActionPreference = "Stop" trap { Invoke-ErrorHandler ` -ErrorRecord $_ continue } Write-Info ` "Globale Fehlerbehandlung aktiviert." } ############################################################ # Save-InstallationState ############################################################ function Save-InstallationState { <# .SYNOPSIS Speichert Installationsstatus. #> param( [Parameter(Mandatory)] [string]$Step, [Parameter(Mandatory)] [ValidateSet( "START", "RUNNING", "SUCCESS", "FAILED" )] [string]$Status ) $StateFile = Join-Path ( (Get-ProjectPaths).Temp ) "InstallationState.json" $State = [PSCustomObject]@{ Step = $Step Status = $Status Computer = $env:COMPUTERNAME User = $env:USERNAME Date = Get-Date } $State | ConvertTo-Json | Set-Content ` -Path $StateFile ` -Encoding UTF8 Write-DebugLog ` "Installationsstatus gespeichert: $Step / $Status" } ############################################################ # Get-InstallationState ############################################################ function Get-InstallationState { <# .SYNOPSIS Liest gespeicherten Status. #> $StateFile = Join-Path ( (Get-ProjectPaths).Temp ) "InstallationState.json" if(!(Test-Path $StateFile)) { return $null } Get-Content ` $StateFile ` -Raw | ConvertFrom-Json } ############################################################ # Remove-InstallationState ############################################################ function Remove-InstallationState { $StateFile = Join-Path ( (Get-ProjectPaths).Temp ) "InstallationState.json" if(Test-Path $StateFile) { Remove-Item ` $StateFile ` -Force } } #Beginn PART 6 ############################################################ # Test-LogFile ############################################################ function Test-LogFile { <# .SYNOPSIS Prüft ob Logdatei verfügbar ist. #> if([string]::IsNullOrWhiteSpace($Script:LogFile)) { return $false } return (Test-Path $Script:LogFile) } ############################################################ # Get-LogInformation ############################################################ function Get-LogInformation { <# .SYNOPSIS Liefert Logging Informationen. #> [PSCustomObject]@{ LogFile = $Script:LogFile Transcript = $Script:TranscriptFile LogLevel = $Script:LogLevel LogAvailable = Test-LogFile } } ############################################################ # Close-Logging ############################################################ function Close-Logging { <# .SYNOPSIS Beendet Logging sauber. #> Write-Info ` "Logging wird beendet." try { Stop-TranscriptLogging } catch { } } ############################################################ # Erweiterte Funktionen für Logging ############################################################ ############################################################ # Enterprise Logging ############################################################ $Script:LogDirectory = "C:\ProgramData\VeeamInstaller\Logs" ############################################################ # Initialize-EnterpriseLog ############################################################ function Initialize-EnterpriseLog { param( [string]$Name = "VeeamInstall" ) if(!(Test-Path $Script:LogDirectory)) { New-Item ` -Path $Script:LogDirectory ` -ItemType Directory ` -Force | Out-Null } $Script:LogFile = Join-Path ` $Script:LogDirectory ` ( $Name + "_" + ( Get-Date ` -Format "yyyyMMdd_HHmmss" ) + ".log" ) New-Item ` -Path $Script:LogFile ` -ItemType File ` -Force | Out-Null return $Script:LogFile } ############################################################ # Write-EnterpriseLog ############################################################ function Write-EnterpriseLog { <# .SYNOPSIS Schreibt Enterprise Log Einträge. #> param( [ValidateSet( "INFO", "WARNING", "ERROR", "DEBUG" )] [string]$Level = "INFO", [Parameter(Mandatory)] [string]$Message ) if(!$Script:LogFile) { Initialize-EnterpriseLog | Out-Null } $Entry = [PSCustomObject]@{ Time = Get-Date Level = $Level Computer = $env:COMPUTERNAME User = $env:USERNAME Message = $Message } $Line = ( $Entry.Time.ToString( "yyyy-MM-dd HH:mm:ss" ) ) + " [" + $Entry.Level + "] " + $Entry.Message Add-Content ` -Path $Script:LogFile ` -Value $Line return $Entry } ############################################################ # Write-AuditEvent ############################################################ function Write-AuditEvent { <# .SYNOPSIS Schreibt strukturiertes Audit Event. #> param( [Parameter(Mandatory)] [string]$Action, [string]$Status = "SUCCESS", [hashtable]$Data ) $AuditDirectory = "C:\ProgramData\VeeamInstaller\Audit" if(!(Test-Path $AuditDirectory)) { New-Item ` -Path $AuditDirectory ` -ItemType Directory ` -Force | Out-Null } $AuditFile = Join-Path ` $AuditDirectory ` "Audit.json" $Event = [PSCustomObject]@{ Time = Get-Date Action = $Action Status = $Status Data = $Data } $Event | ConvertTo-Json ` -Depth 8 | Add-Content ` -Path $AuditFile return $Event } ############################################################ # Write-ExceptionLog ############################################################ function Write-ExceptionLog { <# .SYNOPSIS Speichert Fehlerdetails. #> param( [Parameter(Mandatory)] [System.Exception]$Exception, [string]$Context = "Unknown" ) $ErrorEntry = [PSCustomObject]@{ Time = Get-Date Level = "ERROR" Context = $Context Message = $Exception.Message Type = $Exception.GetType().FullName StackTrace = $Exception.StackTrace } Write-EnterpriseLog ` -Level ERROR ` -Message ( "$Context - $($Exception.Message)" ) $ErrorFile = Join-Path ` $Script:LogDirectory ` "Errors.json" $ErrorEntry | ConvertTo-Json ` -Depth 10 | Add-Content ` -Path $ErrorFile return $ErrorEntry } ############################################################ # Start-InstallPhase ############################################################ function Start-InstallPhase { <# .SYNOPSIS Protokolliert Installationsphase. #> param( [Parameter(Mandatory)] [string]$Name ) Write-EnterpriseLog ` -Level INFO ` -Message ( "START PHASE: " + $Name ) Write-AuditEvent ` -Action ( "Start Phase: " + $Name ) } ############################################################ # Complete-InstallPhase ############################################################ function Complete-InstallPhase { <# .SYNOPSIS Beendet Installationsphase. #> param( [Parameter(Mandatory)] [string]$Name, [string]$Status = "SUCCESS" ) Write-EnterpriseLog ` -Level INFO ` -Message ( "END PHASE: " + $Name ) Write-AuditEvent ` -Action ( "End Phase: " + $Name ) -Status $Status } ############################################################ # Export Module Functions ############################################################ Export-ModuleMember ` -Function ` Initialize-Logging, Write-Log, Write-Info, Write-Success, Write-WarningLog, Write-ErrorLog, Write-DebugLog, Write-Separator, Write-Section, Write-Banner, Start-TranscriptLogging, Stop-TranscriptLogging, Rotate-Logs, Archive-Logs, Compress-Logs, Clear-Logs, Copy-VeeamSetupLogs, Write-ExceptionLog, Write-ProgressLog, Start-OperationTimer, Stop-OperationTimer, Write-ModuleHeader, Write-ModuleFooter, Write-ConfigurationValue, Set-LogLevel, Get-LogLevel, Enable-DebugLogging, Disable-DebugLogging, Invoke-ErrorHandler, Register-GlobalErrorHandler, Save-InstallationState, Get-InstallationState, Remove-InstallationState, Test-LogFile, Get-LogInformation, Initialize-EnterpriseLog Write-EnterpriseLog Write-AuditEvent Write-ExceptionLog Start-InstallPhase Complete-InstallPhase Close-Logging ############################################################ # Ende Logging.psm1 ############################################################