log4j使用例子

目录结构:


D:\code\kongee\log4jtest>tree
卷 软件 的文件夹 PATH 列表
卷序列号为 000D-CD8E
D:.
├─.settings
├─bin
│  └─com
│      └─laolang
│          ├─cal
│          ├─hello
│          └─say
├─lib
├─log
└─src
    └─com
        └─laolang
            ├─cal
            ├─hello
            └─say

D:\code\kongee\log4jtest>tree /f
卷 软件 的文件夹 PATH 列表
卷序列号为 000D-CD8E
D:.
│  .classpath
│  .project
│  build.properties
│  build.xml
│
├─.settings
│      org.eclipse.core.resources.prefs
│      org.eclipse.jdt.core.prefs
│
├─bin
│  │  log4j.properties
│  │
│  └─com
│      └─laolang
│          ├─cal
│          │      Cal.class
│          │
│          ├─hello
│          │      HelloWorld.class
│          │
│          └─say
│                  Hello.class
│
├─lib
│      hamcrest-core-1.3.jar
│      junit-4.11.jar
│      log4j-1.2.17.jar
│
├─log
│      say.log
│      say.log.2015-11-08
│      say.log.2015-11-09
│      say.log.2015-11-10
│
└─src
    │  log4j.properties
    │
    └─com
        └─laolang
            ├─cal
            │      Cal.java
            │
            ├─hello
            │      HelloWorld.java
            │
            └─say
                    Hello.java


D:\code\kongee\log4jtest>
代码:


com.laolang.cal.Cal


package com.laolang.cal;

import org.apache.log4j.Logger;

public class Cal {

	public int add( int a, int b ){
		logger.debug("加运算");
		logger.info("加运算");
		logger.warn("加运算");
		logger.error("加运算");
		logger.fatal("加运算");
		
		return a + b;
	}
	
	public int minus( int a, int b ){
		return a - b;
	}
	
	public int mult( int a, int b ){
		return a * b;
	}
	
	public int divide( int a , int b ){
		return a / b;
	}
	
	//创建logger
	public static final Logger logger = Logger.getLogger(Cal.class);
}
com.laolang.say.Hello



package com.laolang.say;

import org.apache.log4j.Logger;

public class Hello {

	public void syaHello() {

		System.out.println("Hello World");
		logger.debug("hello");
		logger.info("hello");
		logger.warn("hello");
		logger.error("hello");
		logger.fatal("hello");
	}

	private static final Logger logger = Logger.getLogger(Hello.class);
	// 不建议使用
	// private static final Logger logger = Logger.getLogger("hello");
}
com.laolang.hello.HelloWorld



package com.laolang.hello;

import com.laolang.cal.Cal;
import com.laolang.say.Hello;

public class HelloWorld {

	public static void main(String[] args) {
		String url = HelloWorld.class.getClassLoader().getResource("").getPath();
		System.out.println("url:" + url);

		if (-1 != url.lastIndexOf("build/classes/")) {
			url = url.replace("build/classes/", "log");
		}
		if (-1 != url.lastIndexOf("bin/")) {
			url = url.replace("bin/", "log");
		}

		System.out.println("url:" + url);
		
		

		System.setProperty("log_dir", url);
		Cal cal = new Cal();
		cal.add(1, 3);
		Hello hello = new Hello();
		hello.syaHello();
	}
}
log4j.properties



log4j.appender.stout=org.apache.log4j.ConsoleAppender
log4j.appender.stout.layout=org.apache.log4j.PatternLayout
log4j.appender.stout.layout.ConversionPattern=[%p](%l)--->%m(%d)%n
log4j.rootLogger=DEBUG, stout


#log4j.appender.fout=org.apache.log4j.FileAppender
log4j.appender.fout=org.apache.log4j.DailyRollingFileAppender
log4j.appender.fout.datePattern='.'yyyy-MM-dd

#绝对路径名,不建议使用
#log4j.appender.fout.file=d:/hello.log

