如何使用java.util.logging.FileHandler将日志存储在单个日志文件中?

时间:2018-06-21 09:03:59

标签: java exception apache-flink logfile single-file

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

type DataKeys<T> = { [P in keyof T] : T[P] extends Function ? never : P }[keyof T]
type Data<T> = Pick<T, DataKeys<T>>; 


getById(id: number) {
   return this.http.get<Data<User>>(`/api/v1/admin/users/${id}`);
}

this.userService.getById(1).subscribe(data => this.user = Object.assign(new User(),  data));

1 个答案:

答案 0 :(得分:0)

这是因为每次调用该方法时都会创建一个新的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()方法一样多的文件。