目前市面中使用的大多數是spring boot項目,下面我說的方案sring也適用。
在這裏給你們推薦一套目前 最火的Java後端日誌框架方案:
門戶日誌用:slf4j
日誌實現用:log4j2java
具體的配置或者優化以下詳情
一、導入依賴
log4j2應儘可能使用同一版本,不然可能出現不兼容的狀況web
// log升級配置 compile('org.apache.logging.log4j:log4j-1.2-api:2.9.1') compile('org.apache.logging.log4j:log4j-web:2.9.1') compile('org.apache.logging.log4j:log4j-core:2.9.1') compile('org.apache.logging.log4j:log4j-api:2.9.1') // log // compile('log4j:log4j:1.2.17') compile('org.slf4j:slf4j-api:1.6.6') compile('org.slf4j:slf4j-log4j12:1.7.21')
二、建立log4j2.properties
(若是有log4j.properties要刪除的)
(下面還有一種使用log4j.xml的方法,兩種任選其一,如今是傾向於用xml)spring
status = warn name = MyApp #指定輸出源‘類型’爲控制檯 appender.console.type = Console appender.console.name = consoleLogDemo appender.console.filter.threshold.type = ThresholdFilter appender.console.filter.threshold.level = debug appender.console.layout.type = PatternLayout appender.console.layout.pattern = [%-5p] [%d{yyyy-MM-dd HH:mm:ss}] [%C{1}:%M:%L] %m%n appender.console.target = System_out appender.rolling.type = RollingFile appender.rolling.name = fileLogDemo appender.rolling.filter.threshold.type = ThresholdFilter appender.rolling.filter.threshold.level = info appender.rolling.layout.type = PatternLayout appender.rolling.layout.pattern = [%-5p] [%d{yyyy-MM-dd HH:mm:ss}] [%C{1}:%M:%L] %m%n appender.rolling.append = true appender.rolling.fileName =/data/logs/workflow/web.log appender.rolling.filePattern=/data/logs/wokflow/web.log.%d{yyyy-MM-dd} appender.rolling.policies.type = Policies appender.rolling.policies.time.type = TimeBasedTriggeringPolicy appender.rolling.policies.time.interval = 2 appender.rolling.policies.time.modulate = true appender.rolling.policies.size.type = SizeBasedTriggeringPolicy appender.rolling.policies.size.size=100MB appender.rolling.strategy.type = DefaultRolloverStrategy appender.rolling.strategy.max = 5 logger.rolling.name = com.XXX logger.rolling.level = info logger.rolling.additivity = false logger.rolling.appenderRef.rolling.ref = fileLogDemo #指明根級日誌的級別 rootLogger.level = info #指定哪些appender輸出源是根級日誌的輸出級別 rootLogger.appenderRef.consolelogdemo.ref = consoleLogDemo rootLogger.appenderRef.filelogdemo.ref = fileLogDemo
三、log4j2.xmlsql
<?xml version="1.0" encoding="UTF-8"?> <!-- 日誌級別按照從低到高爲:ALL < TRACE < DEBUG < INFO < WARN < ERROR < FATAL < OFF --> <!--status="WARN" :用於設置log4j2自身內部日誌的信息輸出級別,默認是OFF--> <Configuration status="WARN" monitorInterval="30"> <!--自定義一些常量,以後使用${變量名}引用--> <properties> <property name="LOG_PATH">D:/logs</property> <property name="PATTERN" value="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] [%l] %p - %m%n%n"/> <property name="INFO_LOG">info</property> <property name="DEBUG_LOG">debug</property> <property name="ERROR_LOG">error</property> </properties> <!--appenders:定義輸出內容,輸出格式,輸出方式,日誌保存策略等,經常使用其下三種標籤[console,File,RollingFile]--> <Appenders> <Console name="Console" target="SYSTEM_OUT"> <ThresholdFilter level="DEBUG" onMatch="ACCEPT" onMismatch="DENY"/> <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" /> </Console> <RollingFile name="DebugAppender" fileName="${LOG_PATH}/${DEBUG_LOG}.log" filePattern="${LOG_PATH}/$${date:yyyy-MM}/debug-%d{yyyy-MM-dd}-%i.log" immediateFlush="true"> <!--控制檯只輸出level及以上級別的信息(onMatch),其餘的直接拒絕(onMismatch)--> <Filters> <ThresholdFilter level="INFO" onMatch="DENY" onMismatch="NEUTRAL"/> <ThresholdFilter level="DEBUG" onMatch="ACCEPT" onMismatch="DENY"/> </Filters> <PatternLayout pattern="${PATTERN}" /> <Policies> <TimeBasedTriggeringPolicy /> <SizeBasedTriggeringPolicy size="10 MB" /> </Policies> <!-- DefaultRolloverStrategy屬性如不設置,則默認爲最多同一文件夾下7個文件,這裏設置了20 --> <DefaultRolloverStrategy max="20" /> </RollingFile> <RollingFile name="InfoAppender" fileName="${LOG_PATH}/${INFO_LOG}.log" filePattern="${LOG_PATH}/$${date:yyyy-MM}/info-%d{yyyy-MM-dd}-%i.log" immediateFlush="true"> <!--控制檯只輸出level及以上級別的信息(onMatch),其餘的直接拒絕(onMismatch)--> <Filters> <ThresholdFilter level="WARN" onMatch="DENY" onMismatch="NEUTRAL" /> <ThresholdFilter level="INFO" onMatch="ACCEPT" onMismatch="DENY"/> </Filters> <PatternLayout pattern="${PATTERN}" /> <Policies> <TimeBasedTriggeringPolicy /> <!-- SizeBasedTriggeringPolicy :文件大小滾動策略--> <SizeBasedTriggeringPolicy size="10 MB" /> </Policies> <!-- DefaultRolloverStrategy屬性如不設置,則默認爲最多同一文件夾下7個文件,這裏設置了20 --> <DefaultRolloverStrategy max="20" /> </RollingFile> <RollingFile name="ErrorAppender" fileName="${LOG_PATH}/${ERROR_LOG}.log" filePattern="${LOG_PATH}/$${date:yyyy-MM}/error-%d{yyyy-MM-dd}-%i.log" immediateFlush="true"> <!--控制檯只輸出level及以上級別的信息(onMatch),其餘的直接拒絕(onMismatch)--> <Filters> <ThresholdFilter level="WARN" onMatch="ACCEPT" onMismatch="DENY"/> </Filters> <PatternLayout pattern="${PATTERN}" /> <Policies> <TimeBasedTriggeringPolicy /> <SizeBasedTriggeringPolicy size="10 MB" /> </Policies> <!-- DefaultRolloverStrategy屬性如不設置,則默認爲最多同一文件夾下7個文件,這裏設置了20 --> <DefaultRolloverStrategy max="20" /> </RollingFile> </Appenders> <!--定義logger,只有定義了logger並引入的appender,appender纔會生效--> <Loggers> <!--Logger節點用來單獨指定日誌的形式,name爲包路徑,好比要爲org.springframework包下全部日誌指定爲ERROR級別等。 --> <logger name="org.apache.ibatis" additivity="false" level="ERROR" /> <logger name="org.apache.shiro" additivity="false" level="ERROR" /> <logger name="net.sf.ehcache" additivity="false" level="ERROR" /> <logger name="org.apache.commons" additivity="false" level="ERROR" /> <logger name="org.mybatis.spring" additivity="false" level="ERROR" /> <logger name="java.sql" additivity="false" level="ERROR" /> <logger name="org.springframework" additivity="false" level="ERROR" /> <logger name="com.alibaba.druid.filter.stat" additivity="false" level="WARN" /> <logger name="com.alibaba.druid.pool" additivity="false" level="WARN" /> <logger name="druid.sql.Connection" additivity="false" level="WARN" /> <logger name="druid.sql.DataSource" additivity="false" level="WARN" /> <logger name="druid.sql.ResultSet" additivity="false" level="WARN" /> <logger name="druid.sql.Statement" additivity="false" level="WARN" /> <!-- Root節點用來指定項目的根日誌,若是沒有單獨指定Logger,那麼就會默認使用該Root日誌輸出 --> <Root level="INFO"> <AppenderRef ref="Console" /> <AppenderRef ref="DebugAppender" /> <AppenderRef ref="InfoAppender" /> <AppenderRef ref="ErrorAppender" /> </Root> </Loggers> </Configuration>
若是你的項目中使用的是老的框架,使用的是web.xml,那還要去修改
四、修改web.xmlapache
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5"> <!--日誌升級開始--> <listener> <listener-class>org.apache.logging.log4j.web.Log4jServletContextListener</listener-class> </listener> <filter> <filter-name>log4jServletFilter</filter-name> <filter-class>org.apache.logging.log4j.web.Log4jServletFilter</filter-class> </filter> <filter-mapping> <filter-name>log4jServletFilter</filter-name> <url-pattern>/*</url-pattern> <dispatcher>REQUEST</dispatcher> <dispatcher>FORWARD</dispatcher> <dispatcher>INCLUDE</dispatcher> <dispatcher>ERROR</dispatcher> </filter-mapping> <context-param> <param-name>log4jContextName</param-name> <param-value>myApplication</param-value> </context-param> <context-param> <param-name>log4jConfiguration</param-name> <param-value>classpath:log4j2.properties</param-value> </context-param> <!--日誌升級結束-->
在web.xml中移除舊的log4j.property的配置後端
<context-param> <param-name>log4jConfigLocation</param-name> <param-value>classpath:log4j.properties</param-value> </context-param>
五、log4j2測試
使用的LogManager.getLogger(Object.class)方式獲取對象api
加入測試類,並運行。如在項目磁盤目錄下正常輸出日誌內容則說明log4j2添加成功mybatis
public class TestLogger { private static final Logger log = LoggerFactory.getLogger(TestLogger.class); public static void main(String[] args) { int num=10; log.info("8888888888888888Info : numis " + num); log.warn("8888888888888888Warning : numis " + num); log.debug("8888888888888888Debug : numis " + num); log.error("8888888888888888Error : numis " + num); } }