LogCatAppender.java 2.5 KB
Newer Older
N
1.9.5  
NeroZhang 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
package com.example.log4j;

import org.apache.log4j.AppenderSkeleton;
import org.apache.log4j.Layout;
import org.apache.log4j.PatternLayout;
import org.apache.log4j.spi.LoggingEvent;

import android.util.Log;

/**
 * 源自 android-logging-log4j-1.0.3.jar
 * 
 * @author Administrator
 */
public class LogCatAppender extends AppenderSkeleton {
	protected Layout tagLayout;

	public LogCatAppender(Layout messageLayout, Layout tagLayout) {
		this.tagLayout = tagLayout;
		setLayout(messageLayout);
	}

	public LogCatAppender(Layout messageLayout) {
		//这里定义的是Tag名称
		this(messageLayout, new PatternLayout("%c"));
	}

	public LogCatAppender() {
		this(new PatternLayout("%c"));
	}

	protected void append(LoggingEvent le) {
		switch (le.getLevel().toInt()) {
		case 5000:
			if (le.getThrowableInformation() != null) {
				Log.v(getTagLayout().format(le), getLayout().format(le), le.getThrowableInformation().getThrowable());
			} else {
				Log.v(getTagLayout().format(le), getLayout().format(le));
			}
			break;
		case 10000:
			if (le.getThrowableInformation() != null) {
				Log.d(getTagLayout().format(le), getLayout().format(le), le.getThrowableInformation().getThrowable());
			} else {
				Log.d(getTagLayout().format(le), getLayout().format(le));
			}
			break;
		case 20000:
			if (le.getThrowableInformation() != null) {
				Log.i(getTagLayout().format(le), getLayout().format(le), le.getThrowableInformation().getThrowable());
			} else {
				Log.i(getTagLayout().format(le), getLayout().format(le));
			}
			break;
		case 30000:
			if (le.getThrowableInformation() != null) {
				Log.w(getTagLayout().format(le), getLayout().format(le), le.getThrowableInformation().getThrowable());
			} else {
				Log.w(getTagLayout().format(le), getLayout().format(le));
			}
			break;
		case 40000:
			if (le.getThrowableInformation() != null) {
				Log.e(getTagLayout().format(le), getLayout().format(le), le.getThrowableInformation().getThrowable());
			} else {
				Log.e(getTagLayout().format(le), getLayout().format(le));
			}
			break;
		case 50000:
			if (le.getThrowableInformation() != null) {
				Log.wtf(getTagLayout().format(le), getLayout().format(le), le.getThrowableInformation().getThrowable());
			} else
				Log.wtf(getTagLayout().format(le), getLayout().format(le));
			break;
		}
	}

	public void close() {
	}

	public boolean requiresLayout() {
		return true;
	}

	public Layout getTagLayout() {
		return this.tagLayout;
	}

	public void setTagLayout(Layout tagLayout) {
		this.tagLayout = tagLayout;
	}
}