I'm using kubectl to print logs from pods. (my adventure with kubectl and powershell started today)
Our logs always start with:
[12:00:49 INF] ...
or
[12:00:49 WRN] ...
or
[12:00:49 ERR] ...
My goal is to see those lines in colors based on log level.
I would assume I need to add some kind of script to $profile analyzing output of kubectl and colorize it line by line.
Please note that in $profile file I already have scripts for kubectl autocomplete.
Is it possible to do and if so could you please direct me how to do it.
This might help you get started, it will only work for those lines that matches the pattern. You can add more options to each Key Value, such as BackgroundColor etc. This technique uses splatting to determine the coloring of the lines.
$test = @'
[12:00:49 INF] hello
[12:00:49 WRN] world
[12:00:49 ERR] 123
[12:00:49 INF] 123
[12:00:49 WRN] world
[12:00:49 ERR] hello
'@ -split '\r?\n'
$map = @{
ERR = @{ ForegroundColor = 'Red' }
WRN = @{ ForegroundColor = 'Yellow' }
INF = @{ ForegroundColor = 'Green' }
}
[regex] $re = '(?<=^\[[\d:]+\s)(?:{0})' -f ($map.Keys -join '|')
foreach ($line in $test) {
# get the key we need to use for this line with regex
# and assign it to `$key`
if ($key = $re.Match($line).Value) {
# if the line matched the pattern, get inner hashtable
$fg = $map[$key]
# use splatting
Write-Host @fg $line
# and go to next line
continue
}
# if the line didn't match the pattern, use default `Write-Host` values
Write-Host $line
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With