原文地址:http://blog.csdn.net/huoer_12/article/details/10445555
上一节已经介绍了Log4E的安装过程,几种安装方法都有介绍,请仔细阅读。
这节对于Log4E的简单配置做一下示例:
在Window ----- Preferences ---Log4E ,打开Log4E的配置面板,点击 模板 下的 Edit 按钮,对模板进行配置。
图6
imports :就是在引用时需要导入的包,这回出先在 import 块中,不管写的是否使用,配置本身不进行验证;
- import org.apache.log4j.Logger;
- import org.apache.log4j.PropertyConfigurator;
initilializer : 初始化日志,将出现在类的成员区域,作为类的一个字段。
- /**
- * Log4E
- * BasicConfigurator.configure();
- * PropertyConfigurator.configure("log4j.properties");
- */
- private static final Logger ${logger} = Logger.getLogger(${enclosing_type}.class)
使用Log4E的话,前提就是会使用Log4J,记录日志:
在使用Log4j时,要么使用默认的配置,来记录日志,要么使用配置文件来记录日志,Properties文件和XML文件,这里将使用Properties配置文件。在使用默认的配置时,可先声明一下:
- BasicConfigurator.configure();
记得在import 处将BasicConfigurator类引入,或由Eclipse自动修改引入;
如使用配置文件,则使用如下语句:
- PropertyConfigurator.configure("log4j.properties");
在import 处引入PropertyConfigurator类,log4j.properties文件就是配置文件,其路径放在工程的根目录下,与src目录同级,其内容如下:
- log4j.rootLogger=DEBUG,stdout,FILE
- log4j.appender.stdout=org.apache.log4j.ConsoleAppender
- log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
- # Pattern to output the caller's file name and line number.
- log4j.appender.stdout.layout.ConversionPattern=%d{dd MMM yyyy HH:mm:ss,SSS} %c{3} %-4r %5p [%t] (%F:%L) - %m%n
- # log4j.appender.R=org.apache.log4j.FileAppender
- # log4j.appender.R.File=H:\\aa\\example.log
- # log4j.appender.R.Append=true
- # log4j.appender.R.layout=org.apache.log4j.PatternLayout
- # log4j.appender.R.layout.ConversionPattern=%d{dd MMM yyyy HH:mm:ss,SSS} %c{2} %-4r %-5p [%t] %10c %3x - %m%n
- # 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
- log4j.appender.FILE=org.apache.log4j.FileAppender
- log4j.appender.FILE.File=h:\sfile.log
- log4j.appender.FILE.Append=false
- log4j.appender.FILE.layout=org.apache.log4j.SimpleLayout
其中注释的为记录产生日志文件(一直追加类型,没注释的为每次产生的新日志),如需使用,可去掉注释,将文件的第一行改为:
- log4j.rootLogger=DEBUG,stdout,FILE,R
即可。
具体的Log4j使用方法与详细介绍不再这里多说,可自行查阅其他资料。
PS:记得在使用前请导入Log4j包,1.x 与 2.x 的使用不同,请查阅资料,小心使用。在介绍Log4E的时候有这么一段话:
Overview |
Log4E is an Eclipse Plugin which helps you to use your logger easily in Java Projects. 上面的红字部分清楚的介绍了Log4E不依赖于任何框架,即可自行配置。 所以,你可以自己配置日志框架,不一定是Log4j 或是其他的。 配置好后就可以使用了。
下面进行使用: 1、先写一个测试类Log4ETest,这里只是说明一下而已,可做参考;
执行结果不用说,这么简单。 2,使用Log4e来进行记录程序的运行,在代码中点击右键,弹出菜单中有”Log4E“的选择菜单,其中有很多选项,如图:
依照自己的需求选择相应的选项。 3.实例选择,选中”sum“变量,然后选择”Log this variable“,然后会生成代码,记得添加log4j包和手动添加装载配置文件语句;
以上日志代码为自动生成,只有 PropertyConfigurator.configure("log4j.properties"); 为手动添加到程序的前面,配置文件log4j.properties 文件前面已经介绍过了,放到工程根目录下即可。 运行结果:
其他功能自己测试。。。 |