2009-11-19 8 views
1

Grails가 Log4J를 설정하기 위해 버전 1.1에서 도입 한 DSL에 반복적으로 문제가있었습니다. 내 현재의 구성은 다음과 같습니다Grails log4j configuration

log4j = {   
    debug 'com.mypackages' 

    appenders { 
     console name: 'stdout', layout: pattern(conversionPattern: '%d{dd-MM-yyyy HH:mm:ss,SSS} %5p %c{1} - %m%n') 
     rollingFile name: 'hibeFile', file: "hibeFile", maxFileSize: '500KB' 
    } 

    // By default, messages are logged at the error level to both the console and hibeFile 
    root { 
     error 'stdout', 'hibeFile' 
     additivity = true 
    } 
} 

여기 의도는 다음과 같습니다

  • 디버그 수준에서 로그인 com.mypackages 및 오류 수준
  • 로그인 hibeFile라는 이름의 파일에 대한 모든 출력에서 ​​모든 다른 사람과 콘솔

응용 프로그램 또는 통합 테스트를 실행할 때 제대로 작동합니다. 그러나 단위 테스트를 실행할 때 콘솔이나 Grails 테스트 보고서에 표시된 "System.out"또는 "System.err"링크에 로깅이 나타나지 않습니다. 단위 테스트를 실행할 때 내 로그를 보려면 어떻게해야합니까? Grails의 단위 테스트를 실행할 때 돈

답변

2

AFAIK은 전체 로깅 log4j를 통해 사용할 수 없습니다

덕분에,, 등의 도메인 클래스의 log.xxxx 호출은 사용 조롱하는

mockLogging(ClassUnderTest, true) 

"true"는 "디버그 사용"의 약자입니다. 그렇게하기 위해서 단위 테스트 클래스는 GrailsUnitTestCase를 확장해야합니다. mockController (클래스)를 사용하면 암시 적으로 mockLogging (class, false)가 호출되므로 디버그 로깅을 사용할 수 없습니다. 자세한 내용은 grails 소스, 특히 GrailsUnitTestCase 및 MockUtils를 확인하십시오.

위에서 반대로 통합 테스트에서 전체 기계가 시작되고 log4j를 사용할 수 있습니다.

+0

로깅 문으로 흩어져있는 컨트롤러를 어떻게 테스트합니까? 나는 지금이 문제가있다 ?? –

+0

테스트의 setUp() 메소드에서 mockLogging (MyDamnCoolCOntroller, true)을 사용하십시오. –

1

여기에 생각해 보았지만 정확히 묻지는 않았지만 grails 사용자 그룹에서 같은 질문을했습니다. 나는 지식을 전파하기 위해 나의 대답을 게시하고있다.

grails 사용자 그룹에서 설명한 것처럼 종속성 삽입에 의존하지 않고 클래스에서 def log = org.apache.commons.logging.LogFactory.getLog (this)를 명시 적으로 말하면 getLog를 LogFactory.

아래는 grails.tests.MockUtils.mockLogging에서 가져 와서 로거를 반환하도록 수정되었습니다. Grails의 1.1.1 및 설치에 대한 근사치를 사용

class LoggingEnabledTestCase extends GrailsUnitTestCase { 
protected void setUp() { 
     super.setUp() 
     registerMetaClass(org.apache.commons.logging.LogFactory) 
     org.apache.commons.logging.LogFactory.metaClass.'static'.getLog = {instance -> 

      // This is taken from grails.tests.MockUtils and slightly changed to return a logger. 

      // Get the name of the class + the last component of the package 
      // (if it the class is in a package). 
      def pos = instance.class.name.lastIndexOf('.') 
      if (pos != -1) pos = instance.class.name.lastIndexOf('.', pos - 1) 
      def shortName = instance.class.name.substring(pos + 1) 

      // Dynamically inject a mock logger that simply prints the 
      // log message (and optional exception) to stdout. 
      def mockLogger = [ 
        fatal: {String msg, Throwable t = null -> 
         println "FATAL (${shortName}): $msg" 
         if (t) { 
          println "  Exception thrown - ${t.message}" 
         } 
        }, 
        error: {String msg, Throwable t = null -> 
         println "ERROR (${shortName}): $msg" 
         if (t) { 
          println "  Exception thrown - ${t.message}" 
         } 
        }, 
        warn: {String msg, Throwable t = null -> 
         println "WARN (${shortName}): $msg" 
         if (t) { 
          println "  Exception thrown - ${t.message}" 
         } 
        }, 
        info: {String msg, Throwable t = null -> 
         println "INFO (${shortName}): $msg" 
         if (t) { 
          println "  Exception thrown - ${t.message}" 
         } 
        }, 
        debug: {String msg, Throwable t = null -> 
         println "DEBUG (${shortName}): $msg" 
         if (t) { 
          println "  Exception thrown - ${t.message}" 
         } 
        }, 
        trace: {String msg, Throwable t = null -> }, 
        isFatalEnabled: {-> true}, 
        isErrorEnabled: {-> true}, 
        isWarnEnabled: {-> true}, 
        isInfoEnabled: {-> true}, 
        isDebugEnabled: {-> true}, 
        isTraceEnabled: {-> false}] as Log 
      return mockLogger 
     } 
    } 

    protected void tearDown() { 
     super.tearDown() 
    } 
} 
0

, 내가 단위 테스트가 grails test-app를 실행 한 후 FooTests.groovy

라는이, 나는 디렉토리에있는 테스트의 출력을 볼 수 있어요 :

TEST-com.mypackages.FooTests-err.txt 
TEST-com.mypackages.FooTests-out.txt 
TEST-com.mypackages.FooTests.txt 
: 적절한 구체적 파일
./test/reports/plain 

,

hibeFile에 출력이 표시되지 않습니다. 확신 할 수는 없지만 유닛 테스트에서 로깅 설정을 수신하지 못한다는 점에서 이전 포스터가 정확하다고 판단됩니다.