eclipse中纯java配置log4j日志

时间:2022-07-18 15:57:06

1、新建java项目log4Test

2、新建目录lib,把log4j-1.2.9.jar包放入lib目录

3、右键工程,选择Properties->Java Build Path->Libraries->Add JARs...,选择lib下的log4j-1.2.9.jar

4、在src目录下新建两个文件log4j.properties和log.txt

log4j.properties文件配置如下:

log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n
log4j.appender.logfile=org.apache.log4j.FileAppender
log4j.appender.logfile.File=target/spring.log
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - %m%n

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=%d{yyyy/MM/dd HH:mm:ss:SSS} %5p %c:%L - %m%n

log4j.appender.file=org.apache.log4j.FileAppender

#实际项目路径要对应上
log4j.appender.file.File=E:/workspace/log4Test/src/log.txt
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy/MM/dd HH:mm:ss:SSS} %5p %c:%L - %m%n

log4j.rootLogger=info,file

5、新建LogTest 测试类,如下

package com.test;

import org.apache.log4j.Logger;

public class LogTest {

    public static Logger logger = Logger.getLogger(Test.class);
public static void main(String[] args) {
// TODO Auto-generated method stub
String log="log4日志测试";
logger.info(log);
} }

6、运行LogTest ,在log.txt文件写入如下信息:

2015/09/04 09:37:03:650 INFO com.test.Test:11 - log4日志测试