Skip to content

Bad practice - defining logger in superclass  #28

@paul-lysak

Description

@paul-lysak

As documentation of scalalogging suggests, in order to use its macros
capabilities one should mix in Logging or StrictLogging trait.
But with such approach logger instance is attached not to the class that
really writes something to log, but to class of the current instance.
Therefore user looses ability to precisely configure which messages
write to log and which no.
Let me illustrate it with following code: https://gist.github.com/paul-lysak/6168137#file-loggerdemo-scala

SuperClassA/SubClassA hierarchy is extended from Logging trait,
and SuperClassB/SubClassB directly uses SLF4J with manual logger instantiation.
Consider following log4j.properties config file:

log4j.rootLogger=WARN, stdout
log4j.logger.SubClassA=INFO
log4j.logger.SubClassB=INFO
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d [%t] %-5p %c - %m%n

It basically says that subclasses should display log messages up to INFO level,
while all others - only WARN. We aren't interested in INFO and so on - suppose
superclasses are from some framework and we don't care about its internals.

Now let's look at the output:

2013-08-06 22:35:27,311 [main] INFO  SubClassA - Hi, SuperClassA
2013-08-06 22:35:27,312 [main] INFO  SubClassA - Hi, SubClassA
2013-08-06 22:35:27,312 [main] INFO  SubClassB - Hi, SubClassB

Configuration worked as expected for B hierarchy (with manual logger instantiation) but it failed for hierarchy A (extended from Logging).

I really like how you managed to avoid redundant if()s with macros but I think that 2 things should be done:

  1. Give convenient way to use the features without subclassing - for example, via custom LoggerFactory. Of course we can write all this "Logger(LoggerFactory getLogger getClass.getName)", but it's 7 letters longer than direct using of underlying logger library :)
  2. Indicate in the documentation caveats of subclassing from Logging trait

Thanks!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions