Android - Set max length of logcat messages - android

By default, it seems that logcat will truncate any log message that it considers to be "too long". This happens both inside of Eclipse and when running logcat on the command line using adb -d logcat, and is truncating some important debugging messages.
Is there any way to increase the maximum string length supported by logcat to get it to stop truncating the debug information? The official documentation implies that there may not be, but maybe logcat supports some additional options not mentioned there?

Ok, interesting. I was disappointed to see that the answer was "you can't really expand it". My initial thought was to break it up so I could view the whole thing, so here I share with you how I do just that (not that it's anything fancy nor is it near efficient, but it gets the job done in a pinch):
if (sb.length() > 4000) {
Log.v(TAG, "sb.length = " + sb.length());
int chunkCount = sb.length() / 4000; // integer division
for (int i = 0; i <= chunkCount; i++) {
int max = 4000 * (i + 1);
if (max >= sb.length()) {
Log.v(TAG, "chunk " + i + " of " + chunkCount + ":" + sb.substring(4000 * i));
} else {
Log.v(TAG, "chunk " + i + " of " + chunkCount + ":" + sb.substring(4000 * i, max));
}
}
} else {
Log.v(TAG, sb.toString());
}
Edited to show the last string!

Break it up in several pieces recursively.
public static void largeLog(String tag, String content) {
if (content.length() > 4000) {
Log.d(tag, content.substring(0, 4000));
largeLog(tag, content.substring(4000));
} else {
Log.d(tag, content);
}
}

There is a fixed size buffer in logcat for binary logs (/dev/log/events) and this limit is 1024 bytes.
For the non-binary logs there is also a limit:
#define LOGGER_ENTRY_MAX_LEN (4*1024)
#define LOGGER_ENTRY_MAX_PAYLOAD (LOGGER_ENTRY_MAX_LEN - sizeof(struct logger_entry))
So the real message size for both binary and non-binary logs is ~4076 bytes.
The kernel logger interface imposes this LOGGER_ENTRY_MAX_PAYLOAD limit.
The liblog sources (used by logcat) also say:
The message may have been truncated by the kernel log driver.
I would recommend you the nxlog tool which does not use the logcat binary, but due to the limitations in the kernel I doubt that it will solve your problem. Nevertheless, it might be worth a try. (disclaimer: I'm the author.)

for( String line : logMesg.split("\n") ) {
Log.d( TAG, line );
}

Here is the code I use--it truncates the lines at the 4000 limit while also breaking the line at new lines rather than in the middles of the line. Makes for an easier to read log file.
Usage:
Logger.debugEntire("....");
Implementation:
package ...;
import android.util.Log;
import java.util.Arrays;
public class Logger {
private static final String LOG_TAG = "MyRockingApp";
/** #see <a href="http://stackoverflow.com/a/8899735" /> */
private static final int ENTRY_MAX_LEN = 4000;
/**
* #param args If the last argument is an exception than it prints out the stack trace, and there should be no {}
* or %s placeholder for it.
*/
public static void d(String message, Object... args) {
log(Log.DEBUG, false, message, args);
}
/**
* Display the entire message, showing multiple lines if there are over 4000 characters rather than truncating it.
*/
public static void debugEntire(String message, Object... args) {
log(Log.DEBUG, true, message, args);
}
public static void i(String message, Object... args) {
log(Log.INFO, false, message, args);
}
public static void w(String message, Object... args) {
log(Log.WARN, false, message, args);
}
public static void e(String message, Object... args) {
log(Log.ERROR, false, message, args);
}
private static void log(int priority, boolean ignoreLimit, String message, Object... args) {
String print;
if (args != null && args.length > 0 && args[args.length-1] instanceof Throwable) {
Object[] truncated = Arrays.copyOf(args, args.length -1);
Throwable ex = (Throwable) args[args.length-1];
print = formatMessage(message, truncated) + '\n' + android.util.Log.getStackTraceString(ex);
} else {
print = formatMessage(message, args);
}
if (ignoreLimit) {
while (!print.isEmpty()) {
int lastNewLine = print.lastIndexOf('\n', ENTRY_MAX_LEN);
int nextEnd = lastNewLine != -1 ? lastNewLine : Math.min(ENTRY_MAX_LEN, print.length());
String next = print.substring(0, nextEnd /*exclusive*/);
android.util.Log.println(priority, LOG_TAG, next);
if (lastNewLine != -1) {
// Don't print out the \n twice.
print = print.substring(nextEnd+1);
} else {
print = print.substring(nextEnd);
}
}
} else {
android.util.Log.println(priority, LOG_TAG, print);
}
}
private static String formatMessage(String message, Object... args) {
String formatted;
try {
/*
* {} is used by SLF4J so keep it compatible with that as it's easy to forget to use %s when you are
* switching back and forth between server and client code.
*/
formatted = String.format(message.replaceAll("\\{\\}", "%s"), args);
} catch (Exception ex) {
formatted = message + Arrays.toString(args);
}
return formatted;
}
}

int i = 3000;
while (sb.length() > i) {
Log.e(TAG, "Substring: "+ sb.substring(0, i));
sb = sb.substring(i);
}
Log.e(TAG, "Substring: "+ sb);

The code below is a refinement of what was posted by Mark Buikema. It breaks the string at new lines. Useful for logging long JSON strings.
public static void dLong(String theMsg)
{
final int MAX_INDEX = 4000;
final int MIN_INDEX = 3000;
// String to be logged is longer than the max...
if (theMsg.length() > MAX_INDEX)
{
String theSubstring = theMsg.substring(0, MAX_INDEX);
int theIndex = MAX_INDEX;
// Try to find a substring break at a line end.
theIndex = theSubstring.lastIndexOf('\n');
if (theIndex >= MIN_INDEX)
{
theSubstring = theSubstring.substring(0, theIndex);
}
else
{
theIndex = MAX_INDEX;
}
// Log the substring.
Log.d(APP_LOG_TAG, theSubstring);
// Recursively log the remainder.
dLong(theMsg.substring(theIndex));
}
// String to be logged is shorter than the max...
else
{
Log.d(APP_LOG_TAG, theMsg);
}
}

us this paging logic
/*
* StringBuffer sb - long text which want to show in multiple lines
* int lenth - lenth of line need
*/
public static void showInPage(StringBuffer sb, int lenth) {
System.out.println("sb.length = " + sb.length());
if (sb.length() > lenth) {
int chunkCount = sb.length() / lenth; // integer division
if ((chunkCount % lenth) > 1)
chunkCount++;
for (int i = 0; i < chunkCount; i++) {
int max = lenth * (i + 1);
if (max >= sb.length()) {
System.out.println("");
System.out.println("chunk " + i + " of " + chunkCount + ":"
+ sb.substring(lenth * i));
} else {
System.out.println("");
System.out.println("chunk " + i + " of " + chunkCount + ":"
+ sb.substring(lenth * i, max));
}
}
}
}

providing my own take on Travis's solution,
void d(String msg) {
println(Log.DEBUG, msg);
}
private void println(int priority, String msg) {
int l = msg.length();
int c = Log.println(priority, TAG, msg);
if (c < l) {
return c + println(priority, TAG, msg.substring(c+1));
} else {
return c;
}
}
take advantage of the fact that Log.println() returns the number of bytes written to avoid hardcoding "4000". then, recursively call yourself on the part of the message that couldn't be logged until there's nothing left.

If your log is very long (eg. logging entire dump of your database for debugging reasons etc.) it may happen that logcat prevents excessive logging. To work around this you can add a timeout evry x milliseconds.
/**
* Used for very long messages, splits it into equal chunks and logs each individual to
* work around the logcat max message length. Will log with {#link Log#d(String, String)}.
*
* #param tag used in for logcat
* #param message long message to log
*/
public static void longLogDebug(final String tag, #NonNull String message) {
int i = 0;
final int maxLogLength = 1000;
while (message.length() > maxLogLength) {
Log.d(tag, message.substring(0, maxLogLength));
message = message.substring(maxLogLength);
i++;
if (i % 100 == 0) {
StrictMode.noteSlowCall("wait to flush logcat");
SystemClock.sleep(32);
}
}
Log.d(tag, message);
}
Beware, only use this for debugging purpose as it may halts blocks main thread.

As #mhsmith mentioned, the LOGGER_ENTRY_MAX_PAYLOAD is 4068 in the recent Android versions. However, if you use 4068 as the max message length in the code snippets offered in other answers, the messages will be truncated. This is because Android adds more characters to the beginning and end of your message, which also count. Other answers use the 4000 limit as a workaround. However, it is possible to really use the whole limit with this code (the code generates a tag from the stack trace to show the class name and line number which called the log, feel free to modify that):
private static final int MAX_MESSAGE_LENGTH = 4068;
private enum LogType {
debug,
info,
warning,
error
}
private static void logMessage(LogType logType, #Nullable String message, #Nullable String tag) {
logMessage(logType, message, tag, Thread.currentThread().getStackTrace()[4]);
}
private static void logMessage(LogType logType, #Nullable String message, #Nullable String customTag, StackTraceElement stackTraceElement) {
// don't use expensive String.format
String tag = "DASHBOARDS(" + stackTraceElement.getFileName() + "." + (!TextUtils.isEmpty(customTag) ? customTag : stackTraceElement.getMethodName()) + ":" + stackTraceElement.getLineNumber() + ")";
int maxMessageLength = MAX_MESSAGE_LENGTH - (tag.length()) - 4; // minus four because android adds a letter showing the log type before the tag, e. g. "D/" for debug, and a colon and space are added behind it, i. e. ": "
if (message == null || message.length() <= maxMessageLength) {
logMessageInternal(logType, message, tag);
} else {
maxMessageLength -= 8; // we will add counter to the beginning of the message, e. g. "(12/15) "
int totalChunks = (int) Math.ceil((float) message.length() / maxMessageLength);
for (int i = 1; i <= totalChunks; i++) {
int start = (i - 1) * maxMessageLength;
logMessageInternal(logType, "(" + i + "/" + totalChunks + ") " + message.substring(start, Math.min(start + maxMessageLength, message.length())), tag);
}
}
}
private static void logMessageInternal(LogType logType, String message, String tag) {
if (message == null) {
message = "message is null";
}
switch (logType) {
case debug:
Log.d(tag, message);
break;
case info:
Log.i(tag, message);
break;
case warning:
Log.w(tag, message);
break;
case error:
Log.e(tag, message);
}
}
public static void d(String debug, String tag) {
logMessage(LogType.debug, debug, tag);
}

Though the other provided solutions were helpful, I wasn't satisfied by them cause they did not cover cases when the log is longer than twice as long as the LOGGER_ENTRY_MAX_LEN mentioned by #b0ti. Furthermore even my following solution is not perfect as the LOGGER_ENTRY_MAX_LEN is not fetched dynamically. If someone knows a way to do this, I would love to hear about it in the comments! Anyway, this is the solution I use in my code right now:
final int loggerEntryMaxLength = 4000;
int logLength = loggerEntryMaxLength - 2 - TAG.length();
int i = 0;
while (output.length() / logLength > i) {
int startIndex = i++ * logLength;
int endIndex = i * logLength;
Log.d(TAG, output.substring(startIndex, endIndex));
}
int startIndex = i * logLength;
Log.d(
TAG,
output.substring(
startIndex,
startIndex + (output.length() % logLength)
)
);

I dont know any option to increase the length of logcat , but we can find the different logs like main log , event log etc..The main log usually contains everything its length goes upto 4Mb.. So you may able to get what you lost in log terminal. Path is: \data\logger.

Each log has a limit of maximum 4096 bytes (4KB), and some bytes (about 40 bytes) are used for general information of each log like tag, priority(assert, debug, ...) and etc.
So I tried to trim 4056 bytes of the string to be logged.
Advantages:
The trim function executes very fast because it doesn't have any loops (executes in 1 ms)
It doesn't truncate any characters of the log message
It logs entire message using a recursive function into multiple log entries.
Here is the solution:
private static final int MAX_LOG_BYTES = 4056;
public static void log(int priority, String tag, #NonNull String content) {
int size = content.getBytes(StandardCharsets.UTF_8).length;
if (size > MAX_LOG_BYTES) {
String text = trim(content, MAX_LOG_BYTES);
Log.println(priority, tag, text);
log(priority, tag, content.substring(text.length()));
} else {
Log.println(priority, tag, content);
}
}
public static String trim(String text, int length) {
byte[] inputBytes = text.getBytes(StandardCharsets.UTF_8);
byte[] outputBytes = new byte[length];
System.arraycopy(inputBytes, 0, outputBytes, 0, length);
String result = new String(outputBytes, StandardCharsets.UTF_8);
// check if last character is truncated
int lastIndex = result.length() - 1;
if (lastIndex > 0 && result.charAt(lastIndex) != text.charAt(lastIndex)) {
// last character is truncated so remove the last character
return result.substring(0, lastIndex);
}
return result;
}

Related

Comparison method violates its general contract! while sorting [duplicate]

I saw many questions about this, and tried to solve the problem, but after one hour of googling and a lots of trial & error, I still can't fix it. I hope some of you catch the problem.
This is what I get:
java.lang.IllegalArgumentException: Comparison method violates its general contract!
at java.util.ComparableTimSort.mergeHi(ComparableTimSort.java:835)
at java.util.ComparableTimSort.mergeAt(ComparableTimSort.java:453)
at java.util.ComparableTimSort.mergeForceCollapse(ComparableTimSort.java:392)
at java.util.ComparableTimSort.sort(ComparableTimSort.java:191)
at java.util.ComparableTimSort.sort(ComparableTimSort.java:146)
at java.util.Arrays.sort(Arrays.java:472)
at java.util.Collections.sort(Collections.java:155)
...
And this is my comparator:
#Override
public int compareTo(Object o) {
if(this == o){
return 0;
}
CollectionItem item = (CollectionItem) o;
Card card1 = CardCache.getInstance().getCard(cardId);
Card card2 = CardCache.getInstance().getCard(item.getCardId());
if (card1.getSet() < card2.getSet()) {
return -1;
} else {
if (card1.getSet() == card2.getSet()) {
if (card1.getRarity() < card2.getRarity()) {
return 1;
} else {
if (card1.getId() == card2.getId()) {
if (cardType > item.getCardType()) {
return 1;
} else {
if (cardType == item.getCardType()) {
return 0;
}
return -1;
}
}
return -1;
}
}
return 1;
}
}
Any idea?
The exception message is actually pretty descriptive. The contract it mentions is transitivity: if A > B and B > C then for any A, B and C: A > C. I checked it with paper and pencil and your code seems to have few holes:
if (card1.getRarity() < card2.getRarity()) {
return 1;
you do not return -1 if card1.getRarity() > card2.getRarity().
if (card1.getId() == card2.getId()) {
//...
}
return -1;
You return -1 if ids aren't equal. You should return -1 or 1 depending on which id was bigger.
Take a look at this. Apart from being much more readable, I think it should actually work:
if (card1.getSet() > card2.getSet()) {
return 1;
}
if (card1.getSet() < card2.getSet()) {
return -1;
};
if (card1.getRarity() < card2.getRarity()) {
return 1;
}
if (card1.getRarity() > card2.getRarity()) {
return -1;
}
if (card1.getId() > card2.getId()) {
return 1;
}
if (card1.getId() < card2.getId()) {
return -1;
}
return cardType - item.getCardType(); //watch out for overflow!
You can use the following class to pinpoint transitivity bugs in your Comparators:
/**
* #author Gili Tzabari
*/
public final class Comparators
{
/**
* Verify that a comparator is transitive.
*
* #param <T> the type being compared
* #param comparator the comparator to test
* #param elements the elements to test against
* #throws AssertionError if the comparator is not transitive
*/
public static <T> void verifyTransitivity(Comparator<T> comparator, Collection<T> elements)
{
for (T first: elements)
{
for (T second: elements)
{
int result1 = comparator.compare(first, second);
int result2 = comparator.compare(second, first);
if (result1 != -result2)
{
// Uncomment the following line to step through the failed case
//comparator.compare(first, second);
throw new AssertionError("compare(" + first + ", " + second + ") == " + result1 +
" but swapping the parameters returns " + result2);
}
}
}
for (T first: elements)
{
for (T second: elements)
{
int firstGreaterThanSecond = comparator.compare(first, second);
if (firstGreaterThanSecond <= 0)
continue;
for (T third: elements)
{
int secondGreaterThanThird = comparator.compare(second, third);
if (secondGreaterThanThird <= 0)
continue;
int firstGreaterThanThird = comparator.compare(first, third);
if (firstGreaterThanThird <= 0)
{
// Uncomment the following line to step through the failed case
//comparator.compare(first, third);
throw new AssertionError("compare(" + first + ", " + second + ") > 0, " +
"compare(" + second + ", " + third + ") > 0, but compare(" + first + ", " + third + ") == " +
firstGreaterThanThird);
}
}
}
}
}
/**
* Prevent construction.
*/
private Comparators()
{
}
}
Simply invoke Comparators.verifyTransitivity(myComparator, myCollection) in front of the code that fails.
It also has something to do with the version of JDK.
If it does well in JDK6, maybe it will have the problem in JDK 7 described by you, because the implementation method in jdk 7 has been changed.
Look at this:
Description: The sorting algorithm used by java.util.Arrays.sort and (indirectly) by java.util.Collections.sort has been replaced. The new sort implementation may throw an IllegalArgumentException if it detects a Comparable that violates the Comparable contract. The previous implementation silently ignored such a situation. If the previous behavior is desired, you can use the new system property, java.util.Arrays.useLegacyMergeSort, to restore previous mergesort behaviour.
I don't know the exact reason. However, if you add the code before you use sort. It will be OK.
System.setProperty("java.util.Arrays.useLegacyMergeSort", "true");
Consider the following case:
First, o1.compareTo(o2) is called. card1.getSet() == card2.getSet() happens to be true and so is card1.getRarity() < card2.getRarity(), so you return 1.
Then, o2.compareTo(o1) is called. Again, card1.getSet() == card2.getSet() is true. Then, you skip to the following else, then card1.getId() == card2.getId() happens to be true, and so is cardType > item.getCardType(). You return 1 again.
From that, o1 > o2, and o2 > o1. You broke the contract.
if (card1.getRarity() < card2.getRarity()) {
return 1;
However, if card2.getRarity() is less than card1.getRarity() you might not return -1.
You similarly miss other cases. I would do this, you can change around depending on your intent:
public int compareTo(Object o) {
if(this == o){
return 0;
}
CollectionItem item = (CollectionItem) o;
Card card1 = CardCache.getInstance().getCard(cardId);
Card card2 = CardCache.getInstance().getCard(item.getCardId());
int comp=card1.getSet() - card2.getSet();
if (comp!=0){
return comp;
}
comp=card1.getRarity() - card2.getRarity();
if (comp!=0){
return comp;
}
comp=card1.getSet() - card2.getSet();
if (comp!=0){
return comp;
}
comp=card1.getId() - card2.getId();
if (comp!=0){
return comp;
}
comp=card1.getCardType() - card2.getCardType();
return comp;
}
}
I had the same symptom. For me it turned out that another thread was modifying the compared objects while the sorting was happening in a Stream. To resolve the issue, I mapped the objects to immutable temporary objects, collected the Stream to a temporary Collection and did the sorting on that.
The origin of this exception is a wrong Comparator implementation. By checking the docs, we must implement the compare(o1, o2) method as an equivalence relation by following the rules:
if a.equals(b) is true then compare(a, b) is 0
if a.compare(b) > 0 then b.compare(a) < 0 is true
if a.compare(b) > 0 and b.compare(c) > 0 then a.compare(c) > 0 is true
You may check your code to realize where your implementation is offending one or more of Comparator contract rules. If it is hard to find it by a static analysis, you can use the data which cast the exception to check the rules.
If you try to run this code you will meet the kind this exception:
public static void main(String[] args) {
Random random = new Random();
List<Integer> list = new ArrayList<>();
for (int i = 0; i < 50000; i++) {
list.add(random.nextInt());
}
list.sort((x, y) -> {
int c = random.nextInt(3);
if (c == 0) {
return 0;
}
if (c == 1) {
return 1;
}
return -1;
});
}
Exception in thread "main" java.lang.IllegalArgumentException: Comparison method violates its general contract!
at java.util.TimSort.mergeLo(TimSort.java:777)
at java.util.TimSort.mergeAt(TimSort.java:514)
at java.util.TimSort.mergeCollapse(TimSort.java:441)
at java.util.TimSort.sort(TimSort.java:245)
at java.util.Arrays.sort(Arrays.java:1512)
at java.util.ArrayList.sort(ArrayList.java:1462)
at Test.main(Test.java:14)
The reason is when implementing the Comparator, it may meet the case of A > B and B > C and C > A and the sort method will be run around to be broken. Java prevent this case by throw exception this case:
class TimSort<T> {
.
.
.
else if (len1 == 0) {
throw new IllegalArgumentException(
"Comparison method violates its general contract!");
.
.
.
In conclusion, to handle this issue. You have to make sure the comparator will not meet the case of A > B and B > C and C > A.
I got the same error with a class like the following StockPickBean. Called from this code:
List<StockPickBean> beansListcatMap.getValue();
beansList.sort(StockPickBean.Comparators.VALUE);
public class StockPickBean implements Comparable<StockPickBean> {
private double value;
public double getValue() { return value; }
public void setValue(double value) { this.value = value; }
#Override
public int compareTo(StockPickBean view) {
return Comparators.VALUE.compare(this,view); //return
Comparators.SYMBOL.compare(this,view);
}
public static class Comparators {
public static Comparator<StockPickBean> VALUE = (val1, val2) ->
(int)
(val1.value - val2.value);
}
}
After getting the same error:
java.lang.IllegalArgumentException: Comparison method violates its general contract!
I changed this line:
public static Comparator<StockPickBean> VALUE = (val1, val2) -> (int)
(val1.value - val2.value);
to:
public static Comparator<StockPickBean> VALUE = (StockPickBean spb1,
StockPickBean spb2) -> Double.compare(spb2.value,spb1.value);
That fixes the error.
I ran into a similar problem where I was trying to sort a n x 2 2D array named contests which is a 2D array of simple integers. This was working for most of the times but threw a runtime error for one input:-
Arrays.sort(contests, (row1, row2) -> {
if (row1[0] < row2[0]) {
return 1;
} else return -1;
});
Error:-
Exception in thread "main" java.lang.IllegalArgumentException: Comparison method violates its general contract!
at java.base/java.util.TimSort.mergeHi(TimSort.java:903)
at java.base/java.util.TimSort.mergeAt(TimSort.java:520)
at java.base/java.util.TimSort.mergeForceCollapse(TimSort.java:461)
at java.base/java.util.TimSort.sort(TimSort.java:254)
at java.base/java.util.Arrays.sort(Arrays.java:1441)
at com.hackerrank.Solution.luckBalance(Solution.java:15)
at com.hackerrank.Solution.main(Solution.java:49)
Looking at the answers above I tried adding a condition for equals and I don't know why but it worked. Hopefully we must explicitly specify what should be returned for all cases (greater than, equals and less than):
Arrays.sort(contests, (row1, row2) -> {
if (row1[0] < row2[0]) {
return 1;
}
if(row1[0] == row2[0]) return 0;
return -1;
});
A variation of Gili's answer to check if the comparator satisfies the requirements described in the compare method's javadoc - with a focus on completeness and readability, e.g. by naming the variables the same as in the javadoc. Note that this is O(n^3), only use it when debugging, maybe just on a subset of your elements, in order to be fast enough to finish at all.
public static <T> void verifyComparator(Comparator<T> comparator, Collection<T> elements) {
for (T x : elements) {
for (T y : elements) {
for (T z : elements) {
int x_y = comparator.compare(x, y);
int y_x = comparator.compare(y, x);
int y_z = comparator.compare(y, z);
int x_z = comparator.compare(x, z);
// javadoc: The implementor must ensure that sgn(compare(x, y)) == -sgn(compare(y, x))
if (Math.signum(x_y) == -Math.signum(y_x)) { // ok
} else {
System.err.println("not holding: sgn(compare(x, y)) == -sgn(compare(y, x))" //
+ " | x_y: " + x_y + ", y_x: " + y_x + ", x: " + x + ", y: " + y);
}
// javadoc: The implementor must also ensure that the relation is transitive:
// ((compare(x, y)>0) && (compare(y, z)>0)) implies compare(x, z)>0.
if (x_y > 0 && y_z > 0) {
if (x_z > 0) { // ok
} else {
System.err.println("not holding: ((compare(x, y)>0) && (compare(y, z)>0)) implies compare(x, z)>0" //
+ " | x_y: " + x_y + ", y_z: " + y_z + ", x_z: " + x_z + ", x: " + x + ", y: " + y + ", z: " + z);
}
}
// javadoc: Finally, the implementor must ensure that:
// compare(x, y)==0 implies that sgn(compare(x, z))==sgn(compare(y, z)) for all z.
if (x_y == 0) {
if (Math.signum(x_z) == Math.signum(y_z)) { // ok
} else {
System.err.println("not holding: compare(x, y)==0 implies that sgn(compare(x, z))==sgn(compare(y, z)) for all z" //
+ " | x_y: " + x_y + ", x_z: " + x_z + ", y_z: " + y_z + ", x: " + x + ", y: " + y + ", z: " + z);
}
}
}
}
}
}
I had to sort on several criterion (date, and, if same date; other things...). What was working on Eclipse with an older version of Java, did not worked any more on Android : comparison method violates contract ...
After reading on StackOverflow, I wrote a separate function that I called from compare() if the dates are the same. This function calculates the priority, according to the criteria, and returns -1, 0, or 1 to compare(). It seems to work now.
What about doing something simpler like this:
int result = card1.getSet().compareTo(card2.getSet())
if (result == 0) {
result = card1.getRarity().compareTo(card2.getRarity())
}
if (result == 0) {
result = card1.getId().compareTo(card2.getId())
}
if (result == 0) {
result = card1.getCardType().compareTo(card2.getCardType())
}
return result;
You just need to order the comparisons in order of preference.

Can Xposed log current method name?

I want to test an application but it's too large to do by static approach.
I started googling. I found a interesting tool called Xposed Framework.
I read a lot of documents / examples. But I cant find the theads about getting method name of application.
My purpose is to log current method name when I press a button in app. Which parameters are sent when the methods are called?
For more information, the application I want to test is a chat application. I want to check that is it secured to use ? Is it true that developers claims the application uses blah blah blah encryption ? Is it real end-to-end encryption?.
According to the large of application, I need some tools to help me analyse this. When I send a message what methods are called ? what values are sent along with ?
If it is opensource you can easily insert a few logs in the source code and recompile. Some code coverage tools allow you to log the executed methods but i am unsure about the parameters (e.g. EMMA coverage).
If it is closed-source then you can do it with Xposed, but it has some challenges. Xposed allows you to hook Java methods, if it is opensource you can lookup the specific methods you want to intercept and print their parameters. If it is closed source, you can always check the method names through decompiling the app with apktool.
Check the Xposed tutorial on how to register hooks. Assuming you created your class that extends XC_MethodHook, the following methods should do the trick for primitive parameters:
#Override
protected void afterHookedMethod(MethodHookParam param) throws Throwable {
String threadname = Thread.currentThread().getName();
String d = _dateFormat.format(new Date());
Class<?> cls = param.this.getClass();
//Extend XC_MethodHook to receive the mthName in the constructor
//and store it as a static field.
Log.v("MethodInvocation", "[A][" + d + "]"
+ "[" + cls.getName() + "."
+ mthName
+ "(" + args(param) + ")" + " = " + result(param)
+ "]" + " [" + threadname + "]");
}
public boolean shouldPrintContent(Object o) {
if (o.getClass().isPrimitive()
|| o.getClass().getName().contains("java.lang"))
return true;
return false;
}
public String args(MethodHookParam param) {
String args = "";
int counter = 0;
if (param != null) {
for (Object o : param.args) {
if (counter > 0)
args += ",";
// argument can be null
if (o == null) {
args += "null";
} else { // if it is an object lets print its type and content.
args += printclean(o.getClass().getName());
if (shouldPrintContent(o)) {
args += ":" + printclean(o.toString());
} else
args += ":nonPrimitiveOrJavaLang";
}
counter++;
}
}
return args;
}
//avoid identation chars in strings
public String printclean(String str) {
char[] res = str.toCharArray();
for (int i = 0; i < str.length(); i++) {
if (res[i] == '\n' || res[i] == '\r' || res[i] == '\t'
|| res[i] == '[' || res[i] == ']') {
res[i] = '*';
}
}
return String.valueOf(res);
}
public String result(MethodHookParam param) {
String res = "";
Object retobj = param.getResult();
if (retobj == null) {
res += "null";
} else {
res += printclean(retobj.getClass().getName());
if (shouldPrintContent(retobj)) {
res += printclean(retobj.toString());
} else
res += "(nonPrimitiveOrJavaLang)";
}
return res;
}
Note that printing any object is not trivial. Here I printed only known types like primitives or other java.lang objects. More complex objects (including collections) you can try using Gson to represent them but this also comes with limitations (e.g. can't often handle reference loops).
Finally, be careful with what method you hook as hooking and logging methods that are called often will impact the performance of the app.
Good luck!
A new Xposed module called Inspeckage does (among many other useful inspections) what you want to do: you can use it to hook any method and view and even change its input and output.

How can I create Android logcat entries that provide a link to source code in Eclipse? [duplicate]

Is there any way to access automatically any Log in Logcat by a double click ?
Actually, when there is an error crashing my Android Application, I can double click on the line saying for instance
at com.myapp.mypackage$Class.function(File.java:117)
And by Double-clicking on this line, I am automatically redirected to the related line of my code.
But, when I try to generate the same line in another Log, example :
Log.e("TAG", "at com.myapp.mypackage$Class.function(File.java:117)");
The Double-Click doesn't work anymore ...
Any ideas ?
If you want to create a log in logcat that can be clicked and go to your line use the following method to create it:
Enjoy!
public static void showLogCat(String tag, String msg) {
StackTraceElement[] stackTraceElement = Thread.currentThread()
.getStackTrace();
int currentIndex = -1;
for (int i = 0; i < stackTraceElement.length; i++) {
if (stackTraceElement[i].getMethodName().compareTo("showLogCat") == 0)
{
currentIndex = i + 1;
break;
}
}
String fullClassName = stackTraceElement[currentIndex].getClassName();
String className = fullClassName.substring(fullClassName
.lastIndexOf(".") + 1);
String methodName = stackTraceElement[currentIndex].getMethodName();
String lineNumber = String
.valueOf(stackTraceElement[currentIndex].getLineNumber());
Log.i(tag, msg);
Log.i(tag + " position", "at " + fullClassName + "." + methodName + "("
+ className + ".java:" + lineNumber + ")");
}
If you don't mind the clutter in your log, you can easily just add a new Exception() to the log message
Log.e("TAG", "Looky here see", new Exception());

How to insert a log in LogCat that when I click on it jumps to its line in code?

I want to insert a log in LogCat that when I click on it jumps to its line like some error logs that are generated by system.
Is it possible?
I found it:
public static void showLogCat(String tag, String msg) {
StackTraceElement[] stackTraceElement = Thread.currentThread()
.getStackTrace();
int currentIndex = -1;
for (int i = 0; i < stackTraceElement.length; i++) {
if (stackTraceElement[i].getMethodName().compareTo("showLogCat") == 0)
{
currentIndex = i + 1;
break;
}
}
String fullClassName = stackTraceElement[currentIndex].getClassName();
String className = fullClassName.substring(fullClassName
.lastIndexOf(".") + 1);
String methodName = stackTraceElement[currentIndex].getMethodName();
String lineNumber = String
.valueOf(stackTraceElement[currentIndex].getLineNumber());
Log.i(tag, msg);
Log.i(tag + " position", "at " + fullClassName + "." + methodName + "("
+ className + ".java:" + lineNumber + ")");
}
Its usage:
showLogCat("tag", "message");
The important thing is to insert "(X:Y)" in your log message, while X is your desired file name and Y is your desired line number in X. (I learned it from #breceivemail's answer). So try:
public static void log(final String tag, final String msg) {
final StackTraceElement stackTrace = new Exception().getStackTrace()[1];
String fileName = stackTrace.getFileName();
if (fileName == null) fileName=""; // It is necessary if you want to use proguard obfuscation.
final String info = stackTrace.getMethodName() + " (" + fileName + ":"
+ stackTrace.getLineNumber() + ")";
Log.LEVEL(tag, info + ": " + msg);
}
Note: The LEVEL is the log level and can be v, d, i, w, e or wtf.
Now you can use log(tag, msg) instead of Log.LEVEL(tag, msg).
Example:
MainActivity.java:
...
public class MainActivity extends BaseActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
log("Test Tag", "Hello World!");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
...
...
The output:
12-30 14:24:45.343 ? I/Test Tag: onCreate (MainActivity.java:10): Hello World!
And MainActivity.java:10 automatically would be a link and you can click on it!
You can also assign following value to info variable if you want more verbose log:
final String info = stackTrace.getClassName() + "." + stackTrace.getMethodName() + " ("
+ fileName + ":" + stackTrace.getLineNumber() + ")\n";
So the output of above example would be:
12-30 14:33:07.360 ? I/Test Tag: com.example.myapp.MainActivity.onCreate (MainActivity.java:11)
Hello World!
Please use this Tree with Timber.
class MyLinkingTimberTree : Timber.DebugTree() {
override fun createStackElementTag(element: StackTraceElement): String? {
return makeClickableLineNumber(element)
}
private fun makeClickableLineNumber(
element: StackTraceElement
): String {
val className = element.fileName
val methodName = element.methodName
val lineNumber = element.lineNumber
val fileName = element.fileName
val stringBuilder = StringBuilder(className)
.append(".")
.append(methodName)
.append(" (")
.append(fileName)
.append(":")
.append(lineNumber)
.append(") ")
return stringBuilder.toString()
}
}
And then just instantiate it like this:
class MyApplication: Application() {
override fun onCreate() {
super.onCreate()
if(BuildConfig.DEBUG) {
Timber.plant(MyLinkingTimberTree())
}
}
}
Then just use Timber normally:
Timber.d("Currently Signed in:")
And this is the result. Nice, isn't it? I hope you enjoy using it as much as I enjoyed making it! ;)
Yes you can do it .. Follow the example as answered on SO - logging
To answer the question in a simple way:
respecter cette règle :
{FileName}.{ext}:{LigneNumber}
e.g. MainActivity.java:10
which gives a sample as below
Log.d(TAG, "onResume: MainActivity.java:10");
I hope this will help you
This isn't exactly an answer to the question, but perhaps it's a "close enough" workaround.
Highlight the log text
Press CTRL-SHIFT-F
Double-Click on the search result.
If the text is highlighted before you press CTRL-SHIFT-F, then you don't need to type or copy/paste it in.
If your searches tend to produce too many results, you can use live templates to make unique logcat entries:
Create a live template to insert the Class, Method, and Line-Number (at the time of writing). I use "logi." Yes, the line number will become less and less accurate as you continue to write, but it can still function as a way to make your log entries more "findable."

Is there any way to access automatically any Log in Logcat by a double click?

Is there any way to access automatically any Log in Logcat by a double click ?
Actually, when there is an error crashing my Android Application, I can double click on the line saying for instance
at com.myapp.mypackage$Class.function(File.java:117)
And by Double-clicking on this line, I am automatically redirected to the related line of my code.
But, when I try to generate the same line in another Log, example :
Log.e("TAG", "at com.myapp.mypackage$Class.function(File.java:117)");
The Double-Click doesn't work anymore ...
Any ideas ?
If you want to create a log in logcat that can be clicked and go to your line use the following method to create it:
Enjoy!
public static void showLogCat(String tag, String msg) {
StackTraceElement[] stackTraceElement = Thread.currentThread()
.getStackTrace();
int currentIndex = -1;
for (int i = 0; i < stackTraceElement.length; i++) {
if (stackTraceElement[i].getMethodName().compareTo("showLogCat") == 0)
{
currentIndex = i + 1;
break;
}
}
String fullClassName = stackTraceElement[currentIndex].getClassName();
String className = fullClassName.substring(fullClassName
.lastIndexOf(".") + 1);
String methodName = stackTraceElement[currentIndex].getMethodName();
String lineNumber = String
.valueOf(stackTraceElement[currentIndex].getLineNumber());
Log.i(tag, msg);
Log.i(tag + " position", "at " + fullClassName + "." + methodName + "("
+ className + ".java:" + lineNumber + ")");
}
If you don't mind the clutter in your log, you can easily just add a new Exception() to the log message
Log.e("TAG", "Looky here see", new Exception());

Categories

Resources