1、创建maven项目
使用idea快速便捷创建maven项目
2、引入jar包依赖(坐标)
在maven项目的pom文件加入一下的依赖。
<!-- logback日志依赖-->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.11</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>1.2.11</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.36</version>
</dependency>
3、添加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 | %msg%n"/>
<!--设置日志文件路径-->
<property name="LOG_DIR" value="C:\\Users\\86130\\Desktop\\info"/>
<!-- C:\Users\86130\Desktop-->
<!--输出到控制台-->
<appender name="CONSOLE-LOG" class="ch.qos.logback.core.ConsoleAppender">
<!--设置打印日志文字的颜色-->
<target>System.out</target>
<layout class="ch.qos.logback.classic.PatternLayout">
<pattern>${LOG_PATTERN}</pattern>
</layout>
</appender>
<!--输出到文件-->
<appender name="FILE-LOG" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!--设置过滤器过滤ERROR级别的日志-->
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>ALL</level><!--设置输出到文件日志的类型、级别-->
<onMatch>DENY</onMatch>
<onMismatch>ACCEPT</onMismatch>
</filter>
<encoder>
<pattern>${LOG_PATTERN}</pattern>
</encoder>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${LOG_DIR}/%d.log</fileNamePattern>
<maxHistory>30</maxHistory>
</rollingPolicy>
</appender>
<!--错误日志设置-->
<appender name="ERROR_LOG" class="ch.qos.logback.core.rolling.RollingFileAppender">
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>ERROR</level>
</filter>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<FileNamePattern>${LOG_DIR}/error.%d{yyyy-MM-dd}.log</FileNamePattern>
<MaxHistory>30</MaxHistory>
</rollingPolicy>
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<pattern>${LOG_PATTERN}</pattern>
</encoder>
</appender>
<!--输出到文件-->
<appender name="BB-FILE-LOG" class="ch.qos.logback.core.rolling.RollingFileAppender">
<encoder>
<pattern>${LOG_PATTERN}</pattern>
</encoder>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${LOG_DIR}/bb-%d.log</fileNamePattern>
<maxHistory>30</maxHistory>
</rollingPolicy>
</appender>
<logger name="com.xxx.yyy.bb" level="INFO" additivity="false">
<appender-ref ref="BB_FILE_LOG"/>
</logger>
<!--设置打印日志到文件的级别或者理解是激活日志级别-->
<root level="All">
<appender-ref ref="CONSOLE-LOG" />
<appender-ref ref="FILE-LOG" />
<appender-ref ref="ERROR-LOG" />
</root>
</configuration>
4、创建logback对象
public class App
{
public static final Logger LOGGER= LoggerFactory.getLogger("App.class");
public static void main( String[] args )
{
System.out.println( "Hello World!" );
LOGGER.info("INFO模式开始执行。。。。。。");
LOGGER.error("执行error级别日志");
}
}
LOGGER.info
LOGGER.error
将日志输出控制台或打印到文件中。
5、logback配置详解
略。
end