logger代码
使用slf4j-api提供的统一接口(来自logback官网http://logback.qos.ch/xref/chapters/introduction/HelloWorld1.html)
package chapters.introduction; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class HelloWorld1 { public static void main(String[] args) { Logger logger = LoggerFactory.getLogger("chapters.introduction.HelloWorld1"); logger.debug("Hello world."); } }
logger配置:logback.xml
<?xml version="1.0" encoding="UTF-8"?> <configuration> <!-- 定义日志输出格式 --> <property name="LOG_PATTERN" value="%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36}[%line] - %msg%n" /> <!-- 输出到滚动文件 --> <appender name="ACCESS" class="ch.qos.logback.core.rolling.RollingFileAppender"> <!-- 文件名 --> <File>/tmp/log/api/access.log</File> <!-- 配置基于时间的滚动策略 --> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <!-- 滚动时间周期是从fileNamePattern推断出来的 --> <!-- 比如格式:{yyyy-MM-dd}表示按天滚动;{yyyy-MM-dd_HH}表示按小时滚动 --> <fileNamePattern>/tmp/log/api/access.%d{yyyy-MM-dd}.log</fileNamePattern> <!-- 保留历史日志数量 --> <maxHistory>7</maxHistory> </rollingPolicy> <encoder> <pattern>${LOG_PATTERN}</pattern> </encoder> </appender> <appender name="DEBUG_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender"> <File>/tmp/log/api/debug.log</File> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <fileNamePattern>/tmp/log/api/debug.%d{yyyy-MM-dd}.log</fileNamePattern> <maxHistory>7</maxHistory> </rollingPolicy> <encoder> <pattern>${LOG_PATTERN}</pattern> </encoder> </appender> <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender"> <encoder> <pattern>${LOG_PATTERN}</pattern> </encoder> </appender> <logger name="com.xqb.api.commons.GlobalExceptionHandler" level="DEBUG"/> <!-- 特定日志使用指定的appender --> <logger name="org.springframework.web.servlet.DispatcherServlet" additivity="false" level="DEBUG"> <appender-ref ref="ACCESS"/> </logger> <logger name="org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor" additivity="false" level="DEBUG"> <appender-ref ref="ACCESS"/> </logger> <logger name="org.springframework.jdbc.core" level="TRACE"/> <logger name="org.hibernate.type.descriptor.sql.BasicBinder" level="TRACE"/> <logger name="org.hibernate.SQL" level="DEBUG"/> <root level="INFO"> <!-- 启用的appender列表 --> <!-- The ACCESS appender 不用加了,因为在定义DispatcherServlet logger时已经使用过 --> <appender-ref ref="CONSOLE"/> <appender-ref ref="DEBUG_FILE"/> </root> </configuration>
依赖包
slf4j-api.jar
logback-core.jar
logback-classic.jar
maven配置:
<dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${slf4j-version}</version> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.1.2</version> </dependency>
时间: 2024-10-11 04:46:23