我需要在Android studio logcat中观看socket.io-client-java日志。例如:https://github.com/socketio/socket.io-client-java/blob/master/src/main/java/io/socket/client/IO.java#L70
为什么我在logcat中看不到logger.fine(String.format("ignoring socket cache for %s", source));
输出?
以上示例中的记录器将级别Fine
设置为消息,但在Android Studio logcat中没有此日志级别(仅Verbose
,Debug
,Info
,Warn
,Error
,Assert
)。我误解了这种不匹配。请解释一下。
答案 0 :(得分:8)
好的,Logcat没有显示它,因为默认记录器级别是info。
这个解决方案非常适合我。我现在在主要活动中调试socket.io
import io.socket.client.Manager;
import io.socket.client.Socket;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AndroidLoggingHandler.reset(new AndroidLoggingHandler());
java.util.logging.Logger.getLogger(Socket.class.getName()).setLevel(Level.FINEST);
java.util.logging.Logger.getLogger(io.socket.engineio.client.Socket.class.getName()).setLevel(Level.FINEST);
java.util.logging.Logger.getLogger(Manager.class.getName()).setLevel(Level.FINEST);
}
可能的实用工具类
import android.util.Log;
import java.util.logging.*;
public class AndroidLoggingHandler extends Handler {
public static void reset(Handler rootHandler) {
Logger rootLogger = LogManager.getLogManager().getLogger("");
Handler[] handlers = rootLogger.getHandlers();
for (Handler handler : handlers) {
rootLogger.removeHandler(handler);
}
LogManager.getLogManager().getLogger("").addHandler(rootHandler);
}
@Override
public void close() {
}
@Override
public void flush() {
}
@Override
public void publish(LogRecord record) {
if (!super.isLoggable(record))
return;
String name = record.getLoggerName();
int maxLength = 30;
String tag = name.length() > maxLength ? name.substring(name.length() - maxLength) : name;
try {
int level = getAndroidLevel(record.getLevel());
Log.println(level, tag, record.getMessage());
if (record.getThrown() != null) {
Log.println(level, tag, Log.getStackTraceString(record.getThrown()));
}
} catch (RuntimeException e) {
Log.e("AndroidLoggingHandler", "Error logging message.", e);
}
}
static int getAndroidLevel(Level level) {
int value = level.intValue();
if (value >= 1000) {
return Log.ERROR;
} else if (value >= 900) {
return Log.WARN;
} else if (value >= 800) {
return Log.INFO;
} else {
return Log.DEBUG;
}
}
}