Home > Software design >  Colorize output logs of a native command-line app in the PowerShell console
Colorize output logs of a native command-line app in the PowerShell console

Time:06-01

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 Console output

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 the PATH environment variable. So make sure that the full directory path of kubectl is added to the PATH variable.
  • Call the original command using call operator &, forwarding the arguments of the function via the automatic $args variable.
  • Merge the stdout and stderr streams using redirection operator 2>&1 so both can be processed by ForEach-Object.
  • Now the PS 7 specific code:
    • The $KubectlStyle variable is a Hashtable that maps each log level to one of the predefined PowerShell formatting codes. Enter $PSStyle in 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 -replace operator, 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].Value is either "INF", "WRN" or "ERR", while $_.Groups[0].Value is the value of the full match (the whole [...] substring).
    • To produce the substitution value, we look up the style code from the $KubectlStyle hashtable, proceed to add the full match and add $PSStyle.Reset to reset the style to the default.
  • Related