Log4j 实现运行时的日志级别更改

首先定义一个工具类Log4jConfig,具体如下:

import org.apache.log4j.Level;
import org.apache.log4j.LogManager;

public class Log4jConfig {

	public void enableInfo(String target){
		LogManager.getLogger(target).setLevel(Level.INFO);
		}

		public void enableWarn(String target){
		LogManager.getLogger(target).setLevel(Level.WARN);
		}

		public void enableError(String target){
		LogManager.getLogger(target).setLevel(Level.ERROR) ;
		}

		public void enableDebug(String target){
		LogManager.getLogger(target).setLevel(Level.DEBUG) ;
		}
		public void enableTrack(String target){
			LogManager.getLogger(target).setLevel(Level.TRACE) ;
		}
		
		public void enableOff(String target){
			LogManager.getLogger(target).setLevel(Level.OFF) ;
		}

}


然后定义action,定义为Log4jAction,里面定义3个方法分别用户新增日志对象、查询日志对象列表、更改日志对象的级别,具体如下:

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
public class Log4jAction {
	
	Log4jConfig config = new Log4jConfig();
	//日志对象列表
	private List<Logger> loggers;
	
	//日志对象名称
	private String name;
	//日志对象级别
	private String level;
	
	/** 
	 * 日志列表*/
	public String getLogList()
	{
		//日志列表
		loggers = new ArrayList<Logger>();
		//获取根日志
		Logger rootLogger = Logger.getRootLogger();		
		loggers.add(rootLogger);
				
		//获取当前所有的日志对象
		Enumeration<Logger> enumer = (Enumeration<Logger>)rootLogger.getLoggerRepository().getCurrentLoggers();				
		while(enumer.hasMoreElements())
		{
			Logger logger = enumer.nextElement();
			if((null != level) && (!"".equals(level)) && (!"ALL".equals(level))
					&& (null != logger.getLevel()) && (!logger.getLevel().toString().equals(level)))
			{
					continue;				
			}
			
			if((null != name) && (!"".equals(name)) && (!logger.getName().contains(name)))
			{
					continue;
			}
			loggers.add(logger);
		}
		
		return SUCCESS;
	}

	/** 
	 * 更新日志级别
	 * @return
	 */
	public String editLoggerLevel()
	{
		if(Level.INFO.toString().equals(level))
		{
			config.enableInfo(name);
		}
		
		else if(Level.ERROR.toString().equals(level))
		{
			config.enableError(name);
		}
		else if(Level.DEBUG.toString().equals(level))
		{
			config.enableDebug(name);
		}
		else if(Level.WARN.toString().equals(level))
		{
			config.enableWarn(name);
		}
		else if(Level.OFF.toString().equals(level))
		{
			config.enableOff(name);
		}
		
		return SUCCESS;
	}
	
	/** 
	 * 新增日志对象 
	 * @return
	 * @throws IOException 
	 */
	public String addNewLogger() throws IOException
	{
		Logger log = ("".equals(name) ?
	                Logger.getRootLogger() : Logger.getLogger(name));
	    log.setLevel(Level.toLevel(level, Level.DEBUG));	
	    
	    printStr("1");
	     
		return null;
	}
	
	public void printStr(String jsonStr) throws IOException{
		HttpServletResponse  httpServletResponse  = ServletActionContext.getResponse();
		httpServletResponse.setCharacterEncoding("UTF-8");
		httpServletResponse.setContentType("text/x-json;charset=UTF-8");
		PrintWriter pw = httpServletResponse.getWriter();
		pw.print(jsonStr);
		pw.flush();
		pw.close();
	}
	
	/**
	 * @return loggers
	 */
	public List<Logger> getLoggers() {
		return loggers;
	}

	/**
	 * @return name
	 */
	public String getName() {
		return name;
	}

	/**
	 * @param name
	 */
	public void setName(String name) {
		this.name = name;
	}

	/**
	 * @return level
	 */
	public String getLevel() {
		return level;
	}

	/**
	 * @param level
	 */
	public void setLevel(String level) {
		this.level = level;
	}
}


然后在sturts配置文件中配置action具体如下:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
	<package name="log4j" extends="struts-default" namespace="/">
		<action name="getLogList" class="log4jAction" method="getLogList">
			<result name="success" >/log4j2.jsp</result>
		</action>
		
		<action name="editLoggerLevel" class="log4jAction" method="editLoggerLevel" >
			<result name="success" type="redirect">getLogList.do </result>  
		</action>	
		
		<action name="addNewLogger" class="log4jAction" method="addNewLogger" >
		</action>	
					
	</package>
</struts>


