2

I am trying to use lombok's @Slf4j annotation. It works fine for non-static methods but I am unable to use them for static ones, e.g.:

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class MyClass {

    public static void staticMethod() {
        log.info(""); //build error
        //code
    }

    public void nonStaticMethod() {
        log.info(""); //builds ok
        //code
    }

More specifically the build error is:

Error:(17, 9) java: non-static variable log cannot be referenced from a static context

So either I am missing something or this simply is not the way to do it, but what is causing me some confusion is that other answers seem to indicate that this usage is the correct one. Does anyone know what am I doing wrong? Thank you for your help.

João Matos
  • 6,102
  • 5
  • 41
  • 76
  • but annotaion add static log , do you have additional log member? – Ori Marko Jun 22 '20 at 10:37
  • Looks fine to me, aside from the missing } at the end. The documentation for Lombok explicitly states that `log` is static and final: https://projectlombok.org/api/lombok/extern/slf4j/Slf4j.html so this seems like a bug to me. Have you tried using another Lombok version? Aside from that, you can of course just declare "log" yourself. –  Jun 22 '20 at 10:37
  • I run your code it's not showing any error which version are you using – deadshot Jun 22 '20 at 10:39

1 Answers1

4

Check with Delombok what exactly does lombok generate in your case.

Usually the logger should be a static field.

However there is a configuration:

lombok.log.fieldIsStatic = [true | false] (default: true)

From the documentation: Normally the generated logger is a static field. By setting this key to false, the generated field will be an instance field instead.

Of course if the field is non-static you can't use it from the static method as usual in java

A link to documentation

Mark Bramnik
  • 39,963
  • 4
  • 57
  • 97