java web工程中logback换配置文件的路径

本人小网站:   http://51kxd.com/  欢迎大家不开心的时候访问访问,调节一下心情


web.xml中配置:




logbackConfigLocation
file:/datum/Data/conf/config/logback.xml




logbackConfigLocation
file:E:\\datum\\data\\conf\\logback.xml


其中file:一定要有。



com.cxfmvcstu.comn.LogbackConfigListener

LogbackConfigListener为自己的实现类

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.UrlResource;

import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.joran.JoranConfigurator;
import ch.qos.logback.core.joran.spi.JoranException;


/**
 * @description 
 * @path com.cxfmvcstu.comn.LogbackConfigListener
 * @author lijun.justin
 * @time 2015年6月27日 下午8:13:19
 */
public class LogbackConfigListener implements ServletContextListener {
	private static final Logger logger = LoggerFactory.getLogger(LogbackConfigListener.class);

	private static final String CONFIG_LOCATION = "logbackConfigLocation";

	@Override
	public void contextInitialized(ServletContextEvent event) {
		// 从web.xml中加载指定文件名的日志配置文件
		String logbackConfigLocation = event.getServletContext().getInitParameter(CONFIG_LOCATION);
		String fn = event.getServletContext().getRealPath(logbackConfigLocation);
		try {
			UrlResource urlResource = new UrlResource(logbackConfigLocation);
			LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
			loggerContext.reset();
			JoranConfigurator joranConfigurator = new JoranConfigurator();
			joranConfigurator.setContext(loggerContext);
			//joranConfigurator.doConfigure(fn);
			joranConfigurator.doConfigure(urlResource.getFile().getAbsolutePath());
			logger.debug("loaded slf4j configure file from {}", fn);
		} catch (JoranException e) {
			logger.error("can loading slf4j configure file from " + fn, e);
		}catch (Exception e) {
			logger.error(e.getMessage(), e);
		}

	}

	@Override
	public void contextDestroyed(ServletContextEvent event) {
	}
}

要依赖于spring的UrlResource类。里面无用的代码,读者自己精简一下


logback.xml的配置示例:



  



%date [%thread] %-5level %logger{80} - %msg%n





class="ch.qos.logback.core.rolling.RollingFileAppender">

INFO
ACCEPT
DENY


D:/logs/INFO.%d{yyyy-MM-dd}.log
30


%date [%thread] %-5level %logger{80} - %msg%n







ERROR
ACCEPT
DENY


D:/logs/error.%d{yyyy-MM-dd}.log
30


%date [%thread] %-5level %logger{80} - %msg%n



















 



本人小网站:   http://51kxd.com/  欢迎大家访问

你可能感兴趣的:(linux,java,日志,logback)