问题
I am simply trying to print the content of the latest log file inside the logs directory from Grails. command.execute().text is returning empty. so I must be doing something wrong. I appreciate any help! Thanks!
def command = "cat \$(ls logs/localhost_access_log* | tail -1)"
println command.execute().text
回答1:
ServletContextHolder.servletContext.getRealPath('/')
will kind of help although thats the pah to the running app. You may need to do
some verification of path before attempting to get logs (untested)
path=ServletContextHolder.servletContext.getRealPath('/')
println "--- path is ${path}"
command = "cd $path && cat \$(ls ../logs/localhost_access_log* | tail -1)"
回答2:
instead of making a complex cmdline string, why not just program it with the groovy/java tools?
// find real directory of logs folder
def dir = new File(ServletContextHolder.servletContext.getRealPath('logs'))
// inside logs folder look for newest file beginning with "localhost_access"
def file = dir.listFiles({ name -> name.startsWith('localhost_access') } as FilenameFilter).max({ it.lastModified() })
def content = null
if (file) {
// read content directly
def content = file.text
// or via a process
def content = new ProcessBuilder('cat', file.absolutePath).start().text
}
来源:https://stackoverflow.com/questions/39448016/how-to-access-a-file-inside-logs-directory-from-grails-application