2

I have this script which sends logs from each Kubernetes pod to stdout:

#!/usr/bin/env bash

set -e;

oc project cdt-dev

pods=$(oc get pods --show-all=false -o name)

for j in ${pods}; do
    oc logs -f "$j" | bunyan -o short -l error &
done

wait;

what I want to do is prepend the logs with the pod name, something like this:

#!/usr/bin/env bash

# ...

for j in ${pods}; do
    oc logs -f "$j" | bunyan -o short -l error |  echo "$j => $stdin" &
done

wait

I think you can see what I am trying to do, I pipe the logs through a program called bunyan which interprets the logs and then I want to prepend the name of the pod ($j) to each line. But the above can't be right. Is there a way to do this with plain old bash?

Note $stdin is just some dummy variable representing a single line of stdin, that doesn't really exist here tmk.

0

2 Answers 2

5

One option is awk:

for j in ...; do
  oc ... | bunyan --color ... | awk -v node="$j" '{print node " " $0}'
done

An example run:

$ for j in node1 node2 node3
> do
> echo stuff | awk -v node="$j" '{print node " " $0}'
> done
node1 stuff
node2 stuff
node3 stuff

Another option is sed:

for j in node1 node2 node3; do
  j=${j////\\/}
  j=${j//&/\\&}
  oc ... | bunyan --color ... | sed "s/^/$j /"
done

We take care to escape any forward-slashes or & in j, as sed interprets those specially in s// commands. I've used a bash-ism there to do search-and-replace in the parameter expansion. The two forward-slashes mean "replace all of the matches" and the doubled \\ are there in order to result in a single backslash in the replaced text.

5
  • thanks, I have a solution which I posted, but it doesn't keep the control chars, so I lose the terminal colors/styling which was helpful, any idea how to keep the control chars etc? I will try your solution right now. Apr 12, 2018 at 12:57
  • your solution works well, but it has the same problem as mine - control chars are gone / terminal styling is gone in the final output Apr 12, 2018 at 13:08
  • It’s possible that bunyan checks to see if it’s writing to a terminal or not.
    – Jeff Schaller
    Apr 12, 2018 at 14:31
  • thanks you're right, I wonder who it determines that? anyway, I think @meuh solved that one for me, as a comment to my answer, you can force bunyan to use colors, with the --colors flag. Apr 12, 2018 at 15:31
  • I incorporated the --color comment from meuh, @AlexanderMills, and also added a sed option.
    – Jeff Schaller
    Apr 13, 2018 at 18:14
0

This works for me:

oc logs -f "$j" | bunyan -o short -l error  | while read line; do echo "$j $line"; done &

but one problem is that I lose the terminal styling, which was helpful. Anyone know how to keep control chars etc?

2
  • bunyan has an option --color that might force colouring.
    – meuh
    Apr 12, 2018 at 14:26
  • yeah good idea, that might be the one Apr 12, 2018 at 14:34

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .