当前位置: 首页 > article >正文

logback整合rabbitmq实现消息记录日志

logback.xml文件配置

   <!-- 配置rabbitmq的信息,数据取值yml -->
 
 <springProperty name="rabbitmqHost" source="spring.rabbitmq.host"/>
 <springProperty name="rabbitmqPort" source="spring.rabbitmq.port"/>
 <springProperty name="rabbitmqUsername" source="spring.rabbitmq.username"/>
 <springProperty name="rabbitmqPassword" source="spring.rabbitmq.password"/>
 <springProperty name="rabbitmqvirtualHost" source="spring.rabbitmq.virtual-host"/>


 <!-- 配置rabbitmq的日志记录appender -->

<appender name="LogAmqpAppender" class="org.springframework.amqp.rabbit.logback.AmqpAppender">
 
        <!--Layout(纯文本)而不是格式化的JSON -->
        <layout>
            <pattern>
           {"source":"%c-%L","createtime":"%d{yyyy-MM-dd HH:mm:ss}","thread":"%thread","level":"%-5level", "logTrackId": "%X{logTrackId}", "requestUri":"%X{requestUri}", "msg":"%msg"}
            </pattern>
        </layout>
        <host>${rabbitmqHost}</host>
        <port>${rabbitmqPort}</port>
        <username>${rabbitmqUsername}</username>
        <password>${rabbitmqPassword}</password>
        <virtualHost>${rabbitmqvirtualHost}</virtualHost>
        <declareExchange>true</declareExchange>
        <exchangeType>direct</exchangeType>
        <exchangeName>log.exchange.direct</exchangeName>
        <routingKeyPattern>logDirectQueue</routingKeyPattern>
        <generateId>true</generateId>
        <charset>UTF-8</charset>
        <durable>false</durable>
        <autoDelete>false</autoDelete>
        <deliveryMode>NON_PERSISTENT</deliveryMode>
    </appender>

    <!-- root 级别的配置 -->

    <root level="INFO">
        <appender-ref ref="LogAmqpAppender" />

    </root>

yml文件配置

  # rabbitmq
  rabbitmq:
    host: 132.33.228.149
    username: admin
    password: admin@2023$
    port: 5673
        #虚拟host 可以不设置,使用server默认host
    virtual-host: /
    connection-timeout: 10000
    listener:
      simple:
        prefetch: 1 # 每次只能获取一条,处理完成才能获取下一条
        acknowledge-mode: manual #一定改为要手动确认模式

代码配置rabbitmq信息

package com.xx.weixin.rabbitmq;


import java.util.HashMap;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;




/**
* @author 作者 srp
* @version 创建时间:2023-12-1 16:42:41
* 
*/
@Configuration

public class RabbitMqLogConfig {
	
	@Autowired
    private RabbitAdmin rabbitAdmin;
    //强制用此方法生成自己希望的队列
	@Bean
    public Queue logDirectQueue() {
	     //设置过期时间,以毫秒为单位
        HashMap<String, Object> map = new HashMap<>();
        map.put("x-message-ttl", 60000);
        //true,false跟logback.xml对应
        Queue queue = new Queue( "logDirectQueue", true,false,false,map);
        rabbitAdmin.declareQueue(queue);
        return queue;

    }
 
    @Bean
    public DirectExchange logDirectExchange() {
        //true,false跟logback.xml对应

        return new DirectExchange("log.exchange.direct", false, false);
    }
 
    /**
     * 根据路由键绑定队列到交换器上
     *
     * @return
     */
    @Bean
    public Binding logDirectBinding() {
        return BindingBuilder.bind(logDirectQueue()).to(logDirectExchange()).with("logDirectQueue");
    }
    
    @Bean
    public RabbitAdmin rabbitAdmin(ConnectionFactory defaultConnectionFactory){
        return new RabbitAdmin(defaultConnectionFactory);
    }

}

测试客户端

package com.xx.pyt.confg;
import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import org.springframework.amqp.core.Message;

import com.rabbitmq.client.Channel;

///**
//* @author 作者 srp
//* @version 创建时间:2023-12-1 16:45:44
//* 
//*/
@Component