接着实现页面log4j.jsp,具体如下:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
   <style type="text/css">
    .add{ height:30px; line-height:30px; float:right; font-size:14px;}
    .add a{ color:#000000; margin:0px 10px;}
    .clear{ display:block; height:0px; line-height:0px; font-size:0px; clear:both;}
    .fd{ width:100%; height:auto; position:absolute; top:150px; left:0px; z-index:1; display:none;}
    .fd_box{ width:320px; height:auto; margin:0px auto; position:relative; }
    .tm_box{ width:300px; height:200px; padding:10px; background-color:#808080; -webkit-border-radius:5px;-moz-border-radius:5px;border-radius:5px; FILTER: alpha(opacity=50); opacity: 0.5; -moz-opacity: 0.5; position:absolute; top:0px; left:0px; z-index:2;}
    .add_box{ width:280px; height:180px; padding:10px; background-color:#808080; -webkit-border-radius:5px;-moz-border-radius:5px;border-radius:5px; position:absolute; top:10px; left:10px; z-index:3; font-family:"宋体";}
    .add_box h1{ width:270px; height:30px; line-height:30px; font-size:14px; margin:0px; padding:0px 5px; font-weight:100; color:#666666; border-bottom:1px solid #009999;}
    .add_box span{ color:#000000; display:block; margin:10px 0px; padding:0px 5px;}
    .clos{ width:14px; height:13px; background-image:url(/images/close3.gif); background-repeat:no-repeat; position:absolute; top:25px; right:25px; z-index:4; cursor: pointer;}
    .box{ width:760px; height:auto; margin:0px auto; border-top:1px solid #f9f9f9;}
    .box img{ margin:50px auto; display:block; border:0px;}
    </style> 
    
    <script type="text/javascript" src="script/jquery-1.8.2.min.js"></script>
    <script type="text/javascript">
    $(document).ready(function(){
    $("#addNewLogger").click( function(){
    $(".fd").show();
    return false;
    });
    $(".clos").click( function(){
    $(".fd").hide();
    });
    
    $("#addButton").click( function(){
    	
    	var level = $("#logLevel").val();
		var name = $("#logName").val();
		
		if(level=='')
		{
			alert("Level must be not null!!!");
			return;
		}
		
		if(name=='')
		{
			alert("Name must be not null!!!");
			return;
		}
				
    	var param={};
    	param['level'] = level;
		param["name"] = name;
		
		$.post("addNewLogger.do",param,function(data){	    	
		  	if(data == "1"){
		  		alert("Add new logger success!!!");		
		  		window.location.href = "getLogList.do";
	    	}
		  	else {
		  		alert("System error!!!");
		  	} 
		  	$(".fd").hide();
		 });
		      
        });
      });
    </script>
	<div>
	
	<form action="getLogList.do" method="post">
	    <table style="margin-bottom: 8px;" cellspacing="0" cellpadding="0"
							width="60%" border="0" align="center">
							<tbody>
							<tr>
								<td class="f66" align="center" width="80%" height="36px">Level:    
									<select name="level">
                                        <option value="ALL" selected="selected">ALL</option>
                                          <s:generator separator="," val="'DEBUG,INFO,WARN,ERROR,OFF'">  
                                              <s:iterator value="top" id="inner">  
                                                 <option value="<s:property/>" <s:if test="#requestlevel==#inner">selected="selected </s:if>><s:property/></option>                                                       
                                              </s:iterator>  
                                           </s:generator>
                                      </select>
                                         
                                      logger:    <input id="name" name="name" value="${name }"/>
									     
									<input id="search" type="submit" value="search" name="search" class="scbtn"/>
								</td>
								<td align="center">
									<input type="button" value="addNewLogger" id="addNewLogger" />
								</td>
							</tr>
							</tbody>
						</table>
	</form>
	
	<div class="fd">
    <div class="fd_box">
    <div class="tm_box"></div>
    <div class="add_box">
    <h1 style="color:#000000">Add New Logger</h1>
    <span>Level:	<select style="width:150px; height:23px;" id="logLevel"  name="logLevel">
                                        <option value="DEBUG" selected="selected">DEBUG</option>
                                          <s:generator separator="," val="'INFO,WARN,ERROR,OFF'">  
                                              <s:iterator>  
                                                 <option value="<s:property/>"><s:property/></option>                                                       
                                              </s:iterator>  
                                           </s:generator>
                                      </select>
     </span>
    <span>Name:  <input id="logName"  name="logName" id="logName" type="text" /></span>   
    <span>       <input  id="addButton" value="Add"  name="addButton" type="button" /></span>
    </div>
    <div class="clos"></div>
    </div>
    </div>
	
		<table id="gvNews" style="width: 80%; color: #333333;"
			cellspacing="1" cellpadding="3" border="1" align="center">
			<tbody>
				<tr>
					
					<th scope="col" width="100px">
						Level
					</th>
					<th scope="col">
						Logger
					</th>
					<th scope="col" width="400px">
						Set New Level
					</th>
				
				</tr>		
				
				<s:iterator value="loggers" var="bean" status="st">
					<tr>
					
						<td align="center">
							${level}
						</td>
						<td>
							${name}
						</td>

						<td>
						<s:generator separator="," val="'DEBUG,INFO,WARN,ERROR,OFF'">  
                            <s:iterator>  
                             <a href="editLoggerLevel.do?name=${name}&level=<s:property/>"> <s:property/> </a>                                 
                           </s:iterator>  
                         </s:generator>
						
							
						</td>
						</tr>
				</s:iterator>
			</tbody>
		</table>
	</div>


 

你可能感兴趣的:(Log4j 实现运行时的日志级别更改)