业务场景
使用阿里巴巴的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~