log4j 超完美配置文件!

#【该配置为增加到多大量之后自动生产一个】
#可以设置级别:debug>info>error
#debug:显示debug、info、error
#info:显示info、error
#error:只error
#log4j.rootLogger=debug,appender1
#log4j.rootLogger=info,appender1
#####################可以取消注释
log4j.rootLogger=debug,appender1

#输出到文件(这里默认为追加方式)
#追加的意思重启时候是否重新在已有日志里面写入
log4j.appender.appender1=org.apache.log4j.RollingFileAppender
log4j.appender.appender1.Append =false

#设置文件输出路径
#【1】文本文件
log4j.appender.appender1.File=L:/log.log
#设置文件输出样式【自定义】
log4j.appender.appender1.layout=org.apache.log4j.PatternLayout
#自定义输出格式
log4j.appender.appender1.layout.ConversionPattern =[%d{yy/MM/dd HH:mm:ss:SSS}][%C-%M] %m%n
# %-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n
##7 定义A2的输出文件的最大长度 
log4j.appender.appender1.MaxFileSize = 2KB 
##8 定义A2的备份文件数 
log4j.appender.appender1.MaxBackupIndex=2









#【设置多久更新生成一个文件】
#可以设置级别:debug>info>error
#debug:显示debug、info、error
#info:显示info、error
#error:只error
#log4j.rootLogger=debug,appender1
#log4j.rootLogger=info,appender1
#####################可以取消注释

#log4j.rootLogger=debug,appender1
##输出到文件(这里默认为追加方式)
##追加的意思重启时候是否重新在已有日志里面写入
#log4j.appender.appender1=org.apache.log4j.DailyRollingFileAppender
#log4j.appender.appender1.Append =false
#
##设置文件输出路径
##【1】文本文件
#log4j.appender.appender1.File=L:/log.log
##设置文件输出样式【自定义】
#log4j.appender.appender1.layout=org.apache.log4j.PatternLayout
##自定义输出格式
#log4j.appender.appender1.layout.ConversionPattern =[%d{yy/MM/dd HH:mm:ss:SSS}][%C-%M] %m%n
## %-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n
##定义时间多久生成一个文件
#log4j.appender.appender1.DatePattern = '_'yyyy-MM-dd-HH-mm'.log'







#【文本形式】
#可以设置级别:debug>info>error
#debug:显示debug、info、error
#info:显示info、error
#error:只error
#log4j.rootLogger=debug,appender1
#log4j.rootLogger=info,appender1
#####################可以取消注释
#log4j.rootLogger=debug,appender1
#
##输出到文件(这里默认为追加方式)
##追加的意思重启时候是否重新在已有日志里面写入
#log4j.appender.appender1=org.apache.log4j.FileAppender
#log4j.appender.appender1.Append =true
#
##设置文件输出路径
##【1】文本文件
#log4j.appender.appender1.File=c:/Log4JDemo02.log
##设置文件输出样式
#log4j.appender.appender1.layout=org.apache.log4j.TTCCLayout








#【HTML形式】
#可以设置级别:debug>info>error
#debug:显示debug、info、error
#info:显示info、error
#error:只error
#log4j.rootLogger=debug,appender1
#log4j.rootLogger=info,appender1

#####################可以取消注释
#log4j.rootLogger=debug,appender1

##输出到文件(这里默认为追加方式)
##追加的意思重启时候是否重新在已有日志里面写入
#log4j.appender.appender1=org.apache.log4j.FileAppender
#log4j.appender.appender1.Append =true
##设置文件输出路径
##【2】HTML文件
#log4j.appender.appender1.File=c:/Log4JDemo02.html
##设置文件输出样式
#log4j.appender.appender1.layout=org.apache.log4j.HTMLLayout




#【备注】
#org.apache.log4j.HTMLLayout(以HTML表格形式布局),
#org.apache.log4j.PatternLayout(可以灵活地指定布局模式),
#org.apache.log4j.SimpleLayout(包含日志信息的级别和信息字符串),
#org.apache.log4j.TTCCLayout(包含日志产生的时间、线程、类别等等信息)


#%m   输出代码中指定的消息
#%p   输出优先级,即DEBUG,INFO,WARN,ERROR,FATAL 
#%r   输出自应用启动到输出该log信息耗费的毫秒数 
#%c   输出所属的类目,通常就是所在类的全名 
#%t   输出产生该日志事件的线程名 
#%n   输出一个回车换行符,Windows平台为“/r/n”,Unix平台为“/n” 
#%d   输出日志时间点的日期或时间,默认格式为ISO8601,也可以在其后指定格式,比如:%d{yyy MMM dd HH:mm:ss , SSS},输出类似:2002年10月18日  22 : 10 : 28 , 921  
#%l   输出日志事件的发生位置,包括类目名、发生的线程,以及在代码中的行数。举例:Testlog4.main(TestLog4.java: 10 )






