Possible to have custom logs in logcat? - android

I'm using logcat for monitoring my android projects in a custom way. I export my data,errors,method info and many other options.
I prefer to not to use Log defaults like Lod.d or Log.e or etc.
Is it possible to have my own custome logs for example Log.myLog with a new color in Logcat?
I prefer my logs do not interfere with android logs.
I've searched a lot but can't find anything about this purpose:
http://wiki.cyanogenmod.org/w/Doc:_debugging_with_logcat
http://logc.at/

I can recommend you a good one: https://github.com/oronno/log4android
Features
Log syntax similar with popular log4j framework
Automatically added TAG with log message
Derive TAG from the package name
Can disable logging by simply calling Logger.disableLogging(true) method preferably from the class extends Application.
Fully Qualified Class name or SimpleClassName will logged as prefix with log message
Variable Arguments (more than 2) can be passed for printing unlike log4j framework
Very lightweight, < 5KB library size!
I do use it in my every android application.

some time ago i wrote an eclipse plugin that modifies android.util.Log.* calls so that when
you have in your code:
Log.d(TAG, "********** this is line 49 in onCreate method");
android.util.Log.d(TAG, "********** this is line 50 in onCreate method");
you will see in the LogCat:
D/Test ( 306): onCreate:49, ********** this is line 49 in onCreate method
D/Test ( 306): onCreate:50, ********** this is line 50 in onCreate method
the plugin sources are here: https://github.com/pskink/AndroidLoggerBuilder.git

Maybe you should try to establish its own tag for its log? You can then easily filter logs without having to allocate a different color.

Related

Is it okay to use emojis in Logcat logs?

I am using emojis in log cat messages in order to make the logs easier on the eye. So far it works fine, but I wonder if I'll hit any character compatibility issues on older Android devices. My app's minimumSdkVersion is 16.
Examples:
companion object {
private const val TAG = "\uD83D\uDD36SomeClass"
}
...
Log.d(TAG, "⏰ Something happened!")
Is there anything I should be worried about? Are there any reasons against doing this?
Not sure about your emojis in Logcat but I think that if you want to make your life easier use the TAG that inside your Log.d.
For example, here is a log with a custom TAG:
Log.d("myTag","something to show");
After you run your app all you need to do is to search the same tag name within your logcat, like this:
Another thing that you should think about that if you want to search for a specific log would it be comfortable to search the logcat using emojis?
In my opinion, simply searching your tag name to find your log makes thing super easy.

Why shouldn't I use System.out.println() in android

