【问题标题】:Saving errors to a file handler将错误保存到文件处理程序
【发布时间】:2014-09-21 12:16:03
【问题描述】:

使用下面的代码,我正在尝试模拟命令 shell,我什至创建了一个命令并将其称为 (Showerrlog),以帮助用户查看他在当前工作会话期间输入的无效命令,如您所见,我使用文件处理程序做到了,它将错误的命令保存在日志文件中。但是正如您所知,filehandler 将为每个新的工作会话启动一个新文件,并且新文件将被命名为(file.log、file.log.1、file.log.2 等)等等,问题是: 如何让程序避免每次都打开一个新文件,换句话说,有没有其他方法可以让程序只格式化前一个工作会话并添加新文件?

或者至少如何让程序打开属于当前工作会话的最后一个日志文件?

public class WithEyul implements Runnable {

    String command;

    public WithEyul(String command) {
        this.command = command;
    }

    @Override    
    public void run() {
        List<String> input = new ArrayList<String>();
        StringTokenizer tokenizer = new StringTokenizer(command);
        while (tokenizer.hasMoreTokens()) {
            input.add(tokenizer.nextToken());
        }
        ProcessBuilder pb = new ProcessBuilder(input);
        // ProcessBuilder creates a process corresponding to the input command
        // now start the process
        BufferedReader br = null;
        try {
            Process proc = pb.start();
            // obtain the input and output streams
            InputStream is = proc.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            br = new BufferedReader(isr);
            // read what the process returned
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
            br.close();
        } catch (java.io.IOException ioe) {

            try {
                System.err.println("Error");

                Logger logger = Logger.getLogger("Testing");
                FileHandler fh = new FileHandler("E:/MyLogFile.log");

                logger.addHandler(fh);
                SimpleFormatter formatter = new SimpleFormatter();
                fh.setFormatter(formatter);
                logger.info(command);
            } catch (SecurityException e) {
                printStackTrace();
            } catch (IOException ex) {
                Logger.getLogger(WithEyul.class.getName()).log(Level.SEVERE, null, ex);
            }
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException ex) {
                    Logger.getLogger(WithEyul.class.getName()).log(Level.SEVERE, null, ex);
                }
            }    
        }    
    }    
}

这里是主要的方法类

public class TestProcessBuilder {

    static void createProcess(String command) throws java.io.IOException {
        Thread t = new Thread(new WithEyul(command));
        t.start();    
    }

    public static void main(String[] args) throws java.io.IOException {

        String commandLine;
        File wd;
        BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("\n\n***** Welcome to the Java Command Shell *****");
        System.out.println("If you want to exit the shell, type END and press RETURN.\n");
        // we break out with ‘END’
        while (true) {
            // show the Java shell prompt and read what command they entered
            System.out.print("jsh>");
            commandLine = console.readLine();
            // if user entered a return, just loop again
            if (commandLine.equals("")) {
                continue;
            }
            if (commandLine.equalsIgnoreCase("Showerrlog")) {
                try {

                    // Runtime.getRuntime().exec("E:\\MyLogFile.log");
                    if (Desktop.isDesktopSupported()) {
                        Desktop.getDesktop().open(new File("E:\\MyLogFile.log"));
                    }

                } catch (IOException ex) {
                    Logger.getLogger(WithEyul.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            if (commandLine.toLowerCase().equals("end")) { //User wants to end shell
                System.out.println("\n***** Command Shell Terminated. See you next time. BYE for now. *****\n");
                System.exit(0);
            }

            createProcess(commandLine);

        }
    }
}

【问题讨论】:

    标签: java logging filehandler


    【解决方案1】:

    您可以使用FileHandler 构造函数,它允许您指定旋转、限制和附加选项。

    new FileHandler("E:/MyLogFile.log", 0, 1, true);
    

    FileHandler 可能会因许多您无法控制的原因而旋转。如果您不想处理文件轮换,可以打开FileOutputStream 并用StreamHandler 包装它。但是,您必须处理文件锁定冲突。

    您还应该避免在每次生成错误时创建和添加指向同一目标文件的处理程序。您应该在启动时安装处理程序并存储string reference to your logger

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-17
      • 1970-01-01
      相关资源
      最近更新 更多