25 2月 2011

Manage Logger Level via JMX

常用的Log library不外乎logback跟log4j,logback自備了JMX控制的功能,只要在logback.xml中加入

<configuration> 
	<jmxConfigurator />
</configuration>

lo4j沒有,但只要簡單地寫個小小Util就可以達成

@ManagedResource(objectName = "log4j:name=Lo4jLoggerManager", description = "log4j logger level manager")
public class Lo4jLoggerManager {
	@ManagedOperation
	@ManagedOperationParameters({@ManagedOperationParameter(name="loggerName", description=""), 
		@ManagedOperationParameter(name="loggerLevel", description="")})
	public void setLoggerLevel(String loggerName, String loggerLevel) {
		Logger logger = Logger.getLogger(loggerName);
		logger.setLevel(Level.toLevel(loggerLevel));
	}
	
	@ManagedOperation
	@ManagedOperationParameters({@ManagedOperationParameter(name="loggerName", description="")})
	public String getLoggerLevel(String loggerName) {
		Logger logger = Logger.getLogger(loggerName);
		Level level = logger.getEffectiveLevel();
		
		return null != level ? level.toString():Logger.getRootLogger().getLevel().toString();
	}
}

沒有留言: