打赏

logback使用

  logback简介:参考百度百科:Logback是由log4j创始人设计的又一个开源日志组件。logback当前分成三个模块:logback-core,logback- classic和logback-access。logback-core是其它两个模块的基础模块。logback-classic是log4j的一个 改良版本。此外logback-classic完整实现SLF4J API使你可以很方便地更换成其它日志系统如log4j或JDK14 Logging。logback-access访问模块与Servlet容器集成提供通过Http来访问日志的功能

使用

1.引入依赖

<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.1.7</version>
</dependency>

网上有@文章同时配置了logback-ext-spring,说是spring不直接支持logback,时间是2014年,估计现在支持了。所以本人没配。

<dependency>
<groupId>org.logback-extensions</groupId>
<artifactId>logback-ext-spring</artifactId>

<version>0.1.4</version>
</dependency>.

网上还有大量文章配置了core等依赖,例如@文章里就一共添加了slf4j-api.jar,logback-core.jar,logback-classic.jar,logback-access.jar这四个依赖包。

不过作者只用了logback-classic1.1.7一个也同样实现了日志功能(作者水平有限,不能有效判定具体哪些功能受限)

2.测试

package com.yanan.site.controller;

import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import com.yanan.dto.UserDTO;
import com.yanan.service.UserService;

@Controller
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService;
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);
    @RequestMapping("/getListUsers")
    public String getListUsers(ModelMap map){
        logger.info("------------------------进入getListUsers方法-----------------------");
        try {
            List<UserDTO> listUsers = userService.getListUsers();
            map.put("listUsers", listUsers);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "userList";
    }
}
View Code

测试结果

19:26:38.998 [http-bio-8080-exec-3] INFO com.yanan.site.controller.UserController - ------------------------进入getListUsers方法-----------------------
19:26:39.029 [http-bio-8080-exec-3] DEBUG org.mybatis.spring.SqlSessionUtils - Creating a new SqlSession
19:26:39.037 [http-bio-8080-exec-3] DEBUG org.mybatis.spring.SqlSessionUtils - SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@2bb7924c] was not registered for synchronization because synchronization is not active
19:26:39.051 [http-bio-8080-exec-3] DEBUG org.mybatis.spring.transaction.SpringManagedTransaction - JDBC Connection [com.alibaba.druid.proxy.jdbc.ConnectionProxyImpl@326b9098] will not be managed by Spring
19:26:39.057 [http-bio-8080-exec-3] DEBUG com.yanan.dao.UserMapper.getListUsers - ==>  Preparing: select * from user; 
19:26:39.084 [http-bio-8080-exec-3] DEBUG com.yanan.dao.UserMapper.getListUsers - ==> Parameters: 
19:26:39.105 [http-bio-8080-exec-3] DEBUG com.yanan.dao.UserMapper.getListUsers - <==      Total: 1
19:26:39.105 [http-bio-8080-exec-3] DEBUG org.mybatis.spring.SqlSessionUtils - Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@2bb7924c]
View Code

结果显示logback生效了。

然而,这仅限于控制台日志(原因参看下方官网摘录)。若要输出日志文件,还需配置logback配置文件。命名也有规则,参考@官方文档?

官网配置文件名规则摘录

Let us begin by discussing the initialization steps that logback follows to try to configure itself:

1.Logback tries to find a file called logback-test.xml in the classpath.

2.If no such file is found, logback tries to find a file called logback.groovy in the classpath.

3.If no such file is found, it checks for the file logback.xml in the classpath..

4.If no such file is found, service-provider loading facility (introduced in JDK 1.6) is used to resolve the implementation of com.qos.logback.classic.spi.Configurator interface by looking up the file META-INF\services\ch.qos.logback.classic.spi.Configurator in the class path. Its contents should specify the fully qualified class name of the desired Configurator implementation.

5.If none of the above succeeds, logback configures itself automatically using the BasicConfigurator which will cause logging output to be directed to the console.
View Code

选用其中一个作为配置文件名称配置

<?xml version="1.0" encoding="UTF-8"?>
<configuration>

    <property name="LOG_HOME" value="E:/log/zyn" />
    <!--输出到控制台的设置-->
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <layout class="ch.qos.logback.classic.PatternLayout">
            <Pattern>[%d{yyyy-MM-dd HH:mm:ss.SSS}] -- [%p] -- [%thread >>>> %F:%L >>>> Method = %M] -- [Content = %m]%n</Pattern>
        </layout>
    </appender>

    <!-- 按照每天生成日志文件 -->
    <appender name="FILE"  class="ch.qos.logback.core.rolling.RollingFileAppender">
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <!--日志文件输出的路径+文件名-->
            <FileNamePattern>${LOG_HOME}/logbackOutFile.%d{yyyy-MM-dd}.log</FileNamePattern>
            <!--日志文件保留天数-->
            <MaxHistory>30</MaxHistory>
        </rollingPolicy>
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <pattern>[%d{yyyy-MM-dd HH:mm:ss.SSS}] -- [%p] -- [%thread >>>> %F:%L >>>> Method = %M] -- [Content = %m]%n</pattern>
             <charset>UTF-8</charset> 
        </encoder>
        <!--日志文件最大的大小-->
        <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
            <MaxFileSize>100MB</MaxFileSize>
        </triggeringPolicy>
    </appender>

    <logger name="com.yanan" level="TRACE"/>

    <!--myibatis log configure-->
    <logger name="com.apache.ibatis" level="TRACE"/>
    <logger name="java.sql.Connection" level="DEBUG"/>
    <logger name="java.sql.Statement" level="DEBUG"/>
    <logger name="java.sql.PreparedStatement" level="DEBUG"/>

    <!--默认所有级别是 debug,使用控制台和文件两种类型都进行输出输出,如果只要使用一种控制台输出的话,则下面把FILE那一行去掉即可-->
    <root level="TRACE">
        <appender-ref ref="STDOUT" />
        <appender-ref ref="FILE" />
    </root>
