Is it possible to make a Handler recognize that it had been removed?

不打扰是莪最后的温柔 提交于 2019-12-10 13:32:04

问题


I am writing a custom log configuration class that sets up a particular handler and associates it with the root logger, and plan to use it in multiple applications. I am concerned that actual program code will remove that handler and install a different one.

Is there a way that a handler can detect that it had been removed from a particular logger, or for a logger to report that associates have changed?

My only other alternative is to have a thread that will regularly poll the root loggers handlers and reconnect this handler, which is extremely ugly


回答1:


Is there a way that a handler can detect that it had been removed from a particular logger, or for a logger to report that associates have changed?

In order to produce subclasses of Logger you have to create a custom LogManager. In some environments expect a specific log manager so that may not work.

However, there are a few hacky things that you can try.

  1. Modifying the logger handlers requires logging permission. Run under a SecurityManager that either prevents other threads from access or create a custom SecurityManager that fires some callback when logging control is requested.

  2. If you can get past this being highly implementation specific and fragile you can use the fact that Logger.removeHandler relies on calling Handler.equals(Object). Override equals in your custom handler implementation and use the Throwable.getStackTrace() to examine the frames to check if equals was called from removeHandler. If it was then simply return false.

My only other alternative is to have a thread that will regularly poll the root loggers handlers and reconnect this handler, which is extremely ugly

Get ready for extremely ugly.




回答2:


You could create a custom Logger that overrides removeHandler() to do any special processing that you need, and log to that instead of the root logger.



来源:https://stackoverflow.com/questions/35071921/is-it-possible-to-make-a-handler-recognize-that-it-had-been-removed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!