In the Android Open Source Project's code style, it states that we shouldn't use System.out.println() but I don't understand why. Can anyone explain? What should I use to trace my app's log?
Here's the line for reference:
System.out.println() (or printf() for native code) should never be used. System.out and System.err get redirected to /dev/null, so your print statements will have no visible effects. However, all the string building that happens for these calls still gets executed.
You should use the android.util.Log class.
Here's a description of what the Log class does:
API for sending log output.
Generally, you should use the Log.v(), Log.d(), Log.i(), Log.w(), and Log.e() methods to write logs. You can then view the logs in logcat.
The order in terms of verbosity, from least to most is ERROR, WARN, INFO, DEBUG, VERBOSE. Verbose should never be compiled into an application except during development. Debug logs are compiled in but stripped at runtime. Error, warning and info logs are always kept.
These are the available methods of the Log class:
Log.d() - Send a DEBUG log message.
Log.e() - Send an ERROR log message.
Log.i() - Send an INFO log message.
Log.v() - Send a VERBOSE log message.
Log.w() - Send a WARN log message.
Log.wtf() - What a Terrible Failure: Report an exception that should never happen.
The methods above (with the exception of Log.w and Log.wtf which have 3 possible patterns of arguments) require the following arguments:
String tag, String msg:
tag: Used to identify the source of a log message. This value may be null.
msg: The message you would like logged. This value may be null.
String tag, String msg, Throwable tr - Similar to the first pattern, but allows for an exception to be specified. This pattern should be used if you want to log an exception to the log output.
(For Log.w and Log.wtf) String tag, Throwable tr Similar to the third pattern, but does not allow for a message to be specified. Note that you can still pass a message but it should be in the second arrangement of arguments.
EDIT: Going straight to answer your question: println() of System.out and System.err will still be displayed in logcat but with limitations.
You can't log VERBOSE, ERROR, or DEBUG using System.out or System.err.
You can't define your own tag, it will display System.err or System.out with your text. For instance:
System.out.println("Hello!") is equivalent to Log.i("System.out","Hello!")
System.err.println("Hello!") is equivalent to Log.w("System.err","Hello!")
System.out.println("") in android will not run well because there is no Terminal that the app is corrected to.
You would be better off using Log.(d)(v)(e)(i)(w), because there is something actively monitoring LogCat.
System.out.println() will print to LogCat, but only after an additional set of System instuctions, making it not as efficient, however, as i said, it still works.
if we want to trace the android project
we can do it using Log class
there is some methods like
Log.e(TAG,MESSAGE)
Log.v(TAG,MESSAGE)
Log.w(TAG,MESSAGE)
Log.d(TAG,MESSAGE)
Log.i(TAG,MESSAGE)
its a static method of Utils package. put it line by line and u can watch it in the LogCat..
thats at enjoy with android
From your own link:
System.out.println() (or printf() for native code) should never be
used. System.out and System.err get redirected to /dev/null, so your
print statements will have no visible effects. However, all the string
building that happens for these calls still gets executed.
In addition, at the beginning of that page, it says:
The rules below are not guidelines or recommendations, but strict
rules. Contributions to Android generally will not be accepted if they
do not adhere to these rules.
So DON'T do it!
You can use the built in Log utility that will print right out to the LogCat.
You can use Log.e(String, String) for errors which will appear in red. There is also v, d, i, and w for verbose, debug, info, and warning respectively.
The following should do the trick to print the exception
1. Log.d("myapp", Log.getStackTraceString(new Exception()));
or
2. You can get longer stack traces by digging deeper. For example:
Log.getStackTraceString(e.getCause().getCause());
Log is the best way to trace our android project
like following code...
it will help u...
just look in DDMS logCat that how exactly project is build...
requirement... android.utils.Log; package is used..
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
for(int i=0;i
{
Log.e("i = ",""+i);
Log.v("i = ",""+i);
Log.i("i = ",""+i);
Log.w("i = ",""+i);
Log.d("i = ",""+i);
}
}
i hope it will help u

Android: "Class loader may fail for processes that host multiple applications"

What does this message in Eclipse's logcat for Android mean?
W/ActivityThread: ClassLoader.getResources: The class loader returned by Thread.getContextClassLoader() may fail for processes that host multiple applications. You should explicitly specify a context class loader. For example: Thread.setContextClassLoader(getClass().getClassLoader());
Unfortunately, there is no context given as to this warning, so I don't know what causes this problem and how I can resolve it.
Background information
The message means that Android has setup a dummy ClassLoader with Thread.currentThread().setContextClassLoader(), and something tries to use that dummy class loader. The something can be a lot of things, it's hard to tell exactly what from the information given. There is a trick you can try though, see below. Anyway, Android sets up the dummy class loader when there is a risk that the process might contain code from more than one APK. More specifically, Android looks in your manifest if you have used android:sharedUserId:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
...
android:sharedUserId="triggers.dummy.loader" >
or if you run in a non-standard android:process
<application android:process="triggers.dummy.loader">
How to get rid of the warning
There are two things you can do to get rid of the warning:
Don't use android:sharedUserId or android:process
Explicitly set what APK ClassLoader to use before running any other code
To go with solution 2, there are some key insights you need. First, for any class AnyClass in an APK, AnyClass.class.getClassLoader() will return the same ClassLoader. Second,
AnyClass obj = new AnyClass();
Thread.currentThread().setContextClassLoader(obj.getClass().getClassLoader())
is the same as
Thread.currentThread().setContextClassLoader(AnyClass.class.getClassLoader())
Third, you need to call Thread.currentThread().setContextClassLoader(getClass().getClassLoader()) before the code that calls Thread.currentThread().getContextClassLoader().
Fourth, When many APKs are involved, you need to call Thread.setContextClassLoader(getClass().getClassLoader()) after the last APK has been loaded (otherwise loading the last APK will overwrite what you have set manually). Because of that, it would be a good idea to find out who is using the context class loader in you case by using the below debug trick. Then, right before that, you call Thread.setContextClassLoader(getClass().getClassLoader()) for a class from the desired APK, typically the APK that is loaded first (or, in the case when only one APK is involved, that APK ;). Fifth, the context class loader is per thread, which you need to keep in mind if your application is multi-threaded.
Debug trick
If you want to find out what code that calls ClassLoader.getResources(), this should work:
Thread.currentThread().setContextClassLoader(new ClassLoader() {
#Override
public Enumeration<URL> getResources(String resName) throws IOException {
Log.i("Debug", "Stack trace of who uses " +
"Thread.currentThread().getContextClassLoader()." +
"getResources(String resName):", new Exception());
return super.getResources(resName);
}
});
if you do this early enough, you should see in the logcat a stack trace that goes back to whoever calls getResources() on the dummy class loader.
I received this warning without either android:sharedUserId or android:process in my Manifest...
Found it only presented on an emulator...
Devices did not present the warning message. Tested on Smartphone KitKat 4.4 API 19, and Tablet 5.0.1 API 21.

ClassLoader.class "source not found" error when instantiating a database class in android

I am trying to implement Content Providers and Cursor Loaders to get away from cursors as recommended by Android/Google. However, I'm having a terrible time of it. I'm using the tutorials at http://mobile.tutsplus.com/tutorials/android/android-sdk_content-providers/ as my guide and the simplest thing just isn't working. At the beginning of my Activity, I'm doing the following:
SQLData entry = new SQLData(getApplicationContext());
I've also tried
SQLData entry = new SQLData(this);
SQLData is the name of my database class. What I'd like to do after this line of code is create and populate the database using the methods from the content provider class I've created. However, when I try to move past this line in the debugger, a ClassLoader.class window opens, with the message "source not found". I've reloaded and refreshed and cleaned my package, but this doesn't help. I'm happy to provide all the code for my database and content provider classes, but I'm not sure that's what's needed here. Does anyone know how to approach this issue?
Thanks very much!
In android, or any java dev; you may find it more useful to write JUnit tests and put lots of
Log.v(TAG, "message about " + variable);
in your code instead of using the debugger...
I write Java code as my job and use the debug option maybe twice a year as a last resort...
the JUnit tests get my errors out and save me TONS of time, stepping through code in the debugger can be a very time consuming thing...
just a tip, and it may just be my personal pref...

android.util.Log when publishing - what can I do / not do

I've got a hell of a lot of Log.i Log.d Log.e in my code for a recent app I've done. I'm about to publish this app and I don't really want people seeing it when they plug there phone into adb, but I do want it there for my own debugging.
I was wanting to extend android.util.log and just have a boolean switch in there so I could just turn off the log when I publish and turn it on when developing but this class is final, am I missing a trick?
I don't really want to go through my code an remove all, true if worst comes to worst I could do a ctrl+h global replace Log for //Log but that does suck as an answer.
I also realise that Log.d is stripped out at runtime but it is still ran (losing a little performance) so not running this would be an added bonus.
Yeah so basically I'm looking for a way to toggle my debug on and off programatically, this can also allow me later on to make it a preference or something if people want to view it or help out and send it on.
What do you guys implement for this?
Thanks
As Octavian points out inserting a logging constant would be the best way to do this. Writing a new class for this that calls the original logging methods if debugging is enabled is not a good idea.
Good practice:
if (C.D) { Log.d(C.T, "your log text here " + foo + bar); }
Bad practice:
YourLog.d("your log text here " + foo + bar);
// and in YourLog.java's d() method:
... { if (debugging) Log.d(tag, text); }
The first solution is very fast if the constant D of class C is false. If you have complex string operations for creating your logging string they will not be executed if debugging is deactivated. The compiler can even remove these operations at compile time if D is false, which may result in zero runtime overhead. The second (bad) solution will always build the whole string and call a method, which is overhead you don't need.
In general the first solution would be best. And yes, I really call the class and members C, D and T (Constants/Debugging/Tag) - for performance reasons during typing. ;-)
obfuscate using Proguard as proguard has commands to use to filter it out when you write your proguard config file..nice and simple and it works
It is generally a good practice to not include them in your distribution code in any way since they will need to be processed which just leads to unnecessary battery drain.
You could set a boolean in your application somewhere to indicate development or release version of your code and have a lot of if blocks checking for the flag and executing your log code or not but this just leads to code bloat.
You should get rid of them once you no longer need them.

Categories

Resources