把System.out.print的输出加到logback的日志文件中

经常会碰到一些旧系统,使用System.out直接在控制台输出日志,然后再用命令行重定向的方法把日志写到文件中,这个方法主要问题是日志会越来越大,要经常手动删除。

今天我们就把System.out的输出加到logback的日志文件中,由logback来管理这些日志。

直接上代码,一都在代码和注释中了。

package com.example;
 
 
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
import java.io.PrintStream;
 
 
public class MyLog {
 
    private static final Logger logger = LoggerFactory.getLogger(MyLog.class);
 
 
 
    /**
     * 把System.out和System.err替换为新的PrintStream,用logger.info代替System.out.print和System.err.print
     * @param SysPrintStream  可以是System.out和System.err
     * @return  返回新的PrintStream
     */
    public static PrintStream createMyPrintStream(final PrintStream SysPrintStream) {
        PrintStream myStream= new PrintStream(SysPrintStream) {
            public void print(final String string) {
                logger.info(string);
            }
        };
        return myStream;
    }
 
    /**
     * 在程序启动时运行这个函数,让logback接管Sytem.out和System.err
     */
    public static void init() {
        System.setOut(createMyPrintStream(System.out)); //替换System.out
        System.setErr(createMyPrintStream(System.err)); //替换System.err
    }
}
package com.example;
 
 
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
 
 
 
@SpringBootApplication
public class MyApplication {
 
 
    private static Logger logger = LoggerFactory.getLogger(MyApplication.class);
 
    public static void main(String[] args) {
 
        MyLog.init();//程序启动时运行这个方法,主要就是这一句
        SpringApplication.run(MyApplication.class,args);
        //下面这些代码都是测试用的
        System.out.println("===============mytest===============");
        Integer i=100;
        System.err.println(i);
        try{
            Integer t=100/0;
        }catch (Exception e){
            e.printStackTrace();
        }
 
    }
 
}

程序运行之后,我们可以看看控制台的输出:
在这里插入图片描述
再看看log文件的内容:
在这里插入图片描述

和控制台输出的一模一样

项目源码放在Github: https://github.com/Dengxd/LogbackSystemOut

转至:https://blog.csdn.net/dengxiaodai/article/details/129768843

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

LuckyTHP

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值