log4j.appender.fout.file=${log_dir}/say.log
log4j.appender.fout.layout=org.apache.log4j.PatternLayout
log4j.appender.fout.layout.ConversionPattern=[%p](%l)---->%m(%d)%n

# 通过名称访问,不建议使用
#log4j.logger.hello=DEBUG, fout
log4j.logger.com.laolang.say=DEBUG, fout
ant


build.properties


Main-class=com.laolang.hello.HelloWorld
build.xml



<?xml version="1.0" encoding="UTF-8"?>
<project>

	<!--
        fileset可以设定一组文件集来进行操作,dir指明文件集要进行选择的路径,
        通过id可以指定这个文件的名称,在使用的时候进行直接的引入
        include和exclude可以设定包含返回和排除范围**/*.*所有目录中的所有文件
    -->
	<fileset id="src.path" dir="src">
		<include name="**/*.*" />
		<!--<exclude name="**/*.java"/>-->
	</fileset>


	<!--使用属性定义相应的路径时,一定使用location而不要使用value-->
	<property name="build.dir" location="build" />
	<property name="build.classes" location="${build.dir}/classes" />
	<property name="build.src" location="${build.dir}/src" />
	<property name="src.dir" location="src" />
	<property name="lib.dir" location="lib" />

	<!-- 
        打包、运行的相关信息
    -->
	<property file="build.properties">
	</property>

	<path id="compile-path">
		<fileset dir="${lib.dir}" includes="*.jar">
		</fileset>
	</path>


	<target name="init" description="创建必要的文件夹">
		<mkdir dir="${build.dir}" />
		<mkdir dir="${build.src}" />
		<mkdir dir="${build.classes}" />
		<echo message="初始化完成!" />
	</target>

	<target name="copySrc" depends="init" description="复制文件">
		<copy todir="build/src">
			<fileset refid="src.path">
			</fileset>
		</copy>
		<echo message="复制文件完成!" />
	</target>

	<target name="compile" depends="copySrc" description="编译">
		<javac destdir="build/classes" srcdir="src" includeantruntime="false" classpathref="compile-path" debug="true">
			<!--给编译器指定编码,防止出现:"警告: 编码 GBK 的不可映射字符"-->
			<compilerarg line="-encoding UTF-8 " />
		</javac>
		<copy todir="${build.classes}">
			<fileset dir="${src.dir}">
				<include name="**/*.properties" />
			</fileset>
		</copy>
		<echo message="编译完成!" />
	</target>



	<target name="execute" depends="compile" description="运行">
		<echo>基于类路径的classname来完成执行</echo>
		<java classname="${Main-class}" classpath="${build.classes}" fork="true" classpathref="compile-path">
		</java>

	</target>

	<target name="clean" description="清理">
		<delete dir="${build.dir}" />
	</target>
</project>
运行结果:


D:\code\kongee\log4jtest>type log\say.log
[DEBUG](com.laolang.say.Hello.syaHello(Hello.java:10))---->hello(2015-11-08 21:34:50,932)
[INFO](com.laolang.say.Hello.syaHello(Hello.java:11))---->hello(2015-11-08 21:34:50,944)
[WARN](com.laolang.say.Hello.syaHello(Hello.java:12))---->hello(2015-11-08 21:34:50,945)
[ERROR](com.laolang.say.Hello.syaHello(Hello.java:13))---->hello(2015-11-08 21:34:50,946)
[FATAL](com.laolang.say.Hello.syaHello(Hello.java:14))---->hello(2015-11-08 21:34:50,947)

D:\code\kongee\log4jtest>ant execute
Buildfile: D:\code\kongee\log4jtest\build.xml

init:
     [echo] 初始化完成!

copySrc:
     [echo] 复制文件完成!

compile:
     [echo] 编译完成!

