最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

SpringBoot使用AOP統(tǒng)一日志管理的方法詳解

 更新時(shí)間:2022年05月06日 11:35:12   作者:Java分享客棧  
這篇文章主要為大家分享一個(gè)干貨:超簡潔SpringBoot使用AOP統(tǒng)一日志管理,文中的示例代碼講解詳細(xì),感興趣的小伙伴快跟隨小編一起學(xué)習(xí)學(xué)習(xí)吧

前言

請(qǐng)問今天您便秘了嗎?程序員坐久了真的會(huì)便秘哦,如果偶然點(diǎn)進(jìn)了這篇小干貨,就麻煩您喝杯水然后去趟廁所一邊用左手托起對(duì)準(zhǔn)噓噓,一邊用右手滑動(dòng)手機(jī)看完本篇吧。

實(shí)現(xiàn)

本篇AOP統(tǒng)一日志管理寫法來源于國外知名開源框架JHipster的AOP日志管理方式

1、引入依賴

<!-- spring aop -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>

2、定義logback配置

1)dev、test環(huán)境的spring-web包定義日志級(jí)別為INFO,項(xiàng)目包定義日志級(jí)別為DEBUG;

2)prod環(huán)境的spring-web包定義日志級(jí)別為ERROR,項(xiàng)目包定義日志級(jí)別為INFO;

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <include resource="org/springframework/boot/logging/logback/base.xml" />
    <logger name="org.springframework.web" level="INFO"/>
    <logger name="org.springboot.sample" level="TRACE" />

    <springProfile name="dev,test">
        <logger name="org.springframework.web" level="INFO"/>
        <logger name="org.springboot.sample" level="INFO" />
        <logger name="com.example.aoplog" level="DEBUG" />
    </springProfile>

    <springProfile name="prod">
        <logger name="org.springframework.web" level="ERROR"/>
        <logger name="org.springboot.sample" level="ERROR" />
        <logger name="com.example.aoplog" level="INFO" />
    </springProfile>

</configuration>

3、編寫切面類

1)springBeanPointcut():單獨(dú)定義的spring框架切入點(diǎn);

2)applicationPackagePointcut():單獨(dú)定義的項(xiàng)目包切入點(diǎn);

3)logAfterThrowing():1和2定義的切入點(diǎn)拋出異常時(shí)日志格式及顯示內(nèi)容;

4)logAround():1和2定義的切入點(diǎn)方法進(jìn)入和退出時(shí)日志格式及顯示內(nèi)容。

package com.example.aoplog.logging;

import com.example.aoplog.constants.GloablConstants;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.env.Environment;
import org.springframework.core.env.Profiles;
import org.springframework.stereotype.Component;

import java.util.Arrays;

/**
 * <p>
 * AOP統(tǒng)一日志管理 切面類
 * </p>
 *
 * @author 福隆苑居士,公眾號(hào):【Java分享客?!?
 * @since 2022/5/5 21:57
 */
@Aspect
@Component
public class LoggingAspect {

    private final Logger log = LoggerFactory.getLogger(this.getClass());

    private final Environment env;

    public LoggingAspect(Environment env) {
        this.env = env;
    }

    /**
    * 匹配spring框架的repositories、service、rest端點(diǎn)的切面
     */
    @Pointcut("within(@org.springframework.stereotype.Repository *)" +
        " || within(@org.springframework.stereotype.Service *)" +
        " || within(@org.springframework.web.bind.annotation.RestController *)")
    public void springBeanPointcut() {
        // 方法為空,因?yàn)檫@只是一個(gè)切入點(diǎn),實(shí)現(xiàn)在通知中。
    }

    /**
    * 匹配我們自己項(xiàng)目的repositories、service、rest端點(diǎn)的切面
     */
    @Pointcut("within(com.example.aoplog.repository..*)"+
        " || within(com.example.aoplog.service..*)"+
        " || within(com.example.aoplog.controller..*)")
    public void applicationPackagePointcut() {
        // 方法為空,因?yàn)檫@只是一個(gè)切入點(diǎn),實(shí)現(xiàn)在通知中。
    }

    /**
     * 記錄方法拋出異常的通知
     *
     * @param joinPoint join point for advice
     * @param e exception
     */
    @AfterThrowing(pointcut = "applicationPackagePointcut() && springBeanPointcut()", throwing = "e")
    public void logAfterThrowing(JoinPoint joinPoint, Throwable e) {

       // 判斷環(huán)境,dev、test or prod
        if (env.acceptsProfiles(Profiles.of(GloablConstants.SPRING_PROFILE_DEVELOPMENT, GloablConstants.SPRING_PROFILE_TEST))) {
            log.error("Exception in {}.{}() with cause = '{}' and exception = '{}'", joinPoint.getSignature().getDeclaringTypeName(),
                joinPoint.getSignature().getName(), e.getCause() != null? e.getCause() : "NULL", e.getMessage(), e);

        } else {
            log.error("Exception in {}.{}() with cause = {}", joinPoint.getSignature().getDeclaringTypeName(),
                joinPoint.getSignature().getName(), e.getCause() != null? e.getCause() : "NULL");
        }

    }

    /**
     * 在方法進(jìn)入和退出時(shí)記錄日志的通知
     *
     * @param joinPoint join point for advice
     * @return result
     * @throws Throwable throws IllegalArgumentException
     */
    @Around("applicationPackagePointcut() && springBeanPointcut()")
    public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {

        if (log.isDebugEnabled()) {
            log.debug("Enter: {}.{}() with argument[s] = {}", joinPoint.getSignature().getDeclaringTypeName(),
                joinPoint.getSignature().getName(), Arrays.toString(joinPoint.getArgs()));
        }
        try {
            Object result = joinPoint.proceed();
            if (log.isDebugEnabled()) {
                log.debug("Exit: {}.{}() with result = {}", joinPoint.getSignature().getDeclaringTypeName(),
                    joinPoint.getSignature().getName(), result);
            }
            return result;
        } catch (IllegalArgumentException e) {
            log.error("Illegal argument: {} in {}.{}()", Arrays.toString(joinPoint.getArgs()),
                joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName());

            throw e;
        }

    }

}

4、測(cè)試

1)寫個(gè)service

package com.example.aoplog.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * <p>
 * AOP統(tǒng)一日志管理測(cè)試服務(wù)
 * </p>
 *
 * @author 福隆苑居士,公眾號(hào):【Java分享客?!?
 * @since 2022/5/5 21:57
 */
@Service
@Slf4j
public class AopLogService {

   public String test(Integer id) {
      return "傳入的參數(shù)是:" + id;
   }
}

2)寫個(gè)controller

package com.example.aoplog.controller;

import com.example.aoplog.service.AopLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 * 測(cè)試接口
 * </p>
 *
 * @author 福隆苑居士,公眾號(hào):【Java分享客?!?
 * @since 2022/4/30 11:43
 */
@RestController
@RequestMapping("/api")
@Slf4j
public class TestController {

   private final AopLogService aopLogService;

   public TestController(AopLogService aopLogService) {
      this.aopLogService = aopLogService;
   }

   @GetMapping("/test/{id}")
   public ResponseEntity<String> test(@PathVariable("id") Integer id) {
      return ResponseEntity.ok().body(aopLogService.test(id));
   }
}

3)設(shè)置環(huán)境

這里我試試dev,prod自己試聽見沒?不服一拳打哭你哦!

server:
  port: 8888

# 環(huán)境:dev-開發(fā) test-測(cè)試 prod-生產(chǎn)
spring:
  profiles:
    active: dev

4)效果

不解釋了自己看

試試異常情況,手動(dòng)加個(gè)異常。

@Service
@Slf4j
public class AopLogService {

   public String test(Integer id) {
      int i = 1/0;
      return "傳入的參數(shù)是:" + id;
   }
}

效果

到此這篇關(guān)于SpringBoot使用AOP統(tǒng)一日志管理的方法詳解的文章就介紹到這了,更多相關(guān)SpringBoot AOP日志管理內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • 線上Java程序占用CPU過高解決方案

    線上Java程序占用CPU過高解決方案

    這篇文章主要介紹了線上Java程序占用CPU過高解決方案,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-11-11
  • SpringBoot如何集成i18n(多語言)

    SpringBoot如何集成i18n(多語言)

    這篇文章主要介紹了SpringBoot如何集成i18n(多語言)問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-04-04
  • SpringBoot啟動(dòng)java.nio.charset.MalformedInputException: Input length = 1報(bào)錯(cuò)的解決方案

    SpringBoot啟動(dòng)java.nio.charset.MalformedInputException: I

    本文主要介紹了SpringBoot啟動(dòng)java.nio.charset.MalformedInputException: Input length = 1報(bào)錯(cuò)的解決方案
    2023-07-07
  • java 中復(fù)合機(jī)制的實(shí)例詳解

    java 中復(fù)合機(jī)制的實(shí)例詳解

    這篇文章主要介紹了java 中復(fù)合機(jī)制的實(shí)例詳解的相關(guān)資料,希望通過本文大家能了解繼承和復(fù)合的區(qū)別并應(yīng)用復(fù)合這種機(jī)制,需要的朋友可以參考下
    2017-09-09
  • Spring事件監(jiān)聽機(jī)制觀察者模式詳解

    Spring事件監(jiān)聽機(jī)制觀察者模式詳解

    這篇文章主要為大家介紹了Spring事件監(jiān)聽機(jī)制觀察者模式實(shí)例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-11-11
  • 基于Java 數(shù)組內(nèi)存分配的相關(guān)問題

    基于Java 數(shù)組內(nèi)存分配的相關(guān)問題

    本篇文章是對(duì)Java中數(shù)組內(nèi)存分配進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下
    2013-05-05
  • java中的動(dòng)態(tài)代理與責(zé)任鏈模式詳解

    java中的動(dòng)態(tài)代理與責(zé)任鏈模式詳解

    這篇文章主要介紹了java中的動(dòng)態(tài)代理與責(zé)任鏈模式詳解,動(dòng)態(tài)代理提供了一種靈活且非侵入式的方式,可以對(duì)對(duì)象的行為進(jìn)行定制和擴(kuò)展,它在代碼重用、解耦和業(yè)務(wù)邏輯分離、性能優(yōu)化以及系統(tǒng)架構(gòu)中起到了重要的作用,需要的朋友可以參考下
    2023-08-08
  • Java設(shè)計(jì)模式七大原則之單一職責(zé)原則詳解

    Java設(shè)計(jì)模式七大原則之單一職責(zé)原則詳解

    單一職責(zé)原則(Single Responsibility Principle, SRP),有且僅有一個(gè)原因引起類的變更。簡單來說,就是針對(duì)一個(gè)java類,它應(yīng)該只負(fù)責(zé)一項(xiàng)職責(zé)。本文將詳細(xì)介紹一下Java設(shè)計(jì)模式七大原則之一的單一職責(zé)原則,需要的可以參考一下
    2022-02-02
  • java實(shí)現(xiàn)計(jì)算地理坐標(biāo)之間的距離

    java實(shí)現(xiàn)計(jì)算地理坐標(biāo)之間的距離

    java實(shí)現(xiàn)計(jì)算地理坐標(biāo)之間的距離,主要是通過計(jì)算兩經(jīng)緯度點(diǎn)之間的距離來實(shí)現(xiàn),有需要的小伙伴參考下吧
    2015-03-03
  • Java中的構(gòu)造方法this、super的用法詳解

    Java中的構(gòu)造方法this、super的用法詳解

    這篇文章較詳細(xì)的給大家介紹了Java中的構(gòu)造方法this、super的用法,非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友參考下吧
    2018-07-07

最新評(píng)論

辽源市| 长子县| 兰坪| 江达县| 涪陵区| 富裕县| 博爱县| 宁波市| 颍上县| 宝鸡市| 铁岭县| 綦江县| 磐安县| 宁化县| 历史| 沈阳市| 清新县| 兴海县| 黄石市| 会宁县| 广德县| 阳江市| 石景山区| 眉山市| 灵台县| 双辽市| 长白| 磐石市| 灵石县| 沂源县| 临清市| 聊城市| 赤城县| 吐鲁番市| 鹤岗市| 宁夏| 肥西县| 天气| 湟源县| 新龙县| 揭阳市|