如何在 Java 程式碼中使用 Log4j
首先需要建立一個 final static logger
物件:
final static Logger logger = Logger.getLogger(classname.class);
然後,呼叫日誌記錄方法:
//logs an error message
logger.info("Information about some param: " + parameter); // Note that this line could throw a NullPointerException!
//in order to improve performance, it is advised to use the `isXXXEnabled()` Methods
if( logger.isInfoEnabled() ){
logger.info("Information about some param: " + parameter);
}
// In log4j2 parameter substitution is preferable due to readability and performance
// The parameter substitution only takes place if info level is active which obsoletes the use of isXXXEnabled().
logger.info("Information about some param: {}" , parameter);
//logs an exception
logger.error("Information about some error: ", exception);