一般getLogger有两种:
1)slf4j的LoggerFactory.getLogger
2) log4j的Logger.getLogger
第一种默认是用logback和logback.xml,如果没有logback的包,他也可以去找log4j。
第二种就是默认用log4j的了。
至于怎么配置slf4j来使用不同的实现,看
https://dzone.com/articles/how-configure-slf4j-different
Using slf4j
with Simple logger
Create a Maven based project and this in your pom.xml
.
Now you may use Logger
in your Java code like this.
The above will get your program compiled, but when you run it, you will see these output.
What it’s saying is that at runtime, you are missing the logging "implementation" (or the logger binding), so slf4j
simply use a "NOP" implmentation, which does nothing. In order to see the output properly, you may try use ansimple implementation that does not require any configuration at all! Just go back to your pom.xml
and add the following:
Now you see logging output on STDOUT with INFO level. This simple logger will default show any INFO level message or higher. In order to see DEBUG messages, you would need to pass in this System Property -Dorg.slf4j.simpleLogger.defaultLogLevel=DEBUG
at your Java startup.
Using slf4j
with Log4j logger
Now we can experiment and swap different logger implementations, but your application code can remain the same. All we need is ot replace slf4j-simple
with another popular logger implementation, such as the Log4j.
Again, we must configure logging per implementation that we picked. In this case, we need ansrc/main/resources/log4j.properties
file.
Re-run your program, and you should see similar output.
Using slf4j
with JDK logger
The JDK actually comes with a logger package, and you can replace pom.xml
with this logger implementation.
Now the configuration for JDK logging is a bit difficult to work with. Not only need a config file, such assrc/main/resources/logging.properties
, but you would also need to add a System properties -Djava.util.logging.config.file=logging.properties
in order to have it pick it up. Here is an example to get you started:
Using slf4j
with Logback logger
The logback logger implementation is a super dupa quality implementation. If you intend to write serious code that go into production, you may want to evaluate this option. Again modify your pom.xml
to replace with this:
Here is a sample of configuration src/main/resources/logback.xml
to get things started.