execute:
     [echo] 基于类路径的classname来完成执行
     [java] url:/D:/code/kongee/log4jtest/build/classes/
     [java] url:/D:/code/kongee/log4jtest/log
     [java] [DEBUG](com.laolang.cal.Cal.add(Cal.java:8))--->加运算(2015-11-08 21:35:24,595)
     [java] [INFO](com.laolang.cal.Cal.add(Cal.java:9))--->加运算(2015-11-08 21:35:24,603)
     [java] [WARN](com.laolang.cal.Cal.add(Cal.java:10))--->加运算(2015-11-08 21:35:24,604)
     [java] [ERROR](com.laolang.cal.Cal.add(Cal.java:11))--->加运算(2015-11-08 21:35:24,605)
     [java] [FATAL](com.laolang.cal.Cal.add(Cal.java:12))--->加运算(2015-11-08 21:35:24,605)
     [java] Hello World
     [java] [DEBUG](com.laolang.say.Hello.syaHello(Hello.java:10))--->hello(2015-11-08 21:35:24,608)
     [java] [INFO](com.laolang.say.Hello.syaHello(Hello.java:11))--->hello(2015-11-08 21:35:24,618)
     [java] [WARN](com.laolang.say.Hello.syaHello(Hello.java:12))--->hello(2015-11-08 21:35:24,618)
     [java] [ERROR](com.laolang.say.Hello.syaHello(Hello.java:13))--->hello(2015-11-08 21:35:24,619)
     [java] [FATAL](com.laolang.say.Hello.syaHello(Hello.java:14))--->hello(2015-11-08 21:35:24,620)

BUILD SUCCESSFUL
Total time: 3 seconds

D:\code\kongee\log4jtest>type log\say.log
[DEBUG](com.laolang.say.Hello.syaHello(Hello.java:10))---->hello(2015-11-08 21:34:50,932)
[INFO](com.laolang.say.Hello.syaHello(Hello.java:11))---->hello(2015-11-08 21:34:50,944)
[WARN](com.laolang.say.Hello.syaHello(Hello.java:12))---->hello(2015-11-08 21:34:50,945)
[ERROR](com.laolang.say.Hello.syaHello(Hello.java:13))---->hello(2015-11-08 21:34:50,946)
[FATAL](com.laolang.say.Hello.syaHello(Hello.java:14))---->hello(2015-11-08 21:34:50,947)
[DEBUG](com.laolang.say.Hello.syaHello(Hello.java:10))---->hello(2015-11-08 21:35:24,608)
[INFO](com.laolang.say.Hello.syaHello(Hello.java:11))---->hello(2015-11-08 21:35:24,618)
[WARN](com.laolang.say.Hello.syaHello(Hello.java:12))---->hello(2015-11-08 21:35:24,618)
[ERROR](com.laolang.say.Hello.syaHello(Hello.java:13))---->hello(2015-11-08 21:35:24,619)
[FATAL](com.laolang.say.Hello.syaHello(Hello.java:14))---->hello(2015-11-08 21:35:24,620)

D:\code\kongee\log4jtest>



如果修改系统时间的话,会在log目录下有一个相对应的log文件,这里不再演示


记录:

使用log4j的步骤:

1、创建logger


public static final Logger logger = Logger.getLogger(ClassName.class);
2、编写日志



logger.debug("hello");
logger.info("hello");
logger.warn("hello");
logger.error("hello");
logger.fatal("hello");
3、编写配置文件


    3.1创建apender  


log4j.appender.fout=org.apache.log4j.DailyRollingFileAppender
log4j.appender.fout.datePattern='.'yyyy-MM-dd
    3.2设置layout



log4j.appender.fout.file=${log_dir}/say.log
log4j.appender.fout.layout=org.apache.log4j.PatternLayout
    3.3设置输出格式



log4j.appender.fout.layout.ConversionPattern=[%p](%l)---->%m(%d)%n
4、设置日志输出级别



log4j.logger.com.laolang.say=DEBUG, fout






你可能感兴趣的:(log4j使用例子)