logback使用

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.测试

logback使用
logback使用

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

测试结果

logback使用
logback使用

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配置文件。命名也有规则,参考@官方文档?

官网配置文件名规则摘录

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

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

logback使用
logback使用

<?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

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

logback使用

这是日志文件的内容

logback使用
logback使用

[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

大功搞成!

 

转载于:https://www.cnblogs.com/yanan7890/p/7246818.html

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/108295.html原文链接:https://javaforall.net

(0)
上一篇 2022年3月5日 下午4:00
下一篇 2022年3月5日 下午4:00


相关推荐

  • CentOS 修改IP地址, DNS, 网关

    CentOS 修改IP地址, DNS, 网关

    2021年5月9日
    235
  • Spring SpringMVC SpringBoot 常用注解说明

    Spring SpringMVC SpringBoot 常用注解说明SpringSpring 常用注解说明 Spring 注解与 xml 配置的区别不使用注解的案例 Autowired Qualifier Resource Service 使用注解来构造 IoC 容器 Component Controller Service RepositorySp 常用注解汇总 SpringMVC Controller RequestMappi 使用

    2026年3月17日
    3
  • 一文读懂目标检测:R-CNN、Fast R-CNN、Faster R-CNN、YOLO、SSD「建议收藏」

    一文读懂目标检测:R-CNN、Fast R-CNN、Faster R-CNN、YOLO、SSD「建议收藏」一文读懂目标检测:R-CNN、FastR-CNN、FasterR-CNN、YOLO、SSD前言之前我所在的公司七月在线开设的深度学习等一系列课程经常会讲目标检测,包括R-CNN、FastR-CNN、FasterR-CNN,但一直没有比较好的机会深入(但当你对目标检测有个基本的了解之后,再看这些课程你会收益很大)。但目标检测这个领域实在是太火了,经常会看到一些写的不…

    2022年6月11日
    40
  • 智能体性能测试:AI Agents for Beginners基准测试报告

    智能体性能测试:AI Agents for Beginners基准测试报告

    2026年3月16日
    2
  • (二)缺陷报告「建议收藏」

    (二)缺陷报告「建议收藏」当测试人员发现一个缺陷,需要填写一份“缺陷报告”来记录这个缺陷,并通过这个缺陷报告告知开发人员所发生的问题–缺陷报告是测试人员和开发人员交流沟通的重要工具。案例1:张三在测试案例1-2-1程序时,发现除数为0时程序异常退出,向开发组提交一份缺陷报告。一、缺陷报告的组成:①缺陷编号(DefectID):提交缺陷的顺序②缺陷标题(summary):简明扼要的描述缺陷③缺陷…

    2026年1月14日
    6
  • Python如何判断数据类型

    Python如何判断数据类型NoneType 类型 In 12 a NoneIn 13 printtype a 判断方法 ifaisNone passelse pass 转载关于 Null 和 None 的解释 Null 和 None 是 Python 的特殊类型 Null 对象或者是 NoneType 它只有一个值 None 它不支持任何运算也没有任何内建方法

    2026年3月16日
    2

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号