public class DirectConsumer {
	protected final Logger log = LoggerFactory.getLogger(this.getClass());
	@RabbitListener(bindings = @QueueBinding(value = @Queue(value = "logDirectQueue", durable = "false"),
			exchange = @Exchange(name = "log.exchange.direct", durable = "false", type = "direct"),key ="logDirectQueue"))

    @RabbitHandler
    public void handleMessage(String msg, Channel channel, Message message)  throws IOException {
        try {
            // 处理消息逻辑
            processMessage(msg);
            
            // 手动ack确认
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            // 手动nack拒绝,并要求重新投递
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
            log.error(e.getMessage(), e);
        }
    }
 
    private void processMessage(String message) {
        // 模拟处理消息过程
        log.info("Processing message: " + message);
        
       
    }


}

此外,如果要对日志进行链路标记,可以是用MDC

package com.xxm.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.MDC;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import com.ylkh.admin.entity.MyUser;
import com.ylkh.security.dto.JwtUserDto;

import cn.hutool.core.lang.UUID;
import lombok.extern.slf4j.Slf4j;

/**
* @author 作者 srp
* @version 创建时间:2022年1月4日 下午12:52:43
* 
*/
@Slf4j
@Component
@WebFilter(urlPatterns = "/**",filterName = "tlFilter")
public class TraceLogLocalFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
      log.debug("链路过滤器初始化");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    	  HttpServletRequest request = (HttpServletRequest) servletRequest;
   	if(SecurityContextHolder.getContext().getAuthentication()!=null&&!"anonymousUser".equals(SecurityContextHolder.getContext().getAuthentication().getPrincipal())) {
   		     //log.info(""+SecurityContextHolder.getContext().getAuthentication().getPrincipal());
             JwtUserDto jwtUserDto = (JwtUserDto) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
             MyUser myUser = jwtUserDto.getMyUser();
             MDC.put("user", myUser.getUserName());

    	} 
   	  String logtrackId = UUID.randomUUID(true).toString();
   	  if(!request.getRequestURI().contains(".css")&&!request.getRequestURI().contains(".js")&&!request.getRequestURI().contains(".html"))
    	//添加MDC日志
   	    { 
        MDC.put("logTrackId",logtrackId);
        MDC.put("requestUri", request.getRequestURI());
   	     }
        try {
            filterChain.doFilter(servletRequest, servletResponse);
        }finally{
            //移除MDC日志
            MDC.remove(logtrackId);
        }
    //    log.info("过滤器执行完成");
    }

    @Override
    public void destroy() {
        log.warn("过滤器销毁");

    }
}


http://www.kler.cn/a/160509.html

相关文章:

  • 基于Spring Boot与Redis的令牌主动失效机制实现
  • docker更改数据目录
  • 国家网络安全法律法规
  • JavaWeb后端开发知识储备1
  • Scala学习记录,case class,迭代器
  • LeetCode 86.分隔链表
  • 关于域名、ssl证书的一些问题
  • ThreadX开源助力Microsoft扩大应用范围:对比亚马逊AWS的策略差异
  • 在cmd下查看当前python的版本
  • vue2+typescript使用高德地图2.0版本
  • 物联网安全芯片ACL16 采用 32 位内核,片内集成多种安全密码模块 且低成本、低功耗
  • 【1】基于多设计模式下的同步异步日志系统-项目介绍
  • 5-redis高级-哨兵
  • vue3 Hooks函数使用及常用utils封装
  • LeetCode双指针:第一个错误的版本
  • Redis Reactor事件驱动模型源码
  • Linux-centos上如何配置管理NFS服务器?
  • 数据分析中的绝地反击:如何解救一个陷入困境的数据模型
  • IDEA切换Python虚拟环境
  • Vue3计算属性与监听属性和生命周期
  • Linux网卡命名规则
  • Spring Boot学习(三十三):集成kafka
  • 让关节远离疼痛,重拾健康活力
  • Java架构师系统架构设计原则应用
  • 13款趣味性不错(炫酷)的前端动画特效及源码(预览获取)分享(附源码)
  • 解决Error:You‘re using an RSA key with SHA-1, which is no longer allowed