查了一下,Jetty 好像預設使用 slf4j(如果 classpath 中存在 slf4j 的話)[1]
所以似乎比較建議使用 slf4j 作為 Logger。
實際作法蠻簡單的~在專案的 pom.xml 中加入 slf4j 與 log4j 的相關設定
這裡因為我目前還是想用 log4j 來輸出,因此除了 slf4j-api 外,還放了 slf4j-log4j12 的套件
以讓 slf4j 的 log 得以往 log4j 輸出。
1 2 3 4 5 6 7 8 9 10 |
< dependency > < groupId >org.slf4j</ groupId > < artifactId >slf4j-api</ artifactId > < version >1.7.12</ version > </ dependency > < dependency > < groupId >org.slf4j</ groupId > < artifactId >slf4j-log4j12</ artifactId > < version >1.7.12</ version > </ dependency > |
然後在專案中加入 log4j 的輸出設定 log4j.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<? xml version = "1.0" encoding = "UTF-8" ?> <! DOCTYPE log4j:configuration SYSTEM "http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/xml/doc-files/log4j.dtd"> < appender name = "ConsoleAppender" class = "org.apache.log4j.ConsoleAppender" > < layout class = "org.apache.log4j.PatternLayout" > <!-- param name="ConversionPattern" value='%d{yyyy.MM.dd HH:mm:ss.SSS} %5p (%c.%M) - %m%n' /> --> < param name = "ConversionPattern" value='%d{yyyy-MM-dd HH:mm:ss.SSS} | %p | %c > %m%n' /> </ layout > </ appender > < root > < level value = "DEBUG" /> < appender-ref ref = "ConsoleAppender" /> </ root > </ log4j:configuration > |
最後在程式碼中,使用 slf4j 來寫 log。
這裡因為我實驗的是以 Jersey 為入口,因此直接用 Jersey 的範本程式碼:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Root resource (exposed at "myresource" path) */ @Path ( "/" ) public class MyResource { private static Logger log = LoggerFactory.getLogger( "Test" ); /** * Method handling HTTP GET requests. The returned object will be sent * to the client as "text/plain" media type. * * @return String that will be returned as a text/plain response. */ @GET @Produces (MediaType.TEXT_PLAIN) public String getIt() { log.info( "Test got it for info" ); log.debug( "Test got it for deubg" ); return "Got it!" ; } } |
最後呼叫該函式(用瀏覽器存取該函式對應的 RESTful 網址)時,在 Jetty 上反應出來的 stderrout.log 如下:
1 2 3 4 5 |
2015-10-05 15:59:43.278:INFO:oejs.ServerConnector:main: Started ServerConnector@68c4d1f1{HTTP/1.1,[http/1.1]}{0.0.0.0:9200} 2015-10-05 15:59:43.280:INFO:oejs.ServerConnector:main: Started ServerConnector@42444104{HTTP/1.1,[http/1.1]}{0.0.0.0:9300} 2015-10-05 15:59:43.281:INFO:oejs.Server:main: Started @5379ms 2015-10-05 16:00:06.878 | INFO | Test > Test got it for info 2015-10-05 16:00:06.878 | DEBUG | Test > Test got it for deubg |
參考資料:
沒有留言:
張貼留言