Add logging to an external pluggable script

扶醉桌前 提交于 2019-12-11 14:37:05

问题


As described in Can't call one closure from another, I am using a pluggable script from within a Grails app.

Unfortunately, I've found that I can't use log4j from within these scripts. I am forced to use println.

I tried using

import org.apache.commons.logging.LogFactory
def Log log = LogFactory.getLog(getClass())

but I got no output. When I print out the result of the call to getClass(), I get something like

myscript$_run_closure5

So I'm thinking the issue is that there is no configuration in my Grails Config.groovy file for this class.

Is there a way for me to programmatically add these pluggable scripts to the log4j configuration? Keep in mind that I do not know in advance what the names of the scripts are, so this has to happen at runtime.


回答1:


Consider the following code:

import org.apache.log4j.Logger

// ...
Logger log = Logger.getLogger('MyPlugin')
new File( grailsApplication.config.externalFiles ).eachFile { file -> 
  Binding binding = new Binding()
  binding.variables.log = log
  GroovyShell shell = new GroovyShell(binding)
  shell.evaluate(file)
  strategies.put( binding.variables.key, binding.variables )
}

Explanation:

  • It is not obligatory to pass class name to getLogger, it can be actually any string. You just need to make sure that this string is matched in log4j.properties of the main program.

  • You pass once created log to plugin scripts via binding variable "log". Then plugin scripts can access it simply as log.info('test123')

My personal recommendation would be to use logback instead of log4j. Both libraries were developed by the same guy and it is stated that logback supersedes log4j.



来源:https://stackoverflow.com/questions/21011234/add-logging-to-an-external-pluggable-script

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!