AdvancedLogging.psm1

<#
.SYNOPSIS
    Advanced Logging module for PowerShell scripts.
.DESCRIPTION
    Provides a custom logging framework.
.NOTES
    Version: 1.2
    Author: iwanttosleep
#>


#region Module Setup

# Define global variables for logging
$Global:LogName = "Application"
$Global:SourceName = "MyScripts"
$Global:LogFilePath = "C:\Company\Monitoring\"  # Change this to your desired path
$Global:LogFileName = "Log_" + (Get-Date -Format "yyyy-MM-dd_HH-mm-ss") + ".log"
$Global:FullLogPath = Join-Path -Path $LogFilePath -ChildPath $LogFileName
$Global:LogLevel = "INFO"  # Default log level

# Create an event log, if it doesn't already exist.
New-EventLog -LogName $Global:LogName -Source $Global:SourceName -ErrorAction SilentlyContinue

#endregion

#region Functions

# Function to set log level
function Set-LogLevel {
    param (
        [Parameter(Mandatory = $true)]
        [ValidateSet("INFO", "WARN", "ERROR", "DEBUG", "VERBOSE")]
        [string]$Level
    )

    $Global:LogLevel = $Level
}

# Function to write log messages with level filtering
function Write-Log {
    param (
        [Parameter(Mandatory = $true)]
        [string]$Message,

        [Parameter(Mandatory = $false)]
        [ValidateSet("INFO", "WARN", "ERROR", "DEBUG", "VERBOSE")]
        [string]$Level = "INFO",

        [Parameter(Mandatory = $false)]
        [switch]$PrintToConsole = $false
    )

    if (-not (Test-Path -Path $Global:LogFilePath)) {
        New-Item -ItemType Directory -Path $Global:LogFilePath | Out-Null
    }

    if ($Level -eq "DEBUG" -and $Global:LogLevel -ne "DEBUG") { return }
    if ($Level -eq "VERBOSE" -and $Global:LogLevel -notin @("DEBUG", "VERBOSE")) { return }

    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "$timestamp [$Level] - $Message"

    if ($PrintToConsole) { Write-Output $logEntry }
    Add-Content -Path $Global:FullLogPath -Value $logEntry
}

# Function to log to Windows Event Log
function Write-EventLogEntry {
    param (
        [Parameter(Mandatory = $true)]
        [string]$Message,

        [Parameter(Mandatory = $false)]
        [int]$EventId = 1,

        [Parameter(Mandatory = $false)]
        [System.Diagnostics.EventLogEntryType]$EntryType = [System.Diagnostics.EventLogEntryType]::Information
    )

    if (-not (Get-EventLog -LogName $Global:LogName -Source $Global:SourceName -ErrorAction SilentlyContinue)) {
        New-EventLog -LogName $Global:LogName -Source $Global:SourceName -ErrorAction SilentlyContinue
    }

    Write-EventLog -LogName $Global:LogName -Source $Global:SourceName -EntryType $EntryType -EventId $EventId -Message $Message
    Write-Log -Message $Message -Level "EVENT"
}

#endregion

# Export functions
Export-ModuleMember -Function Set-LogLevel, Write-Log, Write-EventLogEntry