在單獨類的main函式中使用log4j記錄日誌
阿新 • • 發佈:2018-12-17
背景
自己的測試類,平時都是用System.out.println();
列印輸出資訊。一直不會在單個類中,使用log4j列印日誌資訊,故,做此嘗試。
做法
我這裡引用lombook
的jar包,因為lombook
中有@Slf4j
註解
<dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.16.18</version> <scope>provided</scope> </dependency>
測試程式碼寫法
import lombok.extern.slf4j.Slf4j; import org.apache.log4j.BasicConfigurator; /** * @author Wayss. * @date 2018/8/7. */ @Slf4j public class TestMain { public static void main(String[] args) { BasicConfigurator.configure(); try { tests("some string"); } catch (Exception e) { log.error("tests方法拋異常了", e); } } public static boolean tests(Object object) throws Exception { Exception exception = new Exception("自定義異常內容"); System.out.println(exception); System.out.println(exception.getMessage()); System.out.println(exception.toString()); throw exception; } }
log4j.properties配置檔案資訊。
# Set root logger level to DEBUG and its only appender to A1. log4j.rootLogger=DEBUG, A1 # A1 is set to be a ConsoleAppender. log4j.appender.A1=org.apache.log4j.ConsoleAppender # A1 uses PatternLayout. log4j.appender.A1.layout=org.apache.log4j.PatternLayout log4j.appender.A1.layout.ConversionPattern=%r %d{yyyy-MM-dd HH\:mm\:ss} %c %p -%m%n
問題: