LOG4J对单服务器多SERVER的集群服务的日记输出支持

LOG4J对单服务器多SERVER的集群服务的日志输出支持
增加LOG4J对单服务器多SERVER的集群服务的日志输出支持
问题:在单台物理服务器上部署的集群中含有多个Server Application时,发布的应用只有一个 WAR包,对应的LOG4J的配置也仅有一个,多个Server Application同时将输出的日志文件写入到一个文件中,会造成日志的丢失,因此设计该方法是为了多个Server Application分别输出各自的日志文件.

思路:
1.log4j的配置文件支持System Property的环境变量的获取,如user home
2.通过ServletContext可以获取到集群中每个server name
3.在不同的server启动时将不同server name的加载到System Property
4.在配置文件中增加一个${WebAppClusterServer}的参数,拼合server_name+logfile_name
5.配置文件的定义:
**************************************************
*logpath=e:/${WebSphereAppHost}_
*log4j.appender.logfile.File=${logpath}test.log
**************************************************

这是思路,需要源码的可以EMAIL我
源码是基于org.springframework.util.Log4jConfigurer进行改造

public class Log4jWebClusterConfig {

	/** Parameter specifying whether to expose the web app cluster property */
	public static final String EXPOSE_WEB_APP_ClUSTER_PARAM = "log4jExposeWebAppCluster";
	public static final String EXPOSE_WEB_APP_ClUSTER_ATTRIBUTE_PARAM = "log4jExposeWebAppClusterAttribute";

	public static void initWebClusterConfig(ServletContext servletContext) throws IllegalArgumentException {
		String webappcluster = servletContext.getInitParameter(EXPOSE_WEB_APP_ClUSTER_PARAM);
		String webappclusterattribute = servletContext.getInitParameter(EXPOSE_WEB_APP_ClUSTER_ATTRIBUTE_PARAM);
		if (webappcluster != null) {
			if (webappclusterattribute == null) {
				throw new IllegalArgumentException(
					"log4jExposeWebAppClusterAttribute is null ! "
						+ "  If set property 'log4jExposeWebAppCluster',"
						+ "'log4jExposeWebAppClusterAttribute' must not be null ");
			}
			String webappclusterattr = (String) servletContext.getAttribute(webappclusterattribute);
			if (webappclusterattr == null || webappclusterattr.equals("")) {
				throw new IllegalArgumentException(
					"Cannot get log4jExposeWebAppClusterAttribute=["
						+ webappclusterattribute
						+ "]"
						+ "  please reconfirm log4jExposeWebAppClusterAttribute's value!");
			}

			//only getAttribute for WebSphere,other WebContain need to reconfigure!!
			if (webappcluster.equals("WebSphere")) {
				System.setProperty("WebAppClusterServer", webappclusterattr);
			}
			servletContext.log(
				"Initialize Log4J For Web_App_Cluster=[" + webappcluster + "] Server=[" + webappclusterattr + "]");
		}

	}
	
	
//	getServletContext().log("----getAttributeNames----");
//	Enumeration vecKey = getServletContext().getAttributeNames();
//	while (vecKey.hasMoreElements()) {
//		String strKey = (String) vecKey.nextElement();
//		getServletContext().log("Key=[" + strKey + "] Value=[" + getServletContext().getAttribute(strKey) + "]");
//	}
//		
//	getServletContext().log("----System.getProperties----");
//	vecKey = propertiesInst.propertyNames();
//	while (vecKey.hasMoreElements()) {
//		String strKey = (String) vecKey.nextElement();
//		getServletContext().log("Key=[" + strKey + "] Value=[" + propertiesInst.getProperty(strKey) + "]");
//	}
//		
//		
//	getServletContext().log("----getInitParameterNames----");
//	vecKey = getServletContext().getInitParameterNames();
//	while (vecKey.hasMoreElements()) {
//		String strKey = (String) vecKey.nextElement();
//		getServletContext().log("Key=[" + strKey + "] Value=[" + getServletContext().getInitParameter(strKey) + "]");
//	}
//		
//	getServletContext().log("getServletContextName="+getServletContext().getServletContextName());

}



public abstract class Log4jWebConfigurer {

	/** Parameter specifying the location of the Log4J config file */
	public static final String CONFIG_LOCATION_PARAM = "log4jConfigLocation";

	/** Parameter specifying the refresh interval for checking the Log4J config file */
	public static final String REFRESH_INTERVAL_PARAM = "log4jRefreshInterval";

	/** Parameter specifying whether to expose the web app root system property */
	public static final String EXPOSE_WEB_APP_ROOT_PARAM = "log4jExposeWebAppRoot";

	/**
	 * Initialize Log4J, including setting the web app root system property.
	 * @param servletContext the current ServletContext
	 * @see WebUtils#setWebAppRootSystemProperty
	 */
	public static void initLogging(ServletContext servletContext) {
		// Expose the web app root system property.
		if (exposeWebAppRoot(servletContext)) {
			WebUtils.setWebAppRootSystemProperty(servletContext);
		}

		//Expose the web app cluster property.
		Log4jWebClusterConfig.initWebClusterConfig(servletContext);

		// Only perform custom Log4J initialization in case of a config file.
		String location = servletContext.getInitParameter(CONFIG_LOCATION_PARAM);
		if (location != null) {
			// Perform actual Log4J initialization; else rely on Log4J's default initialization.
			try {
				// Return a URL (e.g. "classpath:" or "file:") as-is;
				// consider a plain file path as relative to the web application root directory.
				if (!ResourceUtils.isUrl(location)) {
					// Resolve system property placeholders before resolving real path.
					location = SystemPropertyUtils.resolvePlaceholders(location);
					location = WebUtils.getRealPath(servletContext, location);
				}

				// Write log message to server log.
				servletContext.log("Initializing Log4J from [" + location + "]");

				// Check whether refresh interval was specified.
				String intervalString = servletContext.getInitParameter(REFRESH_INTERVAL_PARAM);
				if (intervalString != null) {
					// Initialize with refresh interval, i.e. with Log4J's watchdog thread,
					// checking the file in the background.
					try {
						long refreshInterval = Long.parseLong(intervalString);
						Log4jConfigurer.initLogging(location, refreshInterval);
					}
					catch (NumberFormatException ex) {
						throw new IllegalArgumentException("Invalid 'log4jRefreshInterval' parameter: " + ex.getMessage());
					}
				}
				else {
					// Initialize without refresh check, i.e. without Log4J's watchdog thread.
					Log4jConfigurer.initLogging(location);
				}
			}
			catch (FileNotFoundException ex) {
				throw new IllegalArgumentException("Invalid 'log4jConfigLocation' parameter: " + ex.getMessage());
			}
		}
	}

	/**
	 * Shut down Log4J, properly releasing all file locks
	 * and resetting the web app root system property.
	 * @param servletContext the current ServletContext
	 * @see WebUtils#removeWebAppRootSystemProperty
	 */
	public static void shutdownLogging(ServletContext servletContext) {
		servletContext.log("Shutting down Log4J");
		try {
			Log4jConfigurer.shutdownLogging();
		}
		finally {
			// Remove the web app root system property.
			if (exposeWebAppRoot(servletContext)) {
				WebUtils.removeWebAppRootSystemProperty(servletContext);
			}
		}
	}

	/**
	 * Return whether to expose the web app root system property,
	 * checking the corresponding ServletContext init parameter.
	 * @see #EXPOSE_WEB_APP_ROOT_PARAM
	 */
	private static boolean exposeWebAppRoot(ServletContext servletContext) {
		String exposeWebAppRootParam = servletContext.getInitParameter(EXPOSE_WEB_APP_ROOT_PARAM);
		return (exposeWebAppRootParam == null || Boolean.valueOf(exposeWebAppRootParam).booleanValue());
	}

}


   <context-param>
       <param-name>log4jExposeWebAppCluster</param-name>
       <param-value>WebSphere</param-value>
   </context-param>
   <context-param>
       <param-name>log4jExposeWebAppClusterAttribute</param-name>
       <param-value>com.ibm.websphere.servlet.application.host</param-value>
   </context-param>
	<servlet>
		<servlet-name>Log4jConfigServlet</servlet-name>
		<display-name>Log4jConfigServlet</display-name>
		<servlet-class>com.xxxxx.log4j.web.Log4jConfigServlet</servlet-class>
		<load-on-startup>4</load-on-startup>
	</servlet>



1 楼 sunman5277 2012-07-10  
我在部署weblogic集群时也遇到和你相同的问题,1个服务器部署了4个server,请问你具体是怎么解决的?望不吝赐教