为了更好,此博文更完美。。。

提供配置文件

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>initLogger</servlet-name>
    <servlet-class>servlet.initLogger</servlet-class>
    <init-param>
    	<param-name>log4j</param-name>
    	<param-value>WEB-INF/log4j.properties</param-value>
    </init-param>
     <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>c</servlet-name>
    <servlet-class>servlet.c</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>c</servlet-name>
    <url-pattern>/c</url-pattern>
  </servlet-mapping>

  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>






sevlet  initLogger.java


package servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.PropertyConfigurator;

import util.dao;

public class initLogger extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 7010497166323512560L;

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out
				.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
		out.println("<HTML>");
		out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
		out.println("  <BODY>");
		out.print("    This is ");
		out.print(this.getClass());
		out.println(", using the GET method");
		out.println("  </BODY>");
		out.println("</HTML>");
		out.flush();
		out.close();
	}

	/**
	 * The doPost method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to
	 * post.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out
				.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
		out.println("<HTML>");
		out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
		out.println("  <BODY>");
		out.print("    This is ");
		out.print(this.getClass());
		out.println(", using the POST method");
		out.println("  </BODY>");
		out.println("</HTML>");
		out.flush();
		out.close();
	}

	/*
	 * 通过上下文来取工程路径
	 * 
	 * @return
	 * 
	 * @throws Exception
	 */

	private String getAbsolutePathByContext() throws Exception {

		String webPath = this.getServletContext().getRealPath("/");
		webPath = webPath.replaceAll(
				"[\\\\\\/]WEB-INF[\\\\\\/]classes[\\\\\\/]?", "/");

		webPath = webPath.replaceAll("[\\\\\\/]+", "/");

		webPath = webPath.replaceAll("%20", " ");

		if (webPath.matches("^[a-zA-Z]:.*?$")) {

		} else {

			webPath = "/" + webPath;

		}

		webPath += "/";

		webPath = webPath.replaceAll("[\\\\\\/]+", "/");

		return webPath;

	}

	/**
	 * Initialization of the servlet. <br>
	 * 
	 * @throws ServletException
	 *             if an error occurs
	 */
	public void init() throws ServletException {
		String webPath = null;

		try {

			webPath = getAbsolutePathByContext();
		} catch (Exception e) {

		}

		// 在weblogic 11g 上可能无法从上下文取到工程物理路径,所以改为下面的
		if (webPath == null) {
			try {
				webPath = getAbsolutePathByResource();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if (webPath == null) {
			try {
				webPath = getAbsolutePathByResource();
			} catch (Exception e) {
			}

		}
		String prefix = webPath;
		String file = this.getServletConfig().getInitParameter("log4j");
		System.out.println("prefix = " + prefix);

		String filePath = prefix + file;
		System.out.println(filePath);
		PropertyConfigurator.configure(filePath);
		super.init();// 应用了struts,此方法不能省,ActionServlet覆盖了的此方法中有很多重要操作
	}

	private String getAbsolutePathByResource() throws MalformedURLException,
			URISyntaxException {
		URL url = this.getServletContext().getResource("/");
		String path = new File(url.toURI()).getAbsolutePath();
		if (!path.endsWith("\\") && !path.endsWith("/")) {
			path += File.separator;
		}

		return path;
	}

}




执行方法 c.servlet

package servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import util.Bar;

public class c extends HttpServlet {

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */

	private static Logger logger = Logger.getLogger(c.class);
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		logger.info("不服你tm来打我啊!!!");
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out
				.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
		out.println("<HTML>");
		out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
		out.println("  <BODY>");
		out.print("    This is ");
		out.print(this.getClass());
		out.println(", using the POST method");
		out.println("  </BODY>");
		out.println("</HTML>");
		out.flush();
		out.close();
	}

}




ps: 新手注意

log4j.appender.appender1=org.apache.log4j.DailyRollingFileAppender
org.apache.log4j.DailyRollingFileAppender
log4j.appender.appender1=org.apache.log4j.FileAppender

他们的东西是不一样的,你指定的东西, 有些参数他才生效

我常说,比如、举例才能让话多一些说服力

我就举例

比如,你用了这个

log4j.appender.appender1=org.apache.log4j.FileAppender

这些是无效的。。。

##7 定义A2的输出文件的最大长度 
log4j.appender.appender1.MaxFileSize = 2KB 
##8 定义A2的备份文件数 
log4j.appender.appender1.MaxBackupIndex=2



此文章是网上- -目前最全面的 粘贴可用。。。。不可用,IQ不行或者版本不对。2.0的版本不支持。。谢谢




感谢网友:@yahee 提出的问题。。加载相对路径- -

请看下面

第一修改web.xml





<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>initLogger</servlet-name>
    <servlet-class>servlet.initLogger</servlet-class>
    <init-param>
    	<param-name>log4j</param-name>
    	<param-value>WEB-INF/log4j.properties</param-value>
    </init-param>
    <init-param>
    
    <!--相对路径用-->
    <param-name>log4j_file_path</param-name>  
      <param-value>WEB-INF/logs/</param-value>  
    </init-param>
    <!-- end -->
    
    
     <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>c</servlet-name>
    <servlet-class>servlet.c</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>c</servlet-name>
    <url-pattern>/c</url-pattern>
  </servlet-mapping>

  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>



第二修改


initLogger.java

package servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Properties;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.PropertyConfigurator;

import util.dao;

public class initLogger extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 7010497166323512560L;

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out
				.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
		out.println("<HTML>");
		out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
		out.println("  <BODY>");
		out.print("    This is ");
		out.print(this.getClass());
		out.println(", using the GET method");
		out.println("  </BODY>");
		out.println("</HTML>");
		out.flush();
		out.close();
	}

	/**
	 * The doPost method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to
	 * post.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out
				.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
		out.println("<HTML>");
		out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
		out.println("  <BODY>");
		out.print("    This is ");
		out.print(this.getClass());
		out.println(", using the POST method");
		out.println("  </BODY>");
		out.println("</HTML>");
		out.flush();
		out.close();
	}

	/*
	 * 通过上下文来取工程路径
	 * 
	 * @return
	 * 
	 * @throws Exception
	 */

	private String getAbsolutePathByContext() throws Exception {

		String webPath = this.getServletContext().getRealPath("/");
		webPath = webPath.replaceAll(
				"[\\\\\\/]WEB-INF[\\\\\\/]classes[\\\\\\/]?", "/");

		webPath = webPath.replaceAll("[\\\\\\/]+", "/");

		webPath = webPath.replaceAll("%20", " ");

		if (webPath.matches("^[a-zA-Z]:.*?$")) {

		} else {

			webPath = "/" + webPath;

		}

		webPath += "/";

		webPath = webPath.replaceAll("[\\\\\\/]+", "/");

		return webPath;

	}

	/**
	 * Initialization of the servlet. <br>
	 * 
	 * @throws ServletException
	 *             if an error occurs
	 */
	public void init() throws ServletException {
		String webPath = null;

		try {

			webPath = getAbsolutePathByContext();
		} catch (Exception e) {

		}

		// 在weblogic 11g 上可能无法从上下文取到工程物理路径,所以改为下面的
		if (webPath == null) {
			try {
				webPath = getAbsolutePathByResource();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if (webPath == null) {
			try {
				webPath = getAbsolutePathByResource();
			} catch (Exception e) {
			}

		}
		String prefix = webPath;
		String file = this.getServletConfig().getInitParameter("log4j");
		System.out.println("prefix = " + prefix);
		
		//获取加载log地址
		String logFile=this.getInitParameter("log4j_file_path");   
		System.out.println("log4j_file_path:"+logFile);
		
		//log4j.properties文件地址
		String filePath = prefix + file;
		System.out.println(filePath);
		
		//读取配置文件
		Properties prop = new Properties();
		
		try {
			prop.load(new FileInputStream(filePath));
			设置日志文件的输出路径   
			System.out.println(prop.getProperty("log4j.appender.appender1.File"));;
			//设置log存放地址
			prop.setProperty("log4j.appender.appender1.File", prefix+logFile+"log.log");
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		try {
			//覆盖原log4j.properties  并且加载新的有log输出的log4j.properties文件
			prop.store(new FileOutputStream(filePath),"#");
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		/**其实这里可以这样写
		 	PropertyConfigurator.configure(prop);
		 	
		 	
		try {
			//覆盖原log4j.properties  并且加载新的有log输出的log4j.properties文件
			prop.store(new FileOutputStream(filePath),"#");
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		
		就没用了,,,因为是洁癖- -程序里面我也这样
		 	
		 * 
		 */
		
		

		
		//加载log文件
		PropertyConfigurator.configure(filePath);
		super.init();// 应用了struts,此方法不能省,ActionServlet覆盖了的此方法中有很多重要操作
	}

	private String getAbsolutePathByResource() throws MalformedURLException,
			URISyntaxException {
		URL url = this.getServletContext().getResource("/");
		String path = new File(url.toURI()).getAbsolutePath();
		if (!path.endsWith("\\") && !path.endsWith("/")) {
			path += File.separator;
		}

		return path;
	}

}



这样程序就实现了,加载相对路径,,

其实写这个相对路径0 0 你还不如直接写死路径,坑爹啊

回答完毕,不知小的回答得如何啊








转载于:https://my.oschina.net/openoschina/blog/306323

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值