Keep Logcat from deleting entries - android

In Eclipse, I notice that Logcat only retains a few dozen entries and deletes the older ones as soon as a new one come in. Is there a way to prevent this? I need my app to run for a long time and not lose any entries because my app eventually hangs or crashes after a few days, and I want to see if something in Logcat has been recorded.

I am not sure if this is the most elegant solution to the problem, but you can always increase the LogCat message size in Eclipse.
Window -> Preferences -> Android -> LogCat -> Maximum number of LogCat messages to buffer
The default is 5000, I believe. You can set it to be very high if you are planning to run your application for a long time.

i think you need to increase this show image

Here's a better solution:
Set the Default Uncaught Exception Handler. Whenever the app crashes, this will be called with the exception. Simply write a log entry saying it crashed then dump the logcat to a file. Finally, make sure you re-throw the exception to make sure the app crashes and funky things don't happen. Note: This is per thread, keep that in mind.
Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {
#Override
public void uncaughtException(Thread thread, Throwable ex) {
Log.e("TAG", "---My app crashed just now---", ex);
//TODO: Dump logcat to file
throw new RuntimeException(ex);
}
});

if you want to keep your app running for days.. its better you capture your logs from adb shell.
the common shell command would be :
logcat -c \\ to clear previous logs
logcat -v time>yourLogs.txt & \\ to capture fresh logs

Related

False positives: junit.framework.AssertionFailedError: EditText is not found

I have a problem setting up Robotium tests to run on Travis without random false posivities.
Every couple of builds I get
pl.mg6.agrtt.TestActivityTests > testCanEnterTextAndPressButton[test(AVD) - 4.4.2] FAILED
junit.framework.AssertionFailedError: EditText is not found!
at com.robotium.solo.Waiter.waitForAndGetView(Waiter.java:540)
on all my tests.
I have created a simple project on GitHub to show the issue.
You may see how it builds on Travis. Note build #7 failed after modyfing unrelated file.
I'm suspecting this to be caused by emulator being locked or its sceeen dimmed. I could reproduce this issue on local machine by turning connected device's screen off and then running
./gradlew connectedAndroidTest
After modyfing tests I got a different error message, which is somewhat more informative, so I'm adding it just in case someone tries to find a solution:
pl.mg6.agrtt.TestActivityTests > testCanFindViewsEnterTextAndPressButton[test(AVD) - 4.4.2] FAILED
junit.framework.AssertionFailedError: Click at (160.0, 264.0) can not be completed! (java.lang.SecurityException: Injecting to another application requires INJECT_EVENTS permission)
at com.robotium.solo.Clicker.clickOnScreen(Clicker.java:106)
While the root cause of this problem is still unknown to me, after some investigation and with a help from Robotium's author Renas Reda I could confirm what I initially suspected that emulator indeed locks itself.
A workaround I'm using now is this code put in setUp method:
getInstrumentation().runOnMainSync(new Runnable() {
#Override
public void run() {
getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
}
});
Robotium discards invisible views when using enterText(int, String). Instead use getView(int) of Solo to use resulting view in enterText(View, String).
Like this:
public void testCanEnterTextAndPressButton() {
solo.enterText(((EditText) solo.getView(R.id.editText1)), "my login");
solo.enterText(((EditText) solo.getView(R.id.editText2)), "my password");
solo.clickOnView(solo.getView(R.id.button));
}
And if the device screen is locked Robotium fails to run those instructions you gave. You might want to disable screen locking.
By code above my tests pass.
Your guess is probably right. One way to be sure that it is is to catch the exception that is thrown and call
solo.takeScreenshot("screenshotFileName");
and then take a look at the screenshot that is saved to your phone's SD card to see what your phone was doing at the time of the error.
I solved this problem by turning on the device's "Stay Awake" setting so it won't sleep while recharging.

Viewing logcat in tablet

Is there a way to view the log on a tablet running 4.4? I've downloaded several apps like aLogCat and none of them show what my app writes out with S.o.p or Log.d. I have an intermittent bug that gives the Unfortunately appname has stopped message.Is there any way to view the log after this event without having to connect to a PC and use the adb program?
What other ways are there to get debug output? Would trapping the System.out and System.err classes get the stack trace?
Thanks,
Norm
You're focussing on tring to read out logcat, but there are better solutions for reading crash logs. My personal preference is Crashlytics, which automatically logs fatal exceptions and provides mechanisms for logging other messages.
The way all these crash reporters work, is by defining a UncaughtExceptionHandler:
Thread.setDefaultUncaughtExceptionHandler(
new MyUncaughtExceptionHandler(this));
If you prefer to use your own solution, you may want to look into using this. See this related question for more details.
Is there a way to view the log on a tablet running 4.4?
No, sorry. An app can only see its own log messages, not those from other apps. Hence, a third-party log viewer cannot see your app's messages.
Is there any way to view the log after this event without having to connect to a PC and use the adb program?
Use any standard crash management library, like ACRA, or services like Crashlytics, BugSense, etc.
The AIDE Application (Android Integrated Development Environment) allows one to develop android Apps directly on android device.
One particular feature is to read the logcat.
You can get it here https://play.google.com/store/apps/details?id=com.aide.ui
Here's the code I've put in the program. It seems to work:
// Define inner class to handle exceptions
class MyExceptionHandler implements Thread.UncaughtExceptionHandler {
public void uncaughtException(Thread t, Throwable e){
java.util.Date dt = new java.util.Date();
String fn = LogFilePathPfx + "exception_" + sdf.format(dt) + ".txt";
try{
PrintStream ps = new PrintStream( fn );
e.printStackTrace(ps);
ps.close();
System.out.println("wrote trace to " + fn);
e.printStackTrace(); // capture here also???
SaveStdOutput.stop(); // close here vs calling flush() in class
}catch(Exception x){
x.printStackTrace();
}
lastUEH.uncaughtException(t, e); // call last one Gives: "Unfortunately ... stopped" message
return; //???? what to do here
}
}
lastUEH = Thread.getDefaultUncaughtExceptionHandler(); // save previous one
Thread.setDefaultUncaughtExceptionHandler(new MyExceptionHandler());

Runtime.exec() bug: hangs

First thing my app does is checking for "su" since it's necessary for the app to work. Even though it sometimes work, often after typing "killall packageName" in the terminal. I've done a simple test application and I can't get it to work every time.
Code where it happens:
String[] args = new String[] { "su" };
Log.v(TAG, "run(" + Arrays.toString(args) + ")");
FutureTask<Process> task = new FutureTask<Process>(new Callable<Process>() {
#Override
public Process call() throws Exception {
return Runtime.getRuntime().exec(args);
}
});
try {
Executors.newSingleThreadExecutor().execute(task);
return task.get(10, TimeUnit.SECONDS);
} catch (Throwable t) {
task.cancel(true);
throw new IOException("failed to start process within 10 seconds", t);
}
Complete project: https://github.com/chrulri/android_testexec
Since this app does nothing more than running exec() in the first place, I cannot close any previously opened file descriptors as mentioned in another stackoverflow question: https://stackoverflow.com/a/11317150/1145705
PS: I run Android 4.0.3 / 4.0.4 on different devices.
3c71 was right about open file descriptors. In my case, it was the AdMob SDK which caused the problems since it was sometimes (re-)loading the Ads from the web at the sime time I tried to call exec(..) leaving me hanging in a deadlock.
My solution is to fork a "su" process ONCE and reuse it for all commands and load the Ads AFTER forking that process.
To use Runtime.exec safely you should wait for the process to finish and consume the output and error streams, preferably concurrently (to prevent blocking):
http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html

Runtime.exec() bug: hangs without providing a Process object

Whether I use this:
process = Runtime.getRuntime().exec("logcat -d time");
or that:
process = new ProcessBuilder()
.command("logcat", "-d", "time")
.redirectErrorStream(true)
.start();
I get the same results: it often hangs within the exec() or start() call, no matter what I tried to do!
The thread running this cannot even be interrupted with Thread.interrupt()! The child process is definitely started and if killed the above commands return.
These calls may fail on first attempt, so THERE IS NO WAY TO READ THEIR OUTPUT! I can also use a simple "su -c kill xxx" command line, same result!
EDIT: Started debugging the java_lang_ProcessManager.cpp file in an NDK project with some debugging logs! So here is what I found so far, after the fork() the parent does this:
int result;
int count = read(statusIn, &result, sizeof(int)); <- hangs there
close(statusIn);
Though the child process is not supposed to block on it: That's what the child does (if started at all!):
// Make statusOut automatically close if execvp() succeeds.
fcntl(statusOut, F_SETFD, FD_CLOEXEC); <- make the parent will not block
// Close remaining unwanted open fds.
closeNonStandardFds(statusOut, androidSystemPropertiesFd); <- hangs here sometimes
...
execvp(commands[0], commands);
// If we got here, execvp() failed or the working dir was invalid.
execFailed:
int error = errno;
write(statusOut, &error, sizeof(int));
close(statusOut);
exit(error);
The child can fail for 2 reproducible reasons:
1- child code is not running, but the parent believes it is!
2- child blocks on
closeNonStandardFds(statusOut, androidSystemPropertiesFd);
In either case the read(statusIn...) in the parent ends in deadlock! and a child process is left dead (and cannot be accessed, pid unknown, no Process object)!
This problem is fixed in Jelly Bean (Android 4.1) but not in ICS (4.0.4) and I guess it will never be fixed in ICS.
Above solution didn't prove to be reliable in any ways, causing more issues on some devices!
So I reverted back to the standard .exec() and kept digging...
Looking at the child code that hangs, I noticed the child process will hang while trying to close all file descriptors inherited from the parent (except the one created within the exec() call) !
So I search the whole app code for any BufferedReader/Writer and similar classes to make sure those would be closed when calling exec()!
The frequency of the issue was considerably reduced, and actually never occured again when I removed the last opened file descriptor before calling exec().
NB: Make sure SU binary is up-to-date, it can actually cause this issue too!
Enjoy your search ;)
Bug fix in Bionic was commited monthes ago, but it still hasn't been included in Android 4.0.4.
I have the same problem on ICS (seem to works fine on Android < 4). Did you find a solution?
A simple workaround could be to call the "exec" method in a dedicated thread with a timeout-join so that this situation could be "detected" (yes I know it's not very elegant...)

How to see the crash reason in Eclipse debugger

Following this Android tutorial: http://developer.android.com/resources/tutorials/hello-world.html I added two lines which should cause null pointer exception:
Object o = null;
o.toString();
Now I set breakpoint on the second line and start debugger. When debugger breaks, I click "Step over" and application crashes. However, I don't see any useful information in the debugger. Debug window shows ActivityThread.performLaunchActivity, Source window shows "No source found". I don't see any information about exception, null pointer, etc. in any Eclipse debugger window, and don't see anything pointing to my line of code that causes crash. So, what am I missing?
Edit. Maybe Android UI framework has its own exception handling mechanizm, which prevents me to see exception immediately in my code? Something like this happens in another UI frameworks, like WinForms, Qt, wxWidgets.
After exception occurs you should check Logcat window for details: there you find the entire stack leading to the line of code where exception is. In some cases exception will occur in some other class (not yours) - then you should look for your package/class name in the stack to find otu whether you're "responsible" for it.
Corresponding output will not appear in Logcat immediately - let it run for some time (or until it crashes).
Also you can set "Java exception breakpoint" so the execution will break whenever there is an exception.
You can see the error in the LogCat. Window->Show View->other->Logcat
Try something like this...
try {
Object o = null;
o.toString();
}
catch (Exception e) {
e.printStackTrace();
}
...and use the DDMS perspective in eclipse.
Ideally you want to catch specific exceptions so the catch block would be...
catch (NullPointerException npe {
npe.printStackTrace();
}
...but doing a 'catch all' for Exception as in my first example and using the eclipse DDMS perspective to view logcat output will give you a good head start.
Finally, I found useful information in the "Breakpoints" debugger window. It shows NullPointerException and points exactly to offensive line.

Categories

Resources