Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.2k views
in Technique[技术] by (71.8m points)

Replace java platform system logger with slf4j in spring boot application

I've got a spring boot application build as multi-modular gradle project (old-style, not fancy jigsaw)

What I want to achieve - is replace java platform loggers (e.g., SSlLogger/ System.getLogger) with sl4j & logback that are used in my app and are managed by spring-boot-admin server at runtime. I need all my loggers to write to file instead of console - or else I won't see logs in Logz.io. I do not control how my app is deployed, but I control the way fat jar is built (so, manuals with terminal commands 'java - ...' are not very helpful :( )

I started to follow https://www.baeldung.com/java-9-logging-api guide, but got stuck.

for simplicity, my structure is ->

build.gradle
    /application-module
        build.gradle (combines 3 other modules)
        /src /...
    /rest-module
        build.gradle
        /src /...
    /service-module
        build.gradle
        /src /... 
    /persistency-module
        build.gradle
        /src /... 

So, I want to add one more module

/log-module
    /src -> with actual classes 
         module-info.java
         Slf4jLogger implements System.Logger 
         Slf4jLoggerFinder extends System.LoggerFinder

and include it into my application-module

but when trying to build it all, I get 'error: module not found: org.slf4j', and app is not build.

So, what am I doing wrong? What additional plugins/config do I need? And will it even allow me to achieve my goal?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Okay, I managed to find the solution. It's a combination of

https://www.baeldung.com/java-9-logging-api

https://www.baeldung.com/java-spi

So, I don't even needed jigsaw modules - only the JDK's service provider mechanism

So, in fact you need 3 files [these are id's of pastebin's samples; but they are almost the same as in the java-9-logging-api article]

  • AkXY3zgu -> adapter class
  • YFUkZwat -> logger provider
  • CD6NNibj -> meta-inf file - and that's the trickiest part (with file name :) )

file name -> META_INF/services/java.lang.System$LoggerFinder

com.my-projects.commons.logs.Slf4jLoggerFinder

An now on regular app startup system logger will be replaced with slf4j-adapter. But still, check how system logger is created -> for example, I mostly need SSLLogger, and there is some system-prop-based logic there...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...