1

我不知道是我的想法愚弄了我还是这真的行不通。

我需要不同类型的 Logging 类,所以我创建了一个抽象类,所有类都具有相同的唯一定义是 writeToLog 的处理方式:

public abstract class LoggerTemplate {

    protected String filename ="log/";
    protected File logfile;

    protected FileWriter fw;

    public void writeToLog(String message) {
        if(fw != null) {
            try {
                message = new SimpleDateFormat("dd-MM-hh:mm").format(new Date()) + " " + message;
                fw.write(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

具体的子类将在其构造函数中实现其余逻辑,即其中之一:

public class JitterBufferLogger extends LoggerTemplate {

    public JitterBufferLogger() {
        super();
        filename += new SimpleDateFormat("yyyyddMMhhmm'.log'").format(new Date());

        if(!new File("log/").exists())
            new File("log").mkdir();


        logfile = new File(filename);
        try {
            logfile.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            fw = new FileWriter(logfile);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

但是当我调试时,我可以看到在为特定记录器调用 writeToLog 时,它会跳转到 LoggerTemplate 方法,因此 fw 和 logfile 为空。所以它不起作用。

它不应该工作还是我只是把事情搞砸了,应该进入周末;-)

4

2 回答 2

1

LoggerTemplate调试器在进入writeToLog()方法时进入类应该可以正常工作。奇怪的是基类中的属性有null值。

我已经使用以下简短的测试程序测试了您的代码:

public class Test {
    public static void main(String[] args) {
        LoggerTemplate lt = new JitterBufferLogger();
        lt.writeToLog("Hello");
    }
}

在调用后添加fw.flush()到该LoggerTemplate.writeToLog()方法后fw.write(),它对我有用,日志文件已创建并包含日志消息。

也许 thenew File("log").mkdir()或其他一些调用会引发您看不到的异常,因为stderr已被重定向到某个地方。

于 2012-06-22T10:39:35.463 回答
1

那么可能缺少什么?- 文件写入器刷新可能会有所帮助。- 我无法用原始代码重现空值,不知道发生了什么。- 但正如每个人,包括我在内,都说:它应该有效,而且确实有效。

为什么日志文件中什么都没有?- 也许fw的冲洗丢失了..

无论如何,我用打印机包装它:

public abstract class LoggerTemplate {

    protected String filename ="log/";
    protected File logfile;

    protected PrintWriter pw;

    public void writeToLog(String message) {
            try {
                pw = new PrintWriter(new FileWriter(logfile,true));
                message = new SimpleDateFormat("dd-MM-hh:mm").format(new Date()) + " " + message + "\n";
                pw.write(message);
                pw.flush();
                pw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
    }
}

现在它的工作方式应该和预期的那样。请注意,不再需要具体子类中的 fw 实例化。

于 2012-06-22T10:44:27.360 回答