Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #================================================================
- # Logger class
- #================================================================
- class Logger : System.IDisposable {
- [string]$LogFilePath
- [System.Collections.Generic.List[String]]$buffer
- [int]$bufferSize
- [bool]$Disposed = $false
- Logger([string]$logFilePath, [int]$bufferSize=0) {
- $this.LogFilePath = $logFilePath
- $this.bufferSize = $bufferSize
- $this.buffer = [System.Collections.Generic.List[String]]::new()
- }
- [void] Flush() {
- if ($this.buffer.Count -gt 0) {
- $this.buffer -join "`r`n" | Out-File -Append -FilePath $this.logFilePath
- $this.buffer.Clear()
- }
- }
- [void] LogInfo([string]$message) {
- $logEntry = "[$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')] $($message)"
- # Log to the main log file, regardless of type.
- try {
- if ($this.bufferSize -gt 0) {
- $this.buffer.Add($logEntry)
- if ($this.buffer.Count -ge $this.bufferSize) {
- $this.Flush()
- }
- } else {
- Add-Content -Path $this.LogFilePath -Value $logEntry
- }
- } catch {
- Write-Host " -- Unable to log the message to the log file." -ForegroundColor Yellow
- }
- # Log to stdout
- Write-Host $message
- }
- [void] Dispose() {
- if (-not $this.Disposed) {
- $this.Flush()
- $this.Disposed = $true
- }
- }
- }
- # Example
- $logpath = "$($PSScriptRoot)/test.log" # Make default path be the same as the calling script.
- $bufferSize = 50
- $logger = [Logger]::new($logpath, $bufferSize)
- $logger.LogInfo("Logging at $($logpath)")
- for($i=0; $i -lt 10; $i++){
- $logger.LogInfo("Message $($i)")
- }
- Write-Host "Number of items in the buffer: $($logger.buffer.Count)"
- #$logger.Flush()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement