Java控制台两行同时输出,Java记录器控制台流重复输出

I hope this question has a simple answer. I am trying to add a logger to my Java application. I was able to format the log file perfectly, but I ran into an issue when trying to add a ConsoleHandler to the logger to format the console output.

Once I added the ConsoleHandler, every log message is not printed out three times, twice with the proper formatting I want, and then once with the original format that I do not want.

Ill post my code below, not sure at all what I am doing wrong.

Any help will be greatly appreciated.

// remove and handlers that will be replaced

Handler[] handlers = logger.getHandlers();

for(Handler handler : handlers)

{

if(handler.getClass() == ConsoleHandler.class || handler.getClass() == FileHandler.class)

logger.removeHandler(handler);

}

// file handler

FileHandler fh = new FileHandler(file.toString());

fh.setFormatter(new MS2Formatter());

logger.addHandler(fh);

// console handler

ConsoleHandler ch = new ConsoleHandler();

ch.setFormatter(new MS2Formatter());

logger.addHandler(ch);

logger.setLevel(Level.INFO);

EDIT: Answer

Just wanted to post my final code here to help anyone with a similar problem.

logger = Logger.getLogger("My Logger");

logger.setUseParentHandlers(false);

// remove and handlers that will be replaced

Handler[] handlers = logger.getHandlers();

for(Handler handler : handlers)

{

if(handler.getClass() == ConsoleHandler.class)

logger.removeHandler(handler);

}

// setup the file

File file = new File(location + "/" + fileName);

// file handler

FileHandler fh = new FileHandler(file.toString(), true);

fh.setFormatter(new MS2Formatter());

logger.addHandler(fh);

// console handler

ConsoleHandler ch = new ConsoleHandler();

ch.setFormatter(new MS2Formatter());

logger.addHandler(ch);

// remove and handlers that will be replaced

logger.setLevel(Level.INFO);

解决方案

Exactly how many handlers do you need? addHandler() adds the handler you've created to the handlers associated with that logger. So you have the default handler, and the 2 you've added in your code - FileHandler and ConsoleHandler.

You can get the current set of handlers using the getHandlers() method and use removeHandler() to remove the handlers you don't need.

EDIT

In your case, chances are that the parent handlers are being used. So even though you think you are removing the handlers, if you actually debug the code, you'll see that during execution the in the for loop you never really remove a handler at all (or at least not a ConsoleHandler).

To prevent parent handlers from being used, use this statement.

logger.setUseParentHandlers(false);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值