时时监控日志


在开发过程中需要经常读取日志文件,为了监控状态

本地文件时时监控

package com.jay.timelog;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @version 0.0.1
 * @program: spring-poi-demo
 * @description: 本地时时读和写日志
 *
 * https://www.cnblogs.com/en-heng/p/3926708.html
 *
 * https://www.cnblogs.com/pfblog/articles/6848502.html
 * @author: huangzq
 * @create: 2020-09-10 18:32
 */
public class LogReader implements Runnable{

    private File logFile = null;
    // 上次文件大小
    private long lastTimeFileSize = 0;
    private static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public LogReader(File logFile) {
        this.logFile = logFile;
        lastTimeFileSize = logFile.length();
    }

    /**
     * 实时输出日志信息
     */
    @Override
    public void run() {
        System.err.println("ok进入");
        while (true) {
            try {
                long len = logFile.length();
                if (len < lastTimeFileSize) {
                    System.out.println("Log file was reset. Restarting logging from start of file.");
                    lastTimeFileSize = len;
                } else if(len > lastTimeFileSize) {
                    RandomAccessFile randomFile = new RandomAccessFile(logFile, "r");
                    //移动文件指针位置
                    randomFile.seek(lastTimeFileSize);
                    String tmp = null;
                    while ((tmp = randomFile.readLine()) != null) {
                        //打印读取的内容,并将字节转为字符串输入,做转码处理,要不然中文会乱码
//                        tmp = new String(tmp.getBytes("ISO-8859-1"),"gb2312");
//                        tmp=new String(tmp.getBytes("8859_1"),"gb2312");//解决中文乱码
//                        tmp = new String(tmp.getBytes("UTF-8"),"UTF-8");
                        //上面的都是乱码,网上一大堆都没用,下面的这个有用
                        tmp = new String(tmp.getBytes("iso-8859-1"),"utf-8");
                        System.out.println(dateFormat.format(new Date()) + "\t" + tmp);
                    }
                    lastTimeFileSize = randomFile.length();
                    randomFile.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        File logFile = new File("D:\\workspace\\sampleOne_one\\log\\sample-springboot.log");
//        Thread wthread = new Thread(new LogWrite(logFile));
//        wthread.start();
        Thread rthread = new Thread(new LogReader(logFile));
        rthread.start();
    }
}

远程文件时时监控

package com.jay.timelog;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * @version 0.0.1
 * @program: spring-poi-demo
 * @description: 远程时时读取日志
 *
 * http://www.51testing.com/html/04/446304-817736.html
 * 通过ssh链接到对应的服务器上,然后通过tail -f xx.log 来动态读取服务器上的log日志
 *
 * @author: huangzq
 * @create: 2020-09-10 18:57
 */
public class SSHReaderLog {

    private static Connection conn = null;

    private String hostname = "";
    private String username = "";
    private String password = "";
    private String[] commands;
    /**
     *
     * @param hostname
     * @return
     */
    private Connection getConnection(String hostname) {
        if (conn == null) {
            conn = new Connection(hostname);
        }
        return conn;
    }

    public void exec(String[] commands) {
        for (int i = 0; commands != null && i < commands.length; i++) {
            Connection conn = getConnection(hostname);
            try {
                conn.connect();
                boolean isAuthenticated = conn.authenticateWithPassword(username, password);
                if (isAuthenticated == false) {
                    throw new IOException("Authentication failed.");
                }
                Session sess = conn.openSession();
                sess.execCommand(commands[i]);
                InputStream stdout = new StreamGobbler(sess.getStdout());
                BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
                while (true) {
                    String line = br.readLine();
                    if (line == null) {
                        break;
                    }
                    //if (line.indexOf("sample/statistic/upload/top5") != -1) {
                    //    System.err.println("结束监听");
                    //    return;
                    //}
                    System.out.println(line);
                }
                sess.close();
                conn.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    public static void main(String[] args) {
        SSHReaderLog b = new SSHReaderLog();
        b.setHostname("ip");
        b.setUsername("用户名");
        b.setPassword("密码");
        String[] commands = { "tail -f 日志文件" };
        b.exec(commands);
    }



    public String getHostname() {
        return hostname;
    }

    public void setHostname(String hostname) {
        this.hostname = hostname;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String[] getCommands() {
        return commands;
    }

    public void setCommands(String[] commands) {
        this.commands = commands;
    }
}

时时读取是没问题的

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值