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)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • SCSA之信息安全概述「建议收藏」

    SCSA之信息安全概述「建议收藏」一、信息安全概述1、信息安全防止任何对数据进行未授权访问的措施,或者防止造成信息有意无意泄漏、破坏丢失等问题的发生,让数据处于远离危险、免于威胁的状态或特性。(1)网络安全计算机网络环境下的信息安全。二、信息安全的脆弱性及常见的攻击1、网络环境的开放性“INTERNET的美妙之处在于你和每个人都能互相连接,INTERNET的可怕之处在于每个人都能和你互相连接”2、…

    2022年6月20日
    28
  • Kotlin概述与Java的比较

    Kotlin概述与Java的比较Kotlin是JetBrains的一种新的编程语言。它首次出现在2011年,JetBrains推出了名为“科特林”的项目。Kotlin是开源语言。基本上像Java一样,C和C++-Kotlin也是“静态类型编程语言”。静态类型的编程语言是在使用变量之前不需要定义的那些语言。这意味着静态类型与变量的使用明确声明或初始化有关。如前所述,Java是静态类型语言的一个例子,类似C和C++

    2022年7月8日
    20
  • 数据仓库搭建ODS层[通俗易懂]

    数据仓库搭建ODS层[通俗易懂]其他内容请关注我的博客!在<项目>专栏里!!!目录一、用户行为数据1.1创建日志表1.2ODS层加载数据脚本二、业务数据2.1hive建表2.2ODS层加载数据脚本一、用户行为数据1.1创建日志表1)创建支持lzo压缩的分区表droptableifexistsods_log;CREATEEXTERNALTABLEods_log(`line`string)PARTITIONEDBY(`dt`string)–

    2022年10月5日
    4
  • 【剑指offer】删除字符也出现在一个字符串

    【剑指offer】删除字符也出现在一个字符串

    2022年1月3日
    44
  • [leetcode]Search for a Range

    [leetcode]Search for a Range

    2022年1月14日
    43
  • oracle字符串自身去重,oracle拼接字符串函数(去重和不去重)「建议收藏」

    oracle字符串自身去重,oracle拼接字符串函数(去重和不去重)「建议收藏」oracle拼接字符串函数(去重和不去重)1.不去重FUNCTIONf_linkFunctionf_linkCREATEORREPLACEFUNCTIONf_link(p_strVARCHAR2)RETURNVARCHAR2PARALLEL_ENABLEAGGREGATEUSINGt_link;Typet_linkCREATEORREPLACETYPET_LINK…

    2022年9月20日
    4

发表回复

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

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