Disabling default console handler in Java Logger by codes

The open source packages usu. relies on log4j or Java Logger to print logs, by default the console handler is attached to the logger thus the logs will be printed to console. In certain cases we need to disable this behavior. Usu. it should be done via a propreties file, but for my special case, a logging properties file is not acceptable.

* suggests some solutions like this: http://*.com/questions/2533227/how-can-i-disable-the-default-console-handler-while-using-the-java-logging-api

But unfortunately this won't work in my case (might be JDK implementation differences? My JDK is 1.7.0_71 ), after some debugging and tracing I finally find how to do this. Past the codes here for later reference as well as for somebody else (happy googler) who may need this:

		{
			/**
			 * Learn in the hard way:
			 *
			 * Via debug, we can get root logger using LogManager.getLogger, as rootLogger is the parent
			 * of all other logers, we can remove the handlers of root logger to avoid log messages be print
			 * to console
                         *
                         * Do not try to call Logger.getGlobal or Logger.getLogger("global"), it is but another child of rootLogger
			 */
			// Logger globalLogger = Logger.getLogger("global");
			// Logger globalLogger = Logger.getGlobal();
			Logger globalLogger = LogManager.getLogManager().getLogger("");

			Handler[] handlers = globalLogger.getHandlers();
			for (Handler handler : handlers) {
				globalLogger.removeHandler(handler);
			}
		}
上一篇:HTML5新增的结构元素


下一篇:Bootstrap modal模态框关闭时,combobox input下拉框仍然保留在页面上