概述
贴代码吧,记录下,后面独立项目中使用.
Logger类:
import android.util.Log;
import java.util.logging.Level;
/**
* describe
* date 2018/8/26
*/
public interface Logger {
//正常打印
void log(Level level, String msg);
//异常打印
void log(Level level, String msg, Throwable th);
class AndroidLogger implements Logger {
static final boolean ANDROID_LOG_AVAILABLE;
private String tag;
static {
boolean android = false;
try {
android = Class.forName("android.util.Log") != null;
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
ANDROID_LOG_AVAILABLE = android;
}
public AndroidLogger(String tag) {
this.tag = tag;
}
public static boolean isAndroidLogAvailable() {
return ANDROID_LOG_AVAILABLE;
}
@Override
public void log(Level level, String msg) {
if (level != Level.OFF) {
Log.println(mapLevel(level), tag, msg);
}
}
@Override
public void log(Level level, String msg, Throwable th) {
if (level != Level.OFF) {
// That's how Log does it internally
Log.println(mapLevel(level), tag, msg + "n" + Log.getStackTraceString(th));
}
}
/**
* 降级策略
*
* @param level
* @return
*/
protected int mapLevel(Level level) {
int value = level.intValue();
if (value < 800) { // below INFO
if (value < 500) { // below FINE
return Log.VERBOSE;
} else {
return Log.DEBUG;
}
} else if (value < 900) { // below WARNING
return Log.INFO;
} else if (value < 1000) { // below ERROR
return Log.WARN;
} else {
return Log.ERROR;
}
}
}
class JavaLogger implements Logger {
protected final java.util.logging.Logger logger;
public JavaLogger(String tag) {
logger = java.util.logging.Logger.getLogger(tag);
}
@Override
public void log(Level level, String msg) {
logger.log(level, msg);
}
@Override
public void log(Level level, String msg, Throwable th) {
logger.log(level, msg, th);
}
}
class SystemLogger implements Logger {
@Override
public void log(Level level, String msg) {
System.out.println("[" + level + "] " + msg);
}
@Override
public void log(Level level, String msg, Throwable th) {
System.out.println("[" + level + "] " + msg);
th.printStackTrace(System.out);
}
}
}
打印类
import android.os.Looper;
import java.util.logging.Level;
/**
* describe
* date 2018/8/26
*/
public class XLog {
static Logger logger;
static Level level = Level.INFO;
static Logger getLogger() {
if (logger != null) {
return logger;
} else {
return Logger.AndroidLogger.isAndroidLogAvailable() && getMainLooper() != null
? new Logger.AndroidLogger("XP-LOG") : new Logger.SystemLogger();
}
}
/**
* 主线程打印日志
*
* @return
*/
static Object getMainLooper() {
return Looper.getMainLooper();
}
public static void log(String msg) {
getLogger().log(level, msg);
}
}
最后
以上就是彪壮季节为你收集整理的android日志打印的全部内容,希望文章能够帮你解决android日志打印所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复