3

I'm using SLF4J with Log4J underneath. What access levels should I be setting my loggers to?

static final Logger logger = LoggerFactory.getLogger(ClassName.class);
James McMahon
  • 48,506
  • 64
  • 207
  • 283

2 Answers2

12

I think you should use private access level, because every class should have its own copy of logger. Otherwise we can't tell which class really did the log record.

Ivan Nevostruev
  • 28,143
  • 8
  • 66
  • 82
  • Makes sense, I ask because the SLF4J documentation left off the access modifier, so I didn't know if there were situations where you needed other classes to access the logger. – James McMahon Oct 09 '09 at 19:30
  • Classes internal to the logging system may need to, but they maintain their own references anyway. – David Berger Oct 09 '09 at 19:34
2

I always set them to private. Is there any reason any other class would need access to this logger?

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
  • 2
    I've seen some people that will design superclasses in a way that a logger is exposed to the child classes – matt b Oct 09 '09 at 19:54
  • I've actually done that Matt, protected access makes sense to me in that case. – James McMahon Oct 09 '09 at 20:03
  • @matt b: I've never seen that before. I'll have to try it out to see what it does to the log record. – Bill the Lizard Oct 09 '09 at 20:08
  • 2
    `protected`? that's hideous. `protected static` is always a mistake. – Tom Hawtin - tackline Oct 09 '09 at 20:11
  • You'll see that sometimes in frameworks like Spring, where you might extend one of their controllers or DaoSupport classes. The loggers will be declared as protected final Logger log = LogManager.getLogger(this.getClass()), so that they'll be the runtime class's type. – matt b Oct 09 '09 at 20:45
  • @matt b, yeah that is exactly what I was doing. For protected loggers I don't use static. – James McMahon Oct 09 '09 at 22:12