开发者

Reading tail-f output with groovy process

开发者 https://www.devze.com 2023-02-27 17:03 出处:网络
Hi I want to read tail -f with a groovy process for a while, then take what I got from it and destroy the process. I\'m doing it in a \"watchman-class\"-setting (that is I execute the process at the s

Hi I want to read tail -f with a groovy process for a while, then take what I got from it and destroy the process. I'm doing it in a "watchman-class"-setting (that is I execute the process at the start of the test, and want to get out the data after the test has been completed).

Problem is that I'm not getting anything out of the process (process.in.text), even though lots has been written to the file I'm reading from.

I've tried to see if anyone's attempted this before, but couldn't find any good resource on the matter.

Here's some code from the start and end of the test开发者_Python百科 watchman:


  @Override
    void starting(FrameworkMethod method) {
        if (testCase.logs) {
            println "===> Fetching logs enabled."
            def commands = []
            pathMap.each {key, value ->
                String host = environmentEnvName.toLowerCase() + key.toString()
                value.each {it ->
                    commands.add "ssh ${user}@${host} tail -f '${it}'"
                }
            }
            println "===> Executing processes"
            commands.each {command ->
                procs.add command.execute()
            }
            println "===> ${procs.size()} processes exceuted"
        }
    }


    @Override
    void finished(FrameworkMethod method) {
        if (procs) {
            println "===> Ready to write files and destroy processes."

            def reportDate = new Date()
            procs?.eachWithIndex {proc, index ->
                def target = String.format("%s/target/${index}-%s.txt", userdir, reportDate.format("HHmm-ddMMyyyy"))
                if(proc.in.text){
                    new File(target).write(proc.in.text)
                }
                proc.destroy()
            }

            println "===> Log exerpts written. Processes destroyed."

        }
    }


Process.getText() and InputSteam.getText() read the input fully before returning and doesn't necessarily return anything if you destroy the process. You can get around this by reading in the output line by line, or just passing the stream to the output file directly:

proc.in.newReader().eachLine { line ->
    // do something with line
}
// or
new File(target) << proc.in

Incidentally, tail -f is usually used interactively, rather than by a program. If you want to set the delta of a log file before and after a test, it would be much simpler to just take the file size before, then reopen the file and seek to the old end and start reading from there.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号