1

我想在单个日志文件中添加异常,在我的源代码中多次使用以下代码......我想将所有异常存储在单个文件中,但它会创建多个文件,如 exception.log、exception.log.1、 exception.log.1.lck、exception.log.2 等等……

Date dir1 = new java.util.Date(System.currentTimeMillis());
String baseDir1 = "/home/gaurav/usr/logs/ESBegin/";
String newDir1 = createDateBasedDirectory(baseDir1, dir1);
System.out.println("Exception :: " + e.getMessage());
Logger logger = Logger.getLogger("MyLog");  
FileHandler fh;  
try {  
    // This block configure the logger with handler and formatter  
    fh = new FileHandler(newDir1+"/exception.log");  
    logger.addHandler(fh);
    SimpleFormatter formatter = new SimpleFormatter();
    fh.setFormatter(formatter);  
    // the following statement is used to log any messages  
    logger.info(e.getMessage()); 
} catch (SecurityException ex) {  
    ex.printStackTrace();  
} catch (IOException ex) {  
    ex.printStackTrace();  
}  
4

1 回答 1

2

这是因为您每次调用该方法时都会创建一个新的 FileHandler,而不是使其成为类实例变量。我测试了它并且它有效:

import java.io.IOException;
import java.util.Date;
import java.util.logging.FileHandler;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;

public class Main {

    private static String newDir1 = "C:\\Users\\pavel.orekhov\\Desktop";
    private static FileHandler fh;

    static {
        try {
            fh = new FileHandler(newDir1 + "\\exception.log", 0, 1, true);
        } catch (IOException | SecurityException e) {
        }
    }

    static void test() {
        Date dir1 = new java.util.Date(System.currentTimeMillis());
        Logger logger = Logger.getLogger("MyLog");
        logger.addHandler(fh);
        SimpleFormatter formatter = new SimpleFormatter();
        fh.setFormatter(formatter);
        logger.info("test");

    }

    public static void main(String[] args) {
        // all these write to the same file
        test();
        test();
        test();
        test();
    }
}

您拥有的代码是这样的:

import java.io.IOException;
import java.util.Date;
import java.util.logging.FileHandler;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;

public class Main {

    static void test() {
        Date dir1 = new java.util.Date(System.currentTimeMillis());
        String newDir1 = "C:\\Users\\pavel.orekhov\\Desktop";
        Logger logger = Logger.getLogger("MyLog");
        FileHandler fh;
        try {
            fh = new FileHandler(newDir1 + "\\exception.log", 0, 1, true);
            logger.addHandler(fh);
            SimpleFormatter formatter = new SimpleFormatter();
            fh.setFormatter(formatter);
            logger.info("test");
        } catch (SecurityException | IOException ex) {
            ex.printStackTrace();
        }
    }

    public static void main(String[] args) {
        test(); // creates file 1
        test(); // creates file 2
        test(); // creates file 3
        test(); // creates file 4
    }
}

test()这确实会创建与您调用该方法一样多的文件。

于 2018-06-21T09:37:48.700 回答