禁用System.out的方法之重定向

业务场景

使用阿里巴巴的MNS,但是因为 MNSMessageProducer 类中有system.out.prinlin,所以导致频繁在日志中打印信息

日志文件分分钟就1GB

解决思路

重定向system.out, 并输出空字节

代码

import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Profile;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;

@Order(10)  // 设置优先级为10,防止控制台在启动时就直接禁用掉
@Component
@Profile("product") // 设置为生产环境才作用
public class ForbiddenSystemOut implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments applicationArguments) throws Exception {
        System.setOut(new SystemOutPrintStream());
    }

    class SystemOutPrintStream extends PrintStream {
        public SystemOutPrintStream() {
            super(new ByteArrayOutputStream(0));
        }

        public void println(String s) {
        }
    }
}

设置Order优先级是因为在启动过程中,可能会有程序调用system.out,但我们真正要拦截得是运行时的, 所以设置为10,让代码走一会儿

PS: 生产环境一律禁用system.out, 改用log去记录

设置Profile环境生效是因为在本地开发时有时候还是会偷懒写下system.out, 因为idea输入sout习惯了,过后就删除了

需要配合 spring.profiles.active: product 使用,让其只在生产环境生效

另一种解决方法请查看另外一篇文章 ↓↓↓

 阿里云MNS工具 java-messaging-lib 之万恶的System.out.prinln

 

如果帮到你,请点个赞吧 O(∩_∩)O~

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值