网上太多博客都讲不清楚…忍不住了,最恶心的是你转载copy过来好歹看一下格式吧,一半文件有格式一半文件没格式恶心谁啊
明确目的:只需要在控制台中输出即可
添加依赖
首先添加依赖,这里需要会使用maven
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.14</version>
</dependency>
配置文件
个人的配置,具体可以看下面的连接,可以根据不同情况来配置,如果要输出到文本还要修改…
log4j.rootLogger = debug, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=[%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n
初始化配置文件
根据:log4j在javaWeb项目中的使用〰 我改了一下代码,写完之后需要在web.xml中配置
public class Log4JInitServlet extends HttpServlet {
@Override
public void init(ServletConfig config) throws ServletException {
System.out.println("Log4JInitServlet 正在初始化 log4j日志设置信息");
String log4jLocation = config.getInitParameter("log4j-properties-location");
ServletContext sc = config.getServletContext();
String str= sc.getInitParameter("test");
System.out.println("str:"+str);
if (log4jLocation == null) {
System.err.println("*** 没有 log4j-properties-location 初始化的文件, 所以使用 BasicConfigurator初始化");
BasicConfigurator.configure();
} else {
String webAppPath = sc.getRealPath("/");
String log4jProp = webAppPath + log4jLocation;
File yoMamaYesThisSaysYoMama = new File(log4jProp);
if (yoMamaYesThisSaysYoMama.exists()) {
System.out.println("使用: " + log4jProp+"初始化日志设置信息");
PropertyConfigurator.configure(log4jProp);
} else {
System.err.println("*** " + log4jProp + " 文件没有找到, 所以使用 BasicConfigurator初始化");
BasicConfigurator.configure();
}
}
super.init(config);
}
}
<servlet>
<servlet-name>Log4JInitServlet</servlet-name>
<servlet-class>top.sehnsucht.Log4JInitServlet</servlet-class>
<init-param>
<param-name>log4j-properties-location</param-name>
<param-value>log4j.properties</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
之后在java文件中如何使用?
使用前输入 private Logger logger=Logger.getLogger(this.getClass());
,看下示例就懂了
public class TestServlet extends HttpServlet {
private Logger logger=Logger.getLogger(this.getClass());
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
logger.debug("你好啊");
logger.info("我不好");
logger.error("她和你都很好");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}