logback&lombok 简化日志处理
1 简介
1.1 Logback
相比较log4j,logback性能较好,且日志展现形式较美观。
1.2 Lombok
lombok 提供了简单注解的形式来简化Java代码
1.3 目的
使用lombok简化logback的使用
2 配置
2.1 lombok
详情见:http://blog.csdn.net/leeyuri/article/details/44560859
2.2 Logback
2.2.1 Maven
注:当前最新版本是1.1.2
- <dependency>
- <groupId>ch.qos.logback</groupId>
- <artifactId>logback-classic</artifactId>
- <version>${logback-version}</version>
- </dependency>
2.2.2 Logback.xml
在${项目根目录}/src/main/resources目录下新建logback.xml
注:可以直接复用下面的配置。如果输出到数据库或email等,仅供参考。
- <?xml version="1.0" encoding="UTF-8"?>
- <configuration>
- <!-- 日志保存路径为tomcat下面的logs下面的mobileLog文件夹,logback会自动创建文件夹,这样设置了就可以输出日志文件了
- <substitutionProperty name="logbase" value="${catalina.base}/logs/mobileLog/"
- /> -->
- <substitutionProperty name="logbase" value="${user.dir}/logs/ " />
-
- <jmxConfigurator />
- <appender name="stdout" class="ch.qos.logback.core.ConsoleAppender">
- <layout class="ch.qos.logback.classic.PatternLayout">
- <pattern>%date [%thread] %-5level %logger{80} - %msg%n</pattern>
- </layout>
- </appender>
-
- <appender name="logfile"
- class="ch.qos.logback.core.rolling.RollingFileAppender">
- <Encoding>UTF-8</Encoding>
- <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
- <File>${logbase}%d{yyyy-MM-dd}.log.html</File>
- <FileNamePattern>${logbase}.%d{yyyy-MM-dd}.log.html.zip
- </FileNamePattern>
- </rollingPolicy>
- <triggeringPolicy
- class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
- <MaxFileSize>2MB</MaxFileSize>
- </triggeringPolicy>
- <layout class="ch.qos.logback.classic.html.HTMLLayout">
- <pattern>%date%level%thread%10logger%file%line%msg</pattern>
- </layout>
- </appender>
-
- <!--
- <appender name="Email" class="ch.qos.logback.classic.net.SMTPAppender">
- <SMTPHost>stmp host name</SMTPHost>
- <To>Email Address</To>
- <To>Email Address</To>
- <From>Email Address</From>
- <Subject>TESTING Email Function: %logger{20} - %m</Subject>
- <layout class="ch.qos.logback.classic.html.HTMLLayout">
- <pattern>%date%level%thread%10logger%file%line%msg</pattern>
- </layout>
- </appender> -->
-
-
- <!--
- <appender name="DB" class="ch.qos.logback.classic.db.DBAppender">
- <connectionSource class="ch.qos.logback.core.db.DriverManagerConnectionSource">
- <driverClass>com.mysql.jdbc.Driver</driverClass>
- <url>jdbc:mysql://localhost:3306/test</url>
- <user>root</user>
- <password>trend_dev</password>
- </connectionSource>
- </appender> -->
- <root>
- <level value="debug" />
- <appender-ref ref="stdout" />
- <appender-ref ref="logfile" />
- </root>
-
- </configuration>
3 测试
- import lombok.extern.slf4j.Slf4j;
- import org.junit.Test;
-
- @Slf4j
- public class TestLogback {
- @Test
- public void testLog(){
- log.info("纯粹做测试");
- }
-
- }
4 效果展示