springboot 最简单的日志打印,输出文件 及全局异常捕获处理

一直使用System.out.println()的我终于在今天从良了,我决定开始使用log了。

好了,不废话了,进入正题(先介绍日志简单使用,再介绍全局异常捕获及根据异常类型处理,不想看日志使用的直接看后面。)

前言:

我在学习这个日志打印的时候,在网上浏览了很多相关的知识,发现有些高级配置啊,有些花样日志管理啊等等;

而我,仅仅是想用一下日志的打印, 然后把日志生成某个文件给运维人员看(然后关掉Tomcat那可恶的日志)。 也就是仅此而已。

所以,接下来的日志使用,还真的是蛮轻巧(简单)的。

首先,

日志这边用到的jar包方法是:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

为什么不把pom直接贴出来呢,是因为:

看,

也就是说,还是贴pom.xml的东西出来吧:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>

</dependencies>

spring-boot-starter这里面已经自带了我们这次日志需要使用的依赖了,所以我们不用导额外的了。

那么,依赖不用弄,那我们接下来弄啥?

简单为这个日志使用配置一下吧:

application.properties:

#将日志文件生成到系统盘路径

logging.path=F:\\logtest\\log


#简单设置一下日志等级
logging.level.web=info


#将日志文件生成到项目绝对路径
#logging.file=log\\myboot.log

里面的配置作用就不用解释了吧,你看我的注释,已经简单介绍了。

好了,开始使用。

新建一个controller:

我的叫TestSoGa,你随意。

package com.springbootstudy.controller;




import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;



@RestController
@RequestMapping("testYes")
public class TestSoGa {
   //记得加上这个哇,这是告诉全世界,你要开始在这类里面使用日志
 protected static final Logger logger = LoggerFactory.getLogger(TestSoGa.class);
    


    @RequestMapping("/testlog")
    public String helloworld() {
        logger.info("log开始生成");
        return "Hello world!";
    }


}

好了,运行,访问一下 @RequestMapping("/testlog"),(当然了,我前面还有一个@RequestMapping("/testYes")的,别因为这个而一直访问错误了。),访问后,OK日志打印处理了,然后日志文件也生成了(本地路径的去本地系统盘路径看,绝对路径的在项目看)。

好了,就这样,我们的日志使用已经介绍完了。  真的简单对吧,凑合用下吧,高级点的日志管理,后面有空再更吧(你去外面学去!)

接下来,结合这个日志打印,那么我们来配置全局异常捕获,这么一来,运维人员就舒服点了,去看日志,然后我们异常捕获给他做点日志处理,我们开发也不用被牵扯过去解释了。

首先, 建一个异常Handler吧,

我的叫MyExceptionHandler,你随意。

然后紧接着,先放着吧,我们去上面的日志controller去弄点方法故意抛出点错误。

(里面方法举了2个例子。抛出了2个异常,自己看完后自己举一反三~)

package com.springbootstudy.controller;

import com.springbootstudy.pojo.TestUser;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;


@RestController
@RequestMapping("testYes")
public class TestSoGa {
    protected static final Logger logger = LoggerFactory.getLogger(TestSoGa.class);
    
    @RequestMapping("/errortest")
    public Integer ErrorTest(HttpSession session) {


        String thisMethodName = new Exception().getStackTrace()[0].getMethodName();// 获得当前的方法名
        String thisClassName = new Exception().getStackTrace()[0].getClassName();// 获得当前的方法名
        session.setAttribute("errorSource","方法名称->"+thisMethodName+"   |  "+"控制器名称->"+thisClassName);
        System.out.println("**********"+thisMethodName+"*************"+thisClassName);

        return 100 / 0;
    }

    @RequestMapping("/errortest2")
    public String ErrorTest2(HttpSession session) {
        String thisMethodName = new Exception().getStackTrace()[0].getMethodName();// 获得当前的方法名
        String thisClassName = new Exception().getStackTrace()[0].getClassName();// 获得当前的类名
        session.setAttribute("errorSource","方法名称->"+thisMethodName+"   |  "+"控制器名称->"+thisClassName);
        String tfk= session.getAttribute("testNULLSessionValue").toString();

        return tfk;
    }



    @RequestMapping("/testlog")
    public String helloworld() {
        logger.info("log开始生成");
        return "Hello world!";
    }


}

好了,配置完这个先不用管那么多,我们(MyExceptionHandler)直接继续再复制粘贴:

package com.springbootstudy.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@ControllerAdvice
public class MyExceptionHandler {
    private static Logger logger = LoggerFactory.getLogger(MyExceptionHandler.class);
    @ExceptionHandler(value = Exception.class)
    public void defaultExceptionHandler(HttpServletRequest req, HttpSession session,Exception e){
        String errorSource=  session.getAttribute("errorSource").toString();
        //根据抓获的异常类型,做逻辑处理,并打印日志信息
        if(e instanceof java.lang.NullPointerException){

            logger.info("空指针异常---"+"---出错的方法是:"+errorSource);
        }
        if(e instanceof java.lang.ArithmeticException){
            logger.info("使用0作为分母---"+"---出错的方法是:"+errorSource);
        }

        e.printStackTrace();
        System.out.println("全局异常捕获中");
    }


}

好了,以上全局异常捕获及简单的配合日志打印处理已经完毕了,我下面也介绍下这个全局异常捕获:

先是,controller里面的方法,我们代码走读吧,

就看这个方法吧,

@RequestMapping("/errortest2")
public String ErrorTest2(HttpSession session) {
    String thisMethodName = new Exception().getStackTrace()[0].getMethodName();// 获得当前的方法名
    String thisClassName = new Exception().getStackTrace()[0].getClassName();// 获得当前的类名
    session.setAttribute("errorSource","方法名称->"+thisMethodName+"   |  "+"控制器名称->"+thisClassName);
    String tfk= session.getAttribute("testNULLSessionValue").toString();

    return tfk;
}

这是个故意为了抛异常而弄的, 最后一行就是故意抛出个空指针异常咯,因为session值根本就没~

然后前面获取当前的方法名啊,类名啊 这些,大家都可以自己发挥,也就起到后面日志打印的时候,提供下异常源跟踪。

然后看异常Handler里面的方法:

String errorSource= session.getAttribute("errorSource").toString(); //根据抓获的异常类型,做逻辑处理,并打印日志信息 if(e instanceof java.lang.NullPointerException){ logger.info("空指针异常---"+"---出错的方法是:"+errorSource); }

就看这几行吧, 就是把之前那边的异常跟踪源信息放到session,从这边取出来, 然后就是小重点了:

e instanceof java.lang.NullPointerException  这个,就是用来判断当前捕获到的异常是什么类型,然后就可以添油加醋了。

上个结果图咯:

好了,简单的使用介绍完毕。

猜你喜欢

转载自blog.csdn.net/qq_35387940/article/details/83861805
今日推荐