web app的Log4j应用

本文介绍了Web应用中Log4j的应用,包括建立log.properties文件,设置日志级别和输出方式;建立初始化Action Servlet来初始化日志;以及编写日志记录代码。还展示了log文件的内容,体现了Log4j在Web应用中的具体使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

web appLog4j应用

1 建立log.properties

log level定为INFO,不显示DEBUG信息。log输出依次为文件,控制台

log4j.rootLogger=INFO,R,CONSOLE
#DEBUG,CONSOLE
log4j.addivity.org.apache=true

###################
# Console Appender
###################
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.Threshold=DEBUG
log4j.appender.CONSOLE.Target=System.out
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=[framework] %d - %c -%-4r [%t] %-5p %c %x - %m%n

#####################
# File Appender
,文件满100kb,自动生成
file.log.n
#####################
log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=d:\\file.log
log4j.appender.R.MaxFileSize=100KB
# Keep one backup file
log4j.appender.R.MaxBackupIndex=1

log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n

2 建立初始化Action Servlet
import com.nova.colimas.web.constants.*;
import org.apache.log4j.*;

public class StartupServlet extends Action {
public ActionForward execute(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception{

try{

//初始化log
initLog();
}catch(Exception e){
e.printStackTrace();
return mapping.findForward("failure");
}
Logger logger = Logger.getLogger(this.getClass());
logger.info("init log...");
}

private void initLog() throws Exception{

//获得log.properties绝对地址
java.net.URL myfile=this.getClass().getResource("/resources/log/properties");

//加载log配置文件log.properties
if(myfile.getPath()!=null)
PropertyConfigurator.configure(myfile.getPath());
else
throw new Exception("no log configure");
}
}

3 log

public class LoginAction extends Action {

LoginContext loginContext=null;

LoginForm loginForm=null;

public ActionForward execute(ActionMapping mapping,

ActionForm form,

HttpServletRequest request,

HttpServletResponse response)

throws Exception{

Logger logger = Logger.getLogger(this.getClass());

logger.info("login success");

return mapping.findForward("success");

}

}

log文件内容如下:

INFO http-8080-Processor24 com.nova.colimas.web.action.StartupServlet - init colimas...

INFO http-8080-Processor24 com.nova.colimas.web.action.StartupServlet - init security successfully

INFO http-8080-Processor24 com.nova.colimas.web.action.StartupServlet - init DAO successfully

INFO http-8080-Processor24 com.nova.colimas.web.action.LoginAction - login success

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值