Fineely Log轻量级日志记录框架(支持kakfa和openFeign)

fineely-log是一个用于记录项目REST接口日志的工具,支持Maven和Gradle集成。通过在控制器方法上添加@FineelyLog注解,可以方便地记录请求信息,包括模块名、URL、方法等。日志存储模式默认为队列,也可配置为Feign或Kafka进行远程处理。提供了示例代码展示如何处理日志数据,包括从队列读取和自定义日志存储策略。
摘要由CSDN通过智能技术生成

应用场景:项目rest接口日志记录

fineely-log可在中央Maven存储库中获得。Maven 用户将其添加到您的POM. 

<dependency>
    <groupId>com.fineely</groupId>
    <artifactId>fineely-log</artifactId>
    <version>1.0.2</version>
</dependency>

Gradle 用户将此添加到您的build.gradle.

implementation 'com.fineely:fineely-log:1.0.2'

如何使用: 

@RestController
@RequestMapping("/example")
public class Example {

    @GetMapping("/hello")
    @FineelyLog(method = RequestMethod.GET, module = "example", url = "/example/hello")
    public String hello(String name) {
        return "Hello: " + name;
    }

    @GetMapping("/name")
    @FineelyLog(method = RequestMethod.GET, module = "example", desc = "${name}")
    public String name(String name) {
        return name;
    }

    @PostMapping("/test")
    @FineelyLog(method = RequestMethod.POST, module = "example", desc = "${myExample.xx}, Hello ${one}")
    public String test(@RequestBody MyExample myExample, @FineelyParam ParamMap paramMap) {
        paramMap.put("one", "World");
        return "Hello";
    }
}

注解@FineelyLog中的desc属性可写表达式取结果、入参、方法名称、执行时间等

    /**
     * Description
     * Parameter Name ${name} or ${class.name}
     * Common parameters are as follows:
     * 
     * Method returns a result: ${result.**}
     * Method name: ${methodName}
     * Method execution start time: ${startTime}
     * Method execution end time: ${endTime}
     * Courtship parameter: ${request.**}
     * Array matching: ${result.data[0].name}
     */
    String desc() default "";

 配置文件application.yml 

fineely:
  log:
    storage-mode: queue

注:对于storage-mode = queue 可以不用配置,这是默认的配置 

如何拿取日志数据做处理 

package com.example;

/**
 * fineely.log.storageMode = queue
 */
@Slf4j
@Component
public class LogQueueTask {

    @Scheduled(fixedRate = 5000)
    public void monitorQueueLog(){
        LinkedTransferQueue<MethodLogEntity> oplogQueue = QueueOperator.INSTANCE.getOplogQueue();
        if (!oplogQueue.isEmpty()) {
            // do something
            List<MethodLogEntity> oplogs = new ArrayList<>();
            oplogQueue.drainTo(oplogs);
            for (MethodLogEntity oplog : oplogs) {
                log.info("::::::: log:[{}]", oplog.toString());
            }
        } else {
            log.info("::::::: No log temporarily");
        }
    }
}

当然,你想自己拿取数据做处理,不用Queue也许,只用这样操作 

import com.fineelyframework.log.entity.MethodLogEntity;

/**
 * CustomLogDaoImpl
 * Implement the MethodLogDao interface
 * Yml does not need to add configuration
 */
@Component
public class CustomLogDaoImpl implements MethodLogDao {


    @Override
    public boolean saveLog(MethodLogEntity methodLogEntity) {
        // do something
        return true;
    }

}

注:上述直接实现MethodLogDao接口,进行自定义处理,当然这里也不需要yml配置 

当然也支持kafka和 openFeign,配置如下

fineely:
  log:
    storage-mode: feign
    # Choose between the name and url
    # Without eureka, Please use path
    feign:
      # Application Name registered in eureka
      name: example
      url: http://localhost:8895
      path: /test
# If you need eureka, you can add configurations, set fineely.log.feign.name = target spring.application.name
eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:1112/eureka/
  instance:
    prefer-ip-address: true

 注:有用eureka的配置直接用name,如果没有就用url指定服务器

接口如何定义,项目中默认的为save,目前还不支持配置

public class LogEntity {
    private String[] method;
    private String methodName;
    private String module;
    private String url;
    private String desc;
    private LocalDateTime startTime;
    private LocalDateTime endTime;
    private double timeConsuming;
    private String allParams;
    private String result;
    private String ipAddress;
    private String exceptionInfo;
    private String operator;
    private LocalDateTime createTime;
}

@RestController
@RequestMapping("/test")
public class TestController {

    /**
     * feign mode mapping url is `save`
     */
    @PostMapping("save")
    public boolean saveLog(@RequestBody LogEntity logEntity) {
        System.out.println(myEntity.toString());
        // do something
        return true;
    }
}

 kafka的配置如下

fineely:
  log:
    storage-mode: kafka
    kafka:
      kafka-brokers: 192.168.3.190:9092
      topic: test-server
      group-id: e27121ee40c6c6f45f91ab52101b1122

以下省略KafkaConfig 类,以下代码为监听器 

/**
 * Kafka listener, listening for log notifications
 */
@Slf4j
@Component
public class KafkaMessageHandler {

    @KafkaListener(
            containerFactory = "messageReceiveListener",
            topics = {"${topic}"},
            groupId = "${group-id}"
    )
    public void consumerCommonMessageNotify(List<ConsumerRecord<?, ?>> records, Acknowledgment ack) {
        try {
            records.forEach(content -> {
                log.info("=====:::::: Start processing message=====");
                // do something
                String message = content.value().toString();
                log.info(String.format(":::::: Receive message content => %s", message));
                log.info("=====:::::: Processing Message End=====");
            });
        } catch (Exception e) {
            log.error(":::::: Message processing error => ", e);
        } finally {
            ack.acknowledge();
        }
    }
}

 参考:GitHub - Big-billed-shark/fineely-log: Record Request Interface Log

            Maven Central: com.fineely:fineely-log:1.0.2 

            Gitee - kepler_16b/fineely-log

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值