2

I'm building Gradle script that runs Tomcat (sadly I cannot use Gretty or Cargo plugin). After launching Tomcat ($TOMCAT_HOME/bin/startup.sh) I want to open file in Gradle/Groovy and then print all lines that comes in, another words: open file, track if smt new has came, print it.

Now my task looks like that:

task startTomcat(dependsOn: ...) << {
    def catalinaOut = "${project.TOMCAT_HOME}/logs/catalina.out"
    delete { catalinaOut }
    exec {
        workingDir '.'
        executable "${project.TOMCAT_HOME}/bin/${tomcatStartScript()}"
        environment CATALINA_OPTS: tomcatArgs.join(' ')
    }
    new File(catalinaOut).eachLine { line -> println(line) }
}

Of course it won't work because new File opens and immediately closes file.

MAGx2
  • 3,149
  • 7
  • 33
  • 63

1 Answers1

3

What you are looking for is basically the behaviour of tail -f <file> on unix. So one obvious way to handle this would just to call this (e.g. ['tail', '-f', '<file>'].execute()) if you have access to this tool.

Otherwise Java IO implementation of unix/linux "tail -f" holds several answers.

So this is a trivial example using apache commons-io Tailer:

buildscript {
        repositories.jcenter()
        dependencies {
                classpath 'commons-io:commons-io:2.4'
        }
}

task tail << {
        def tailer = new org.apache.commons.io.input.Tailer(
                "/tmp/mylog" as File,
                [handle: { String l -> println l }] as org.apache.commons.io.input.TailerListenerAdapter
        )
        try {
                tailer.run()
        }
        finally {
                tailer.stop()
        }
}

Run with gradle tail and add lines to the mentioned file /tmp/mylog. Stop with CTRL-C.

Community
  • 1
  • 1
cfrick
  • 35,203
  • 6
  • 56
  • 68