How to fetch jenkins log between two timestamp using groovy?

202 views Asked by At

My jenkins log is too big and often consoleFull did not load it completely. So using groovy script fetching logs between timestamp like below.

JOBNAME = 'My_Jenkins_job'
BUILDID = '34'
def start = 23
def end = 25
def time_prefix = '2021-11-30T08:'

for (job in Jenkins.instance.getAllItems(Job.class)) {
    if (job.name == JOBNAME) {
        for (build in job.builds) {
            if (build.id == BUILDID) {
                def lines = build.logFile.readLines()

                println '===================================================='
                println "Log summary between ${time_prefix}${start}..${end}"
                println '======================================================='
                for (int i in start..end) {
                    def logmsg = lines.findAll {
                        it.contains("${time_prefix}${i}")
                    }
                    logmsg.each {
                        println it
                    }
                }
            }
        }
    }
}

But here I am using string and contains to parse the timings ,But if I can use datetime in range it will be good. How to convert the date time format in Jenkins to groovy and put it in a range.

I am trying to convert time and it fails.

String log_time="2021-12-01T09:19:54-07:00"
String timestamp = Date.parse("yyyy-MM-dd'T'HH:mm-ss':00'", log_time) 
println(timestamp)

If I can convert the jenkins timestamp and put it in range operator I can extract the log between timestamp. How to do it?

1

There are 1 answers

0
Kaus2b On

This is working for me:

import java.time.LocalDateTime
import java.time.format.DateTimeFormatter

def log_time='2021-12-01T09:19:54-07:00'
def timestamp = LocalDateTime.parse(log_time, DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssz"))  
println timestamp