How to get logs of jobs created by a cronjob?

12/6/2018

Seems that kubectl logs doesn't support cronjob. It says

error: cannot get the logs from *v1beta1.CronJob: selector for *v1beta1.CronJob not implemented

Currently I check the logs of all relative jobs one by one.

Is there any simple command or tool to get these logs?


I did some research on bash script and modified edbighead's answer to better suit my needs.

# cronJobGetAllLogs.sh: Get all logs of a cronjob.
# example:
# ./cronJobGetAllLogs.sh [Insert name of cronJob]

jobs=( $(kubectl get jobs --no-headers -o custom-columns=":metadata.name" | awk "/$1-[0-9]+/{print \$1}" | sort -r ) )
for job in "${jobs[@]}"
do
    echo Logs from job $job
    pod=$(kubectl get pods -l job-name=$job --no-headers -o custom-columns=":metadata.name")
    kubectl logs $pod
done
# cronJobGetLatestLog.sh: Get log of latest job initiated by a cronjob.
# example:
# ./cronJobGetLateestLog.sh [Insert name of cronJob]

job=$(kubectl get jobs --no-headers -o custom-columns=":metadata.name" | awk "/$1-[0-9]+/{print \$1}" | sort -r | head -1)
pod=$(kubectl get pods -l job-name=$job --no-headers -o custom-columns=":metadata.name")
kubectl logs $pod
-- Leisen Chang
cron
kubernetes

1 Answer

12/6/2018

From documentation of CronJobs and Jobs

A Cron Job creates Jobs on a time-based schedule

...

A job creates one or more pods and ensures that a specified number of them successfully terminate.

All you need is to view logs for a pod that was created for the job.

  1. Find your job with kubectl get jobs. This will return your CronJob name with a timestamp

  2. Find pod for executed job kubectl get pods -l job-name=your-job-@timestamp

  3. Use kubectl logs your-job-@timestamp-id to view logs

Here's an example of bash script that does all the above and outputs logs for every job's pod.

jobs=( $(kubectl get jobs --no-headers -o custom-columns=":metadata.name") )
for job in "${jobs[@]}"
do
   pod=$(kubectl get pods -l job-name=$job --no-headers -o custom-columns=":metadata.name")
   kubectl logs $pod
done
-- edbighead
Source: StackOverflow