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.
CodePudding user response:
This might help you get started, it will only work for those lines that 
The colorization code requires PS 7 , but the basic principle of overriding a (native) command could be applied to PS 5.1 too:
- Define a function named like the original command.
- In the function body, get the original command using
Get-Command. By passing-CommandType Application, PowerShell searches only for a native command of the given name, within the paths defined by thePATHenvironment variable. So make sure that the full directory path ofkubectlis added to thePATHvariable. - Call the original command using call operator
&, forwarding the arguments of the function via the automatic$argsvariable. - Merge the stdout and stderr streams using redirection operator
2>&1so both can be processed byForEach-Object. - Now the PS 7 specific code:
- The
$KubectlStylevariable is aHashtablethat maps each log level to one of the predefined PowerShell formatting codes. Enter$PSStylein the console to see what other values are available. You may even specify RGB values like this:$PSStyle.Foreground.FromRgb(255,127,255). - Using the
-replaceoperator, we define a regular expression to match the[...]substring of the log lines and a script block to dynamically define the replacement value. - Within the script block,
$_is the current match.$_.Groups[1].Valueis either "INF", "WRN" or "ERR", while$_.Groups[0].Valueis the value of the full match (the whole[...]substring). - To produce the substitution value, we look up the style code from the
$KubectlStylehashtable, proceed to add the full match and add$PSStyle.Resetto reset the style to the default.
- The