</configuration>
View Code

启动项目,对应目录下可以看到日志文件生成

这是日志文件的内容

[2017-07-27 19:51:41.284] -- [INFO] -- [localhost-startStop-1 >>>> DruidDataSource.java:638 >>>> Method = init] -- [Content = {dataSource-1} inited]
[2017-07-27 19:51:41.401] -- [DEBUG] -- [localhost-startStop-1 >>>> LogFactory.java:135 >>>> Method = setImplementation] -- [Content = Logging initialized using 'class org.apache.ibatis.logging.slf4j.Slf4jImpl' adapter.]
[2017-07-27 19:51:41.481] -- [DEBUG] -- [localhost-startStop-1 >>>> VFS.java:109 >>>> Method = getClass] -- [Content = Class not found: org.jboss.vfs.VFS]
[2017-07-27 19:51:41.482] -- [DEBUG] -- [localhost-startStop-1 >>>> JBoss6VFS.java:142 >>>> Method = setInvalid] -- [Content = JBoss 6 VFS API is not available in this environment.]
[2017-07-27 19:51:41.483] -- [DEBUG] -- [localhost-startStop-1 >>>> VFS.java:109 >>>> Method = getClass] -- [Content = Class not found: org.jboss.vfs.VirtualFile]
[2017-07-27 19:51:41.483] -- [DEBUG] -- [localhost-startStop-1 >>>> VFS.java:70 >>>> Method = getInstance] -- [Content = VFS implementation org.apache.ibatis.io.JBoss6VFS is not valid in this environment.]
[2017-07-27 19:51:41.484] -- [DEBUG] -- [localhost-startStop-1 >>>> VFS.java:84 >>>> Method = getInstance] -- [Content = Using VFS adapter org.apache.ibatis.io.DefaultVFS]
[2017-07-27 19:51:41.485] -- [DEBUG] -- [localhost-startStop-1 >>>> DefaultVFS.java:222 >>>> Method = findJarForResource] -- [Content = Find JAR URL: jar:file:/D:/Server/Tomcat%207.0/webapps/zyn-web-site/WEB-INF/lib/zyn-service-1.0-SNAPSHOT.jar!/com/yanan/dto]
[2017-07-27 19:51:41.485] -- [DEBUG] -- [localhost-startStop-1 >>>> DefaultVFS.java:230 >>>> Method = findJarForResource] -- [Content = Inner URL: file:/D:/Server/Tomcat%207.0/webapps/zyn-web-site/WEB-INF/lib/zyn-service-1.0-SNAPSHOT.jar!/com/yanan/dto]
[2017-07-27 19:51:41.485] -- [DEBUG] -- [localhost-startStop-1 >>>> DefaultVFS.java:243 >>>> Method = findJarForResource] -- [Content = Extracted JAR URL: file:/D:/Server/Tomcat%207.0/webapps/zyn-web-site/WEB-INF/lib/zyn-service-1.0-SNAPSHOT.jar]
[2017-07-27 19:51:41.486] -- [DEBUG] -- [localhost-startStop-1 >>>> DefaultVFS.java:330 >>>> Method = isJar] -- [Content = Found JAR: file:/D:/Server/Tomcat%207.0/webapps/zyn-web-site/WEB-INF/lib/zyn-service-1.0-SNAPSHOT.jar]
[2017-07-27 19:51:41.486] -- [DEBUG] -- [localhost-startStop-1 >>>> DefaultVFS.java:65 >>>> Method = list] -- [Content = Listing jar:file:/D:/Server/Tomcat%207.0/webapps/zyn-web-site/WEB-INF/lib/zyn-service-1.0-SNAPSHOT.jar!/com/yanan/dto]
[2017-07-27 19:51:41.486] -- [DEBUG] -- [localhost-startStop-1 >>>> DefaultVFS.java:200 >>>> Method = listResources] -- [Content = Found resource: /com/yanan/dto/UserDTO.class]
[2017-07-27 19:51:41.487] -- [DEBUG] -- [localhost-startStop-1 >>>> ResolverUtil.java:256 >>>> Method = addIfMatching] -- [Content = Checking to see if class com.yanan.dto.UserDTO matches criteria [is assignable to Object]]
[2017-07-27 19:51:41.503] -- [DEBUG] -- [localhost-startStop-1 >>>> SqlSessionFactoryBean.java:458 >>>> Method = buildSqlSessionFactory] -- [Content = Parsed configuration file: 'class path resource [mybatis-config.xml]']
[2017-07-27 19:51:41.558] -- [DEBUG] -- [localhost-startStop-1 >>>> SqlSessionFactoryBean.java:490 >>>> Method = buildSqlSessionFactory] -- [Content = Parsed mapper file: 'class path resource [mybatis/UserMapper.xml]']
View Code

大功搞成!

 

posted @ 2017-07-27 19:55  每天都要学一点  阅读(316)  评论(0编辑  收藏  举报