Comprehensive Logging Tool
<# .SYNOPSIS Comprehensive Logging Tool .DESCRIPTION This script provides functionality for creating, managing, and analyzing log files in various formats. It includes features for creating logs, appending to existing logs, searching logs, and performing basic log analysis. .NOTES File Name : LoggingTool.ps1 Author : [Your Name] Prerequisite : PowerShell V5.1 or later Version : 1.0 Date : [Current Date] .EXAMPLE .\LoggingTool.ps1 #> # Global variables $global:logPath = "$env:USERPROFILE\Desktop\Logs" $global:currentLogFile = "" <# .SYNOPSIS Displays the main menu of the tool. #> function Show-Menu { Clear-Host Write-Host "=== Comprehensive Logging Tool ===" -ForegroundColor Cyan Write-Host "Current Log File: $global:currentLogFile" Write-Host "1. Create New Log File" Write-Host "2. Append to Existing Log" Write-Host "3. View Log Content" Write-Host "4. Search Log" Write-Host "5. Analyze Log (Basic Statistics)" Write-Host "6. Export Log to CSV" Write-Host "7. Rotate Log File" Write-Host "8. Delete Log File" Write-Host "9. Exit" } <# .SYNOPSIS Creates a new log file. #> function Create-NewLogFile { $logName = Read-Host "Enter the name for the new log file (without extension)" $logFormat = Read-Host "Enter log format (txt/json/xml)" $fileName = "$logName.$(Get-Date -Format 'yyyyMMdd').$logFormat" $global:currentLogFile = Join-Path $global:logPath $fileName if (!(Test-Path $global:logPath)) { New-Item -ItemType Directory -Path $global:logPath | Out-Null } switch ($logFormat) { "txt" { "" | Out-File -FilePath $global:currentLogFile } "json" { "[]" | Out-File -FilePath $global:currentLogFile } "xml" { '<?xml version="1.0" encoding="UTF-8"?><log></log>' | Out-File -FilePath $global:currentLogFile } default { Write-Host "Invalid format. Creating a txt file." -ForegroundColor Yellow; "" | Out-File -FilePath $global:currentLogFile } } Write-Host "Log file created: $global:currentLogFile" -ForegroundColor Green } <# .SYNOPSIS Appends an entry to the current log file. #> function Append-ToLog { if ([string]::IsNullOrEmpty($global:currentLogFile)) { Write-Host "No log file selected. Please create or select a log file first." -ForegroundColor Red return } $logEntry = Read-Host "Enter the log entry" $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss" $fileExtension = [System.IO.Path]::GetExtension($global:currentLogFile) switch ($fileExtension) { ".txt" { "$timestamp - $logEntry" | Out-File -FilePath $global:currentLogFile -Append } ".json" { $jsonContent = Get-Content -Raw -Path $global:currentLogFile | ConvertFrom-Json $newEntry = @{ "timestamp" = $timestamp "message" = $logEntry } $jsonContent += $newEntry $jsonContent | ConvertTo-Json | Set-Content -Path $global:currentLogFile } ".xml" { [xml]$xmlContent = Get-Content -Path $global:currentLogFile $newEntry = $xmlContent.CreateElement("entry") $newEntry.SetAttribute("timestamp", $timestamp) $newEntry.InnerText = $logEntry $xmlContent.log.AppendChild($newEntry) | Out-Null $xmlContent.Save($global:currentLogFile) } } Write-Host "Log entry added successfully." -ForegroundColor Green } <# .SYNOPSIS Views the content of the current log file. #> function View-LogContent { if ([string]::IsNullOrEmpty($global:currentLogFile)) { Write-Host "No log file selected. Please create or select a log file first." -ForegroundColor Red return } Get-Content -Path $global:currentLogFile | Out-Host Read-Host "Press Enter to continue..." } <# .SYNOPSIS Searches the current log file for a specific term. #> function Search-Log { if ([string]::IsNullOrEmpty($global:currentLogFile)) { Write-Host "No log file selected. Please create or select a log file first." -ForegroundColor Red return } $searchTerm = Read-Host "Enter the search term" $results = Get-Content -Path $global:currentLogFile | Select-String -Pattern $searchTerm if ($results) { Write-Host "Search Results:" -ForegroundColor Yellow $results | ForEach-Object { Write-Host $_ } } else { Write-Host "No matches found." -ForegroundColor Yellow } Read-Host "Press Enter to continue..." } <# .SYNOPSIS Performs basic analysis on the current log file. #> function Analyze-Log { if ([string]::IsNullOrEmpty($global:currentLogFile)) { Write-Host "No log file selected. Please create or select a log file first." -ForegroundColor Red return } $content = Get-Content -Path $global:currentLogFile $totalEntries = $content.Count $uniqueEntries = ($content | Select-Object -Unique).Count $firstEntry = $content | Select-Object -First 1 $lastEntry = $content | Select-Object -Last 1 Write-Host "Log Analysis:" -ForegroundColor Yellow Write-Host "Total Entries: $totalEntries" Write-Host "Unique Entries: $uniqueEntries" Write-Host "First Entry: $firstEntry" Write-Host "Last Entry: $lastEntry" Read-Host "Press Enter to continue..." } <# .SYNOPSIS Exports the current log file to CSV format. #> function Export-LogToCSV { if ([string]::IsNullOrEmpty($global:currentLogFile)) { Write-Host "No log file selected. Please create or select a log file first." -ForegroundColor Red return } $csvPath = [System.IO.Path]::ChangeExtension($global:currentLogFile, "csv") $content = Get-Content -Path $global:currentLogFile $csvData = $content | ForEach-Object { if ($_ -match "^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}) - (.*)$") { [PSCustomObject]@{ Timestamp = $matches[1] Message = $matches[2] } } } $csvData | Export-Csv -Path $csvPath -NoTypeInformation Write-Host "Log exported to CSV: $csvPath" -ForegroundColor Green } <# .SYNOPSIS Rotates the current log file. #> function Rotate-LogFile { if ([string]::IsNullOrEmpty($global:currentLogFile)) { Write-Host "No log file selected. Please create or select a log file first." -ForegroundColor Red return } $directory = [System.IO.Path]::GetDirectoryName($global:currentLogFile) $fileName = [System.IO.Path]::GetFileNameWithoutExtension($global:currentLogFile) $extension = [System.IO.Path]::GetExtension($global:currentLogFile) $newFileName = "{0}_{1}{2}" -f $fileName, (Get-Date -Format "yyyyMMddHHmmss"), $extension $newFilePath = Join-Path $directory $newFileName Move-Item -Path $global:currentLogFile -Destination $newFilePath Write-Host "Log file rotated. New file: $newFilePath" -ForegroundColor Green # Create a new empty log file "" | Out-File -FilePath $global:currentLogFile Write-Host "New empty log file created: $global:currentLogFile" -ForegroundColor Green } <# .SYNOPSIS Deletes the current log file. #> function Delete-LogFile { if ([string]::IsNullOrEmpty($global:currentLogFile)) { Write-Host "No log file selected. Please create or select a log file first." -ForegroundColor Red return } $confirmation = Read-Host "Are you sure you want to delete the current log file? (Y/N)" if ($confirmation -eq "Y") { Remove-Item -Path $global:currentLogFile -Force Write-Host "Log file deleted: $global:currentLogFile" -ForegroundColor Green $global:currentLogFile = "" } else { Write-Host "Deletion cancelled." -ForegroundColor Yellow } } # Main program loop do { Show-Menu $choice = Read-Host "`nEnter your choice (1-9)" switch ($choice) { "1" { Create-NewLogFile } "2" { Append-ToLog } "3" { View-LogContent } "4" { Search-Log } "5" { Analyze-Log } "6" { Export-LogToCSV } "7" { Rotate-LogFile } "8" { Delete-LogFile } "9" { Write-Host "Exiting program..." -ForegroundColor Yellow; break } default { Write-Host "Invalid choice. Please try again." -ForegroundColor Red } } if ($choice -ne "9") { Read-Host "`nPress Enter to continue..." } } while ($choice -ne "9")
This Comprehensive Logging Tool includes:
- A menu-driven interface for easy navigation.
- Functions to manage and analyze log files:
- Creating new log files in various formats (txt, json, xml)
- Appending entries to existing logs
- Viewing log content
- Searching logs for specific terms
- Performing basic log analysis
- Exporting logs to CSV format
- Rotating log files
- Deleting log files
- Support for different log formats (txt, json, xml)
- Error handling and user confirmations for critical operations
Key features:
- Flexible log creation in multiple formats
- Easy log entry addition with automatic timestamps
- Search functionality for quick information retrieval
- Basic log analysis for insights
- Log rotation for managing file sizes
- CSV export for further analysis in spreadsheet applications
- Safe log file deletion with user confirmation
This tool is particularly useful for:
- Developers needing to implement logging in their applications
- System administrators managing log files
- IT professionals troubleshooting issues using logs
- Anyone needing to create, manage, or analyze log files
To use this script effectively:
- Run PowerShell with appropriate permissions to create and modify files in the specified log directory
- Ensure you have write access to the desktop or modify the
$global:logPath
variable to a suitable location - Be cautious when deleting log files, as this operation is irreversible
This script provides a comprehensive set of features for log management and analysis, making it easier to maintain, search, and gain insights from log files in various formats.
Leave a Reply
Want to join the discussion?Feel free to contribute!