PowerShell: Simple Logging helper

Scenario: How to log all my message with different color on the console and with category into CSV files


Code Snippet

$global:errorCount = 0
$logFolder = "$root\Logs"

function EnsureLogFolder() {
	$command = $MyInvocation.MyCommand.Name
	if(!(Test-Path $logFolder)) {		
		$newFolder = New-Item -ItemType Directory -Path $logFolder -Force
		LogInfo "[$command]: Log folder does not exist, provisioning folder $logFolder..."
	}
}

function LogMessage($msg, $category) {	
	$logFile = "$logFolder\log.csv"
	$mailFile = "$logFolder\mail.csv"

	$Properties = @{		
		"Category" = $category
		Date = (Get-Date)		
		Message = $msg
	}
	
	switch($category) {
		"INFO" { Write-Host $msg }
		"DEBUG" { Write-Host "================ $msg ================" -ForegroundColor Magenta  }
		"SUCCESS" { Write-Host $msg -ForegroundColor Green }
		"WARNING" { Write-Host $msg -ForegroundColor Yellow }
		"ERROR" { Write-Host $msg -ForegroundColor Red }
		"MAIL" { }
	}

	$obj = New-Object psobject -Property $Properties
	if($category -ne "MAIL") {		
		$obj | Select Date, Category, Message | Export-Csv $logFile -NoTypeInformation -Append
	}
	else {
		$obj | Select Date, Message | Export-Csv $mailFile -NoTypeInformation -Append
	}
}

function LogEmail($msg) {
	LogMessage $msg "MAIL"
}

function LogDebug($msg) {
	LogMessage $msg "DEBUG"
}

function LogInfo($msg) {	
	LogMessage $msg "INFO"
}

function LogSuccess($msg) {
	LogMessage $msg "SUCCESS"
}

function LogWarning($msg) {
	LogMessage $msg "WARNING"
}

function LogError($msg) {
	LogMessage $msg "ERROR"
	$global:errorCount++
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s