grails / grails-core

The Grails Web Application Framework
http://grails.org
Apache License 2.0
2.79k stars 949 forks source link

Problem With log Property From Static Context #10969

Open jeffscottbrown opened 6 years ago

jeffscottbrown commented 6 years ago
class DemoService {

    static void someMethod() {
       log.error 'This is an error message'
    }
}

That code won't compile...

/Users/jeffbrown/logdemo/grails-app/services/logdemo/DemoService.groovy: 6: Apparent variable 'log' was found in a static scope but doesn't refer to a local variable, static field or class. Possible causes:
You attempted to reference a variable in the binding or an instance variable from a static context.
You misspelled a classname or statically imported field. Please check the spelling.
You attempted to use a method 'log' but left out brackets in a place not allowed by the grammar.
 @ line 6, column 9.
           log.error 'This is an error message'
           ^

This does compile...

class DemoService {

    static void someMethod() {
        DemoService.log.error 'This is an error message'
    }
}

Another way to make this work is to mark the class with @Slf4j.

It is a little unusual to have static methods in a Grails artifact like this, but it probably should be allowed to work.

graemerocher commented 6 years ago

@Slf4j is the default for 3.3 I believe

jeffscottbrown commented 6 years ago

@Slf4j is the default for 3.3 I believe

That is true, but the code below won't compile with 3.3.3 unless @Slf4j is explicitly added the class...

class DemoService {

    static void someMethod() {
        log.error 'This is an error message'
    }
}
jeffscottbrown commented 3 years ago

FYI... The project at github.com/jeffbrown/issue10969 indicates this is still a problem with Grails 4.0.9.

grails-app/services/issue10969/DemoService.groovy

package issue10969

import groovy.util.logging.Slf4j

// https://github.com/grails/grails-core/issues/10969
//
// Adding the @Slf4j annotation allows the code to compile.
//
//@Slf4j
class DemoService {

    static void someMethod() {
        log.error 'This is an error message'
    }
}
jeffscottbrown commented 1 day ago

FYI... I have verified this phenomenon still exists in Grails 6.2.1. Without the @Slf4j annotation the log property really is added to the class, like this...

private static final transient Logger log

I am only speculating but I suspect that the log property is being added too late for a static method in the class to reference it.