Introduction:
In the development and production environment, we sometimes need to dynamically switch the configuration of the log to debug, monitor, and check the Run-time information of the system.
There are generally two ways of
1, through the Spring Log4jconfiglistener on the start timer to load the configuration file
2, through the JMX dynamic control
You can get more detailed information from my presentation on using spring to manage my applications, including the sample source program, address
http://yulimin.javaeye.com/blog/52354
Let's talk about the difference and disadvantage of the above two methods:
1, through Spring Log4jconfiglistener, you must open the thread in the background, is timed scan, and then to work regularly, a bit wasteful;
2, through the JMX dynamic control must be for a managed port, not only possible port is occupied (of course, there is a workaround to solve it), there are firewalls and so on need to configure this management port for external exposure and so on.
Although the above two methods have some deficiencies, but these two methods in a specific situation, can be very good to use it to work perfectly.
Now, using it for encapsulation and extension, we can subtly customize it and make it easier to dynamically switch configuration information through the Web Console interface without having to restart the running application.
Second, analysis
By analyzing Log4jconfiglistener, the complete class name is Org.springframework.web.util.Log4jConfigListener, the process and principle of dynamic loading can be obtained.
Log4jconfiglistener.java
public class Log4jconfiglistener implements Servletcontextlistener {public
void contextinitialized ( Servletcontextevent event) {
log4jwebconfigurer.initlogging (Event.getservletcontext ());
}
public void contextdestroyed (Servletcontextevent event) {
log4jwebconfigurer.shutdownlogging ( Event.getservletcontext ());
}
It can be learned that everything is done by Log4jwebconfigurer to operate, and then analyze the code, you can get log4jwebconfigurer work process, and thus carried into the log4jconfigurer.
Finally, we can get the most direct and useful three methods, respectively, as follows:
1, log4jconfigurer.initlogging (location);
Initialize the log configuration based on the given configuration file
2, log4jconfigurer.initlogging (location, refreshinterval);
Initializes the log configuration and reloads the configuration file periodically based on the given configuration file and interval.
3, log4jconfigurer.shutdownlogging ();
Close Log
According to the above analysis, the next is the need for a new encapsulation of the work, we also retain the original time loading function, but set through the switch, while the entire function of the encapsulation and expansion.
Iii. Encapsulation and expansion
1, the design of a JavaBean named Log4jrefreshinterval
1.1 defines the following configurable options:
Private String CLASSPATH = "CLASSPATH:";
Private String location = CLASSPATH + "Log4j.xml";
Private String locationrunning = location;
Private long RefreshInterval = 60000;
Private long Refreshsecond = 0;
Private long Refreshminute = 0;
Private long refreshhour = 0;
Private Boolean Refreshdaemon = false;
Increase the Refreshdaemon switch, in the configuration to open whether or not the time to load log configuration file;
Add a series of time configuration parameters, milliseconds, seconds, minutes, and times, and then add and sum to the time.
Refreshhour * 3600 * 1000 + refreshminute * 1000 + refreshsecond * 1000 + refreshinterval;
The 1.2 package method is controlled in the following way
Public interface ilog4jrefreshinterval{public
void init ()/////To initialize log public
void Destroy () based on configuration information;//Destroy Log
public void Refreshintervalthread (); The configuration information for the scheduled load log is public
void refreshintervalimmediately ();//load default log configuration information now public
void Refreshintervalimmediatelybyfilepath (String Log4jfilepath); Loads the specified log profile now public
void Refreshintervalimmediately (Boolean isxmlconfig,string log4jconfiginfo); Load the specified log profile now public
String getrunningconfing () throws exception;//get log configuration information that is running
}
The
1.3 Build Page
is easier to manage through the Web console page, as well as Web Services and so on, because PO JO so you can choose according to the actual situation of the project.
Create the index.html file with the following code:
1.4 Building Controller
This example is controlled directly by using Spring MVC, which is simple and easy to use.
Direct implements Controller to create three Controller, as follows:
Log4jrefreshcontroller the controller to reload the log configuration file
Log4jshutdowncontroller the controller to turn off the log
Log4jrunningcontroller the controller that gets the log configuration information that is running
1.5 Building a Servlet
Used to test whether the log configuration information was successfully loaded
public class HelloServlet extends HttpServlet {private static final long Serialversionuid =-4506255419343502640
L
private static final Logger Logger = Logger.getlogger (Helloservlet.class); public void doget (HttpServletRequest request,httpservletresponse response) {try {servletoutputst
Ream out = Response.getoutputstream ();
Out.println ("
1.6 Building Two JSP pages
A successful page refreshsuccess.jsp, the code is as follows
<% @page contenttype= "text/html; Charset=utf-8 "pageencoding=" UTF-8 "%>
And a failed page refreshfailed.jsp, the code is slightly
1.7 Configuring Spring's Bean file (Service)
Beanreflog4j.xml
<?xml version= "1.0" encoding= "UTF-8"?> <! DOCTYPE beans Public "-//spring//dtd bean//en" "Http://www.springframework.org/dtd/spring-beans.dtd" > <beans&
Gt <bean id= "Propertyconfigurer" class= "Org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" > <property name= "Locations" > <list> <VALUE>CLASSPATH:LOGGERCONSOLE.PROPERTIES&L t;/value> </list> </property> </bean> <bean id= "Log4jrefreshinterval" class = "Net.agile.springtime.logger.util.Log4JRefreshInterval" init-method= "Init" destroy-method= "destroy" > < Property name= "Location" value= "${logger.log4j.location}"/> <property name= "Refreshdaemon" value= G4j.refreshdaemon} "/> <property name= refreshinterval" value= "${logger.log4j.refreshinterval}"/> < Property Name= "Refreshsecond" value= "${logger.log4j.refreshsecond}"/> <property name= "Refreshminut"E "value=" ${logger.log4j.refreshminute} "/> <property name=" Refreshhour "value=" ${logger.log4j.refreshhour} "/ > </bean> </beans>
1.8 Configuring Spring's Bean file (MVC)
Beanrefmvc.xml
<?xml version= "1.0" encoding= "Utf-8"?> <! DOCTYPE beans Public "-//spring//dtd bean//en" "Http://www.springframework.org/dtd/spring-beans.dtd" > <beans&
Gt <bean id= "urlmapping" class= "org.springframework.web.servlet.handler.SimpleUrlHandlerMapping" > <property
Name= "Mappings" > <props> <prop key= "/log4jrefresh.do" >log4JRefreshController</prop> <prop key= "/log4jshutdown.do" >log4JShutdownController</prop> <prop key= "/log4jrunning.do" > log4jrunningcontroller</prop> </props> </property> </bean> <bean id= "vie Wresolver "class=" Org.springframework.web.servlet.view.InternalResourceViewResolver "> <property name="
Prefix "> <value>/WEB-INF/jsp/</value> </property> <property name=" suffix "> <value>.jsp</value> </property> </bean> <beanId= "Log4jrefreshcontroller" class= "Net.agile.springtime.logger.web.Log4JRefreshController" > <property name= "Successview" value= "refreshsuccess"/> <property name= "Failedview" value= "refreshfailed"/> <proper Ty name= "Log4jrefreshinterval" ref= "Log4jrefreshinterval"/> </bean> <bean id= "Log4jshutdowncontroll Er "class=" Net.agile.springtime.logger.web.Log4JShutdownController "> <property name=" Successview "value=" Refreshsuccess "/> <property name=" Failedview "value=" refreshfailed "/> <property name=" Log4JRefresh Interval "ref=" Log4jrefreshinterval "/> </bean> <bean id=" Log4jrunningcontroller "class=" net.agile.s Pringtime.logger.web.Log4JRunningController "> <property name=" Successview "value=" refreshsuccess "/>" Lt;property name= "Failedview" value= "refreshfailed"/> <property name= "Log4jrefreshinterval" ref= "Log4JRefresh" Interval "/> </bean>
</beans>
1.9 Introduce these two Spring profiles into your existing applications, or adjust them to your project structure
<?xml version= "1.0" encoding= "Utf-8"?>
<! DOCTYPE beans Public "-//spring//dtd bean//en" "Http://www.springframework.org/dtd/spring-beans.dtd" >
<beans>
<import resource= "Beanreflog4j.xml"/>
<import resource= "Beanrefmvc.xml"/>
</beans>
1.10 Configuring Web.xml Files
Add the configuration of Spring MVC and the test Servlet configuration in Web.xml, complete with the following configuration:
<! DOCTYPE Web-app Public "-//sun Microsystems, INC.//DTD Web Application 2.3//en" "Http://java.sun.com/dtd/web-app_2_3. DTD "> <web-app> <display-name>spring log4j Refresh web application</display-name> <d Escription>spring log4j Refresh Web application</description> <context-param> <param-name> ;contextconfiglocation</param-name> <param-value>/web-inf/classes/beanrefapplication.xml</ param-value> </context-param> <listener> <listener-class>org.springframework .web.context.contextloaderlistener</listener-class> </listener> <servlet> <servle T-name>dispatcherservlet</servlet-name> <servlet-class> Org.springframework.web.servlet.dispatcherservlet</servlet-class> <load-on-startup>50</ load-on-startup> </servlet> <servlet> <servlet-name>helLoservlet</servlet-name> <display-name>HelloServlet</display-name> <servlet-class>net.
Agile.springtime.logger.web.helloservlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>HelloServlet</servlet-name> <url-pattern>/HelloServlet</url-pattern> &L
T;/servlet-mapping> <servlet-mapping> <servlet-name>dispatcherServlet</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> </web-app>
In this way, your project has the function of dynamic log configuration switch.
Verify the log is successfully changed
1. Start the application, Access http://localhost:8080/Log4J_Spring_Web/as shown in the following image
You can switch dynamically by selecting "log4j file path" or by entering the detailed configuration file's "log4j detailed configuration information" mode directly.
2. View configuration information to view the currently running configuration information, as shown in the following figure:
3. Reload immediately
The default log configuration can be loaded immediately
File and return the default configuration, as shown in the following figure:
4. Stop the log immediately
You can stop the log immediately and display the log configuration information before you stop, as shown in the following figure:
5. Test is normal
This test Servlet allows you to see if the log was successful, and after reloading the new configuration file, it is recommended that you call to test the success of the switch, as shown in the following figure:
Submit the INFO level configuration first
Then look at the result information for the test as follows:
Show Info-level information only
Change to the debug level and submit as follows:
Then look at the result information for the test as follows:
The DEBUG level information is displayed, indicating that the dynamic switch has been successfully performed.
v. Summary
A simple encapsulation and expansion, the implementation of the log configuration for dynamic switching, debugging, monitoring and inspection of the system's Run-time information, a lot of convenience, improve the development efficiency.
Turn from: http://java.chinaitlab.com/Spring/744849.html