Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android上定義一個懶人專用的log

Android上定義一個懶人專用的log

編輯:關於Android編程

在Android上打印log時,我習慣已類名為tag,這樣在每一個類都得定義一個tag變量,然後又填入第一個參數,後來覺得很麻煩,在網上找到了一篇有用的博客,這個log類通過獲取調用所在的類名為tag進行打印,這樣就省了每次填第一個參數的煩惱了,方便了許多.原出處不知道在哪裡,這個我是轉載過來稍微修改的,下面貼上我修改過的源碼.修改AppConfig.DEBUG_MODEL的值就可以控制打印或者不打印了.


import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Formatter;
import java.util.Locale;



import android.os.Environment;
import android.text.TextUtils;

/**
 * Log工具,類似android.util.Log。 tag自動產生,格式:
 * customTagPrefix:className.methodName(Line:lineNumber),
 * customTagPrefix為空時只輸出:className.methodName(Line:lineNumber)。
 * http://blog.csdn.net/finddreams
 * 復制的博客地址:http://blog.csdn.net/iplayvs2008/article/details/40422999
 * 我調用另一個類轉換了,所以此類的類名可以為Log
 */
public class LogLazy {

	public static String customTagPrefix = "junjing"; // 自定義Tag的前綴,可以是作者名
	private static final boolean isSaveLog = false; // 是否把保存日志到SD卡中
	public static final String ROOT = Environment.getExternalStorageDirectory().getPath() + "/finddreams/"; // SD卡中的根目錄
	private static final String PATH_LOG_INFO = ROOT + "info/";

	private LogLazy() {
	}

	// 容許打印日志的類型,默認是true,設置為false則不打印
	public static boolean allowD = true;
	public static boolean allowE = true;
	public static boolean allowI = true;
	public static boolean allowV = true;
	public static boolean allowW = true;
	public static boolean allowWtf = true;
	public static final boolean DEBUG = AppConfig.DEBUG_MODEL;

	private static String generateTag(StackTraceElement caller) {
		String tag = "%s.%s(Line:%d)"; // 占位符
		String callerClazzName = caller.getClassName(); // 獲取到類名
		callerClazzName = callerClazzName.substring(callerClazzName.lastIndexOf(".") + 1);
		callerClazzName = callerClazzName.substring(callerClazzName.lastIndexOf(".") + 1);// 我的修改,獲取倒數第二個類名,原因是我用另一個log輸出的.
		tag = String.format(tag, callerClazzName, caller.getMethodName(), caller.getLineNumber()); // 替換
		tag = TextUtils.isEmpty(customTagPrefix) ? tag : customTagPrefix + ":" + tag;
		return tag;
	}

	/**
	 * 自定義的logger
	 */
	public static CustomLogger customLogger;

	public interface CustomLogger {
		void d(String tag, String content);

		void d(String tag, String content, Throwable tr);

		void e(String tag, String content);

		void e(String tag, String content, Throwable tr);

		void i(String tag, String content);

		void i(String tag, String content, Throwable tr);

		void v(String tag, String content);

		void v(String tag, String content, Throwable tr);

		void w(String tag, String content);

		void w(String tag, String content, Throwable tr);

		void w(String tag, Throwable tr);

		void wtf(String tag, String content);

		void wtf(String tag, String content, Throwable tr);

		void wtf(String tag, Throwable tr);
	}

	public static void d(String content) {
		if (!DEBUG)
			return;
		if (!allowD)
			return;
		StackTraceElement caller = getCallerStackTraceElement();
		String tag = generateTag(caller);

		if (customLogger != null) {
			customLogger.d(tag, content);
		} else {
			MyLog.d(tag, content);
		}
	}

	public static void d(String content, Throwable tr) {
		if (!DEBUG)
			return;
		if (!allowD)
			return;
		StackTraceElement caller = getCallerStackTraceElement();
		String tag = generateTag(caller);

		if (customLogger != null) {
			customLogger.d(tag, content, tr);
		} else {
			MyLog.d(tag, content, tr);
		}
	}

	public static void e(String content) {
		if (!DEBUG)
			return;
		if (!allowE)
			return;
		StackTraceElement caller = getCallerStackTraceElement();
		String tag = generateTag(caller);

		if (customLogger != null) {
			customLogger.e(tag, content);
		} else {
			MyLog.e(tag, content);
		}
		if (isSaveLog) {
			point(PATH_LOG_INFO, tag, content);
		}
	}

	public static void e(String content, Throwable tr) {
		if (!DEBUG)
			return;
		if (!allowE)
			return;
		StackTraceElement caller = getCallerStackTraceElement();
		String tag = generateTag(caller);

		if (customLogger != null) {
			customLogger.e(tag, content, tr);
		} else {
			MyLog.e(tag, content, tr);
		}
		if (isSaveLog) {
			point(PATH_LOG_INFO, tag, tr.getMessage());
		}
	}

	public static void i(String content) {
		if (!DEBUG)
			return;
		if (!allowI)
			return;
		StackTraceElement caller = getCallerStackTraceElement();
		String tag = generateTag(caller);

		if (customLogger != null) {
			customLogger.i(tag, content);
		} else {
			MyLog.i(tag, content);
		}

	}

	public static void i(String content, Throwable tr) {
		if (!DEBUG)
			return;
		if (!allowI)
			return;
		StackTraceElement caller = getCallerStackTraceElement();
		String tag = generateTag(caller);

		if (customLogger != null) {
			customLogger.i(tag, content, tr);
		} else {
			MyLog.i(tag, content, tr);
		}

	}

	public static void v(String content) {
		if (!DEBUG)
			return;
		if (!allowV)
			return;
		StackTraceElement caller = getCallerStackTraceElement();
		String tag = generateTag(caller);

		if (customLogger != null) {
			customLogger.v(tag, content);
		} else {
			MyLog.v(tag, content);
		}
	}

	public static void v(String content, Throwable tr) {
		if (!DEBUG)
			return;
		if (!allowV)
			return;
		StackTraceElement caller = getCallerStackTraceElement();
		String tag = generateTag(caller);

		if (customLogger != null) {
			customLogger.v(tag, content, tr);
		} else {
			MyLog.v(tag, content, tr);
		}
	}

	public static void w(String content) {
		if (!DEBUG)
			return;
		if (!allowW)
			return;
		StackTraceElement caller = getCallerStackTraceElement();
		String tag = generateTag(caller);

		if (customLogger != null) {
			customLogger.w(tag, content);
		} else {
			MyLog.w(tag, content);
		}
	}

	public static void w(String content, Throwable tr) {
		if (!DEBUG)
			return;
		if (!allowW)
			return;
		StackTraceElement caller = getCallerStackTraceElement();
		String tag = generateTag(caller);

		if (customLogger != null) {
			customLogger.w(tag, content, tr);
		} else {
			MyLog.w(tag, content, tr);
		}
	}

	public static void w(Throwable tr) {
		if (!DEBUG)
			return;
		if (!allowW)
			return;
		StackTraceElement caller = getCallerStackTraceElement();
		String tag = generateTag(caller);

		if (customLogger != null) {
			customLogger.w(tag, tr);
		} else {
			MyLog.w(tag, tr);
		}
	}

	public static void wtf(String content) {
		if (!DEBUG)
			return;
		if (!allowWtf)
			return;
		StackTraceElement caller = getCallerStackTraceElement();
		String tag = generateTag(caller);

		if (customLogger != null) {
			customLogger.wtf(tag, content);
		} else {
			MyLog.wtf(tag, content);
		}
	}

	public static void wtf(String content, Throwable tr) {
		if (!DEBUG)
			return;
		if (!allowWtf)
			return;
		StackTraceElement caller = getCallerStackTraceElement();
		String tag = generateTag(caller);

		if (customLogger != null) {
			customLogger.wtf(tag, content, tr);
		} else {
			MyLog.wtf(tag, content, tr);
		}
	}

	public static void wtf(Throwable tr) {
		if (!DEBUG)
			return;
		if (!allowWtf)
			return;
		StackTraceElement caller = getCallerStackTraceElement();
		String tag = generateTag(caller);

		if (customLogger != null) {
			customLogger.wtf(tag, tr);
		} else {
			MyLog.wtf(tag, tr);
		}
	}

	private static StackTraceElement getCallerStackTraceElement() {
		return Thread.currentThread().getStackTrace()[4];
	}

	public static void point(String path, String tag, String msg) {
		if (isSDAva()) {
			Date date = new Date();
			SimpleDateFormat dateFormat = new SimpleDateFormat("", Locale.SIMPLIFIED_CHINESE);
			dateFormat.applyPattern("yyyy");
			path = path + dateFormat.format(date) + "/";
			dateFormat.applyPattern("MM");
			path += dateFormat.format(date) + "/";
			dateFormat.applyPattern("dd");
			path += dateFormat.format(date) + ".log";
			dateFormat.applyPattern("[yyyy-MM-dd HH:mm:ss]");
			String time = dateFormat.format(date);
			File file = new File(path);
			if (!file.exists())
				createDipPath(path);
			BufferedWriter out = null;
			try {
				out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true)));
				out.write(time + " " + tag + " " + msg + "\r\n");
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				try {
					if (out != null) {
						out.close();
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 根據文件路徑 遞歸創建文件
	 * 
	 * @param file
	 */
	public static void createDipPath(String file) {
		String parentFile = file.substring(0, file.lastIndexOf("/"));
		File file1 = new File(file);
		File parent = new File(parentFile);
		if (!file1.exists()) {
			parent.mkdirs();
			try {
				file1.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * A little trick to reuse a formatter in the same thread
	 */
	private static class ReusableFormatter {

		private Formatter formatter;
		private StringBuilder builder;

		public ReusableFormatter() {
			builder = new StringBuilder();
			formatter = new Formatter(builder);
		}

		public String format(String msg, Object... args) {
			formatter.format(msg, args);
			String s = builder.toString();
			builder.setLength(0);
			return s;
		}
	}

	private static final ThreadLocal thread_local_formatter = new ThreadLocal() {
		protected ReusableFormatter initialValue() {
			return new ReusableFormatter();
		}
	};

	public static String format(String msg, Object... args) {
		ReusableFormatter formatter = thread_local_formatter.get();
		return formatter.format(msg, args);
	}

	public static boolean isSDAva() {
		if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)
				|| Environment.getExternalStorageDirectory().exists()) {
			return true;
		} else {
			return false;
		}
	}

}


 

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved