简体   繁体   中英

how to use different output logger files in java?

I am trying to have two output loggers in my gui. This code correctly outputs to each file.

public static void main(String[] args) {
    try {
        Handler handler = new FileHandler("OutFile.log");
        Logger.getLogger("myApp").addHandler(handler);
        Logger.getLogger("myApp").setUseParentHandlers(false);
        Handler handler2 = new FileHandler("User.log");
        handler2.setFormatter(new SimpleFormatter());
        Logger.getLogger("User").addHandler(handler2);
        Logger.getLogger("User").setUseParentHandlers(false);


        Logger.getLogger("myApp").severe("AppStarting");
        Logger.getLogger("User").severe("UserLogStarting");

But afterwards when I test the same two lines in the gui it does not work anymore. Is my interpretation of the logger wrong or am I doing something wrong?

Instead if I use the below line in the main (so I removed myApp from the string) then the logger works perfectly throughout the app, but everything goes to one file only.

    Logger.getLogger("").addHandler(handler);

PS I don't want to use a third party class if I can help it.

You need to assign the Logger been returned by Logger.getLogger() to a Logger object, like this:

Logger log = Logger.getLogger("myApp");

and then use log to work. Otherwise Logger.getLogger() will always return a new instance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM