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

时间:2010-04-05 08:58:37

标签: 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
    }

}

我是否需要添加导入声明?我需要添加什么?请注意,该类位于src / groovy / org / utils中。我知道'log'变量可以在控制器,服务等中访问。在'src'类中不确定。

感谢。

5 个答案:

答案 0 :(得分: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方法。

答案 1 :(得分:5)

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

import groovy.util.logging.Slf4j

@Slf4j
class MyUtil {

答案 2 :(得分:3)

日志变量由grails注入,因此仅在grails特定的类中可用,如控制器,服务等 - 我认为你不能以任何方式“导入”它。

在这些课程之外,你只需要“定期”使用log4j,即

Logger.getLogger(MyClass.class).debug()

答案 3 :(得分:0)

Log4j是groovy

的最佳日志记录之一
import groovy.util.logging.Log4j

@Log4j
public class MyClass{
//Use for logger check
public static void myMethod(){
    //log.error(null, "This is the log message", throwable)

    //log.error(null, "This is the log message", throwable)

    //log.info("This is the message for info")

    //log.debugg("This is the message for debugging")
}
}

<强> Log4j.properties

# Define the root logger with appender file
log =folderpath
log4j.rootLogger=INFO, R, stdout

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout

# Pattern to output the caller's file name and line number.
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
# %d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%C:%L [%t]  - %m%n

log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=${log}/filename.log

log4j.appender.R.MaxFileSize=2048KB
# Keep one backup file
log4j.appender.R.MaxBackupIndex=1
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern="%d %5p %c{1}:%L - %m%n"
# %d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%C:%L [%t]  - %m%n

# Direct log messages to stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

希望它能帮到你......

答案 4 :(得分:0)

我在grails 3.1.8中使用了Logback。

import org.apache.commons.logging.LogFactory

public class MyClass{

   static final LOG = LogFactory.getLog(this)

   def function(){
     LOG.debug "Debug message"
   }

   static staticFunction(){
     LOG.debug "Another debug message"
   }
}
相关问题