我怎样才能在src/groovy/class中使用'log'

fir*_*iel 15 grails log4j

我遇到了这个错误:

groovy.lang.MissingPropertyException:没有这样的属性:类的日志:org.utils.MyClass

这是班级的内容:

package org.utils

class MyClass {
    int organizationCount = 0

    public int getOrganizationCount(){
        log.debug "There are ${organizationCount} organization(s) found."
        return organizationCount
    }

}
Run Code Online (Sandbox Code Playgroud)

我需要添加一个import语句吗?我需要添加什么?请注意,该类位于src/groovy/org/utils中.我知道'log'变量可以在控制器,服务等中访问.在'src'类中不确定.

谢谢.

Dan*_*dio 7

在Groovy 1.8中,您也可以使用@Log(对于java.util.logging)或@Log4j(对于log4j)来注释该类,并且它将"神奇地"具有log属性.有关详细信息,请参阅http://docs.codehaus.org/display/GROOVY/Groovy+1.8+release+notes#Groovy1.8releasenotes-@Log.

PS.:如果使用java.util.logging,log.debug调用仍然会失败,因为没有debug方法.


Rya*_*ote 6

在grails 3中,默认日志记录系统是logback.只需将@ Slf4j注释添加到src/groovy类中即可.

import groovy.util.logging.Slf4j

@Slf4j
class MyUtil {
Run Code Online (Sandbox Code Playgroud)


Mic*_*rdt 3

日志变量是由 grails 注入的,因此只能在特定于 grails 的类(如控制器、服务等)中使用 - 而且我认为您不能以任何方式“导入”它。

在这些类之外,您只需“定期”使用 log4j,即

Logger.getLogger(MyClass.class).debug()
Run Code Online (Sandbox Code Playgroud)