Vitor Estevam
Vitor Estevam

Reputation: 223

how to generate a log in kubectl pod by command line

I have a mysqldb pod and need to add a log when we run a script restorebackup.sh. The script is inside the pod and i need this log in the general logs of the pod (to access it with kubectl get logs services/mysqldb).

There is any way to do this?

Upvotes: 8

Views: 6298

Answers (3)

mozello
mozello

Reputation: 1244

A container engine handles and redirects any output generated to a containerized application's stdout and stderr streams.

On Linux, the set of file descriptors open in a process can be accessed under the path /proc/PID/fd/, where PID is the process identifier. File descriptor /proc/PID/fd/0 is stdin, /proc/PID/fd/1 is stdout, and /proc/PID/fd/2 is stderr.

So, assuming the main command in a container has PID '1' run the following command inside a k8s Pod:

$ sh restorebackup.sh >> /proc/1/fd/1

Then you will see its stdout in the Pod's logs.

$ kubectl logs yourPodName
...
some stdout from your script...
...

Keep in mind, that this way you only write the stdout of your bash script.

To write stdout and stderr from your script, run it like this:

$ sh restorebackup.sh 1>> /proc/1/fd/1 2>> /proc/1/fd/2

Or modify the code of the script to write info messages to /proc/1/fd/1 and error messages to /proc/1/fd/2.

Upvotes: 1

confused genius
confused genius

Reputation: 3254

  • kubectl logs is nothing but the stdout&stderr stream of the container (pid 1 process) in it
  • So to have restorebackup.sh output saved to a file and also to stream it to stdout , we can use utilities like tee ( it saves output to a file and also to stdout)

Example :

[root@c3~]# echo foo | tee boo
foo
[root@c3~]# cat boo
foo
  • in your case restorebackup.sh should be modified in such a way that all the output generating commands should use tee

Upvotes: 2

Ji Bin
Ji Bin

Reputation: 531

Generally the kubectl logs shows the first process's stdout (pid=1). So you could try put logs to /proc/1/fd/1 in you pod.

An example command in pod:

echo hello >> /proc/1/fd/1

Then you will able to see this hello by kubectl logs.

For you script restorebackup.sh, maybe you could try sh restorebackup.sh >> /proc/1/fd/1 to redirect all outputs.

Upvotes: 12

Related Questions