对LOG4J日志操作的一点心得

           JAVA中通常用的日志工具就是LOG4J,而开发包就是开源的“commons-logging”包。这个包里包含了通用的API(又称通用接口)和一个通过日志实现(个人认为就相当于驱动程序库)。但这个包里的日志实现功能有限,所以我们通常会用到另外一个包(或者说驱动)----“log4j”包,这个包主要提供三个组件(就是三个主要类)。同时我们还应该在我们程序目录下“/WEB-INF/classes”里建一个配置驱动信息和日志功能的配置文件。
我们在程序中调用日志则很简单,分两步就可以。

1、创建“Log”对象:Log log=LogFactory.getLog(classname);


2、调用“log对象”的输出日志方法,如:log.trace(string)、log.debug(string)、log.info(string)、log.warn(string)、log.falte(string)。

注:log类也提供isTraceEnable()、isDebugEnable()、isInfoEnable()等判断当前调试级别是否大于设置级别,如果大于或等于则返回真。

3、配置好日志文件。驱动根据配置文件决定是否输出、输出到什么地方以及按什么格式输出。
配置文件名为log4j.properties       。

部分代码如下:
# Sample Log4J configuration for a typical Spring web app.
# Standard Log4J syntax applies.

# Log all messages down to level INFO.
# Write messages to console and to example.log file.
log4j.rootLogger=DEBUG, stdout,

# Defines the console logger.
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p %c - %m%n

# Defines the file logger, using the "web app root" system property
# (set by Log4jConfigListener) for a log file relative to the web app.
#log4j.appender.examplefile=org.apache.log4j.FileAppender
#log4j.appender.examplefile.File=${example.root}/WEB-INF/example.log
# Pattern to output: date priority [category] - message
#log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
#log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - %m%n

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值