Advertisement
Guest User

Untitled

a guest
Feb 21st, 2025
50
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #================================================================
  2. # Logger class
  3. #================================================================
  4. class Logger : System.IDisposable {
  5.     [string]$LogFilePath
  6.     [System.Collections.Generic.List[String]]$buffer
  7.     [int]$bufferSize
  8.     [bool]$Disposed = $false
  9.  
  10.     Logger([string]$logFilePath, [int]$bufferSize=0) {
  11.         $this.LogFilePath = $logFilePath
  12.         $this.bufferSize = $bufferSize
  13.         $this.buffer = [System.Collections.Generic.List[String]]::new()
  14.     }
  15.  
  16.     [void] Flush() {
  17.         if ($this.buffer.Count -gt 0) {
  18.             $this.buffer -join "`r`n" | Out-File -Append -FilePath $this.logFilePath
  19.             $this.buffer.Clear()
  20.         }
  21.     }
  22.  
  23.     [void] LogInfo([string]$message) {
  24.         $logEntry = "[$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')] $($message)"
  25.         # Log to the main log file, regardless of type.
  26.  
  27.         try {
  28.  
  29.             if ($this.bufferSize -gt 0) {
  30.                 $this.buffer.Add($logEntry)
  31.                 if ($this.buffer.Count -ge $this.bufferSize) {
  32.                     $this.Flush()
  33.                 }
  34.             } else {
  35.                 Add-Content -Path $this.LogFilePath -Value $logEntry
  36.             }
  37.         } catch {
  38.             Write-Host "    -- Unable to log the message to the log file." -ForegroundColor Yellow
  39.         }
  40.        
  41.         # Log to stdout
  42.         Write-Host $message
  43.     }
  44.  
  45.     [void] Dispose() {
  46.         if (-not $this.Disposed) {
  47.             $this.Flush()
  48.             $this.Disposed = $true
  49.         }
  50.     }
  51. }
  52.  
  53. # Example
  54. $logpath = "$($PSScriptRoot)/test.log" # Make default path be the same as the calling script.
  55. $bufferSize = 50
  56. $logger = [Logger]::new($logpath, $bufferSize)
  57. $logger.LogInfo("Logging at $($logpath)")
  58. for($i=0; $i -lt 10; $i++){
  59.     $logger.LogInfo("Message $($i)")
  60. }
  61.  
  62. Write-Host "Number of items in the buffer: $($logger.buffer.Count)"
  63.  
  64. #$logger.Flush()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement