###Java日志组件java
Java日志API由三个核心组件组成web
Loggers:Logger负责捕捉事件并将其发送给合适的Appender。apache
Appenders:也被称为Handlers,负责将日志事件记录到目标位置。在将日志事件输出以前,Appenders使用Layouts来对事件进行格式化处理。app
Layouts:也被称为Formatters,它负责对日志事件中的数据进行转换和格式化。Layouts决定了数据在一条日志记录中的最终形式。dom
###日志抽象层maven
###日志实现测试
###采用slf4j + log4j2 做为日志组件url
maven 配置spa
<!--log config log4j 2 + slf4j--> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-web</artifactId> <version>${log4j.version}</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-slf4j-impl</artifactId> <version>${log4j.version}</version> </dependency>
web 配置日志
<!-- log4j2-begin web3.0 针对web3.0的配置--> <context-param> <param-name>isLog4jAutoInitializationDisabled</param-name> <param-value>true</param-value> </context-param> <!-- log4j2-begin web2.0 针对web2.0的配置--> <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>
贴一个log4j2的配置
<?xml version="1.0" encoding="UTF-8"?> <Configuration status="off" monitorInterval="1800"> <properties> <property name="LOG_HOME">${web:rootDir}/log</property> <property name="FILE_NAME">mylog</property> </properties> <Appenders> <Console name="Console" target="SYSTEM_OUT"> <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" /> </Console> <!--文件会打印出全部信息,这个log每次运行程序会自动清空,由append属性决定,这个也挺有用的,适合临时测试用--> <File name="log" fileName="${LOG_HOME}/test.log" append="false"> <PatternLayout pattern="%d{HH:mm:ss.SSS} %-5level %class{36} %L %M - %msg%xEx%n"/> </File> <!--这个会打印出全部的信息,每次大小超过size,则这size大小的日志会自动存入按年份-月份创建的文件夹下面并进行压缩,做为存档--> <RollingRandomAccessFile name="RollingFile" fileName="${LOG_HOME}/${FILE_NAME}.log" filePattern="${LOG_HOME}/$${date:yyyy-MM}/${FILE_NAME}-%d{yyyy-MM-dd}-%i.log.gz"> <PatternLayout pattern="%date{yyyy-MM-dd HH:mm:ss.SSS} %level [%thread][%file:%line] - %msg%n" /> <Policies> <TimeBasedTriggeringPolicy /> <SizeBasedTriggeringPolicy size="10 MB" /> </Policies> <DefaultRolloverStrategy max="20" /> </RollingRandomAccessFile> </Appenders> <Loggers> <Root level="trace"> <AppenderRef ref="Console" /> <AppenderRef ref="RollingFile" /> <AppenderRef ref="log" /> </Root> </Loggers> </Configuration>