1 /*
2  * Copyright (C) 2006 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package android.util;
18 
19 import android.os.DeadSystemException;
20 
21 import com.android.internal.os.RuntimeInit;
22 import com.android.internal.util.FastPrintWriter;
23 import com.android.internal.util.LineBreakBufferedWriter;
24 
25 import java.io.PrintWriter;
26 import java.io.StringWriter;
27 import java.io.Writer;
28 import java.net.UnknownHostException;
29 
30 /**
31  * API for sending log output.
32  *
33  * <p>Generally, use the Log.v() Log.d() Log.i() Log.w() and Log.e()
34  * methods.
35  *
36  * <p>The order in terms of verbosity, from least to most is
37  * ERROR, WARN, INFO, DEBUG, VERBOSE.  Verbose should never be compiled
38  * into an application except during development.  Debug logs are compiled
39  * in but stripped at runtime.  Error, warning and info logs are always kept.
40  *
41  * <p><b>Tip:</b> A good convention is to declare a <code>TAG</code> constant
42  * in your class:
43  *
44  * <pre>private static final String TAG = "MyActivity";</pre>
45  *
46  * and use that in subsequent calls to the log methods.
47  * </p>
48  *
49  * <p><b>Tip:</b> Don't forget that when you make a call like
50  * <pre>Log.v(TAG, "index=" + i);</pre>
51  * that when you're building the string to pass into Log.d, the compiler uses a
52  * StringBuilder and at least three allocations occur: the StringBuilder
53  * itself, the buffer, and the String object.  Realistically, there is also
54  * another buffer allocation and copy, and even more pressure on the gc.
55  * That means that if your log message is filtered out, you might be doing
56  * significant work and incurring significant overhead.
57  */
58 public final class Log {
59 
60     /**
61      * Priority constant for the println method; use Log.v.
62      */
63     public static final int VERBOSE = 2;
64 
65     /**
66      * Priority constant for the println method; use Log.d.
67      */
68     public static final int DEBUG = 3;
69 
70     /**
71      * Priority constant for the println method; use Log.i.
72      */
73     public static final int INFO = 4;
74 
75     /**
76      * Priority constant for the println method; use Log.w.
77      */
78     public static final int WARN = 5;
79 
80     /**
81      * Priority constant for the println method; use Log.e.
82      */
83     public static final int ERROR = 6;
84 
85     /**
86      * Priority constant for the println method.
87      */
88     public static final int ASSERT = 7;
89 
90     /**
91      * Exception class used to capture a stack trace in {@link #wtf}.
92      */
93     private static class TerribleFailure extends Exception {
TerribleFailure(String msg, Throwable cause)94         TerribleFailure(String msg, Throwable cause) { super(msg, cause); }
95     }
96 
97     /**
98      * Interface to handle terrible failures from {@link #wtf}.
99      *
100      * @hide
101      */
102     public interface TerribleFailureHandler {
onTerribleFailure(String tag, TerribleFailure what, boolean system)103         void onTerribleFailure(String tag, TerribleFailure what, boolean system);
104     }
105 
106     private static TerribleFailureHandler sWtfHandler = new TerribleFailureHandler() {
107             public void onTerribleFailure(String tag, TerribleFailure what, boolean system) {
108                 RuntimeInit.wtf(tag, what, system);
109             }
110         };
111 
Log()112     private Log() {
113     }
114 
115     /**
116      * Send a {@link #VERBOSE} log message.
117      * @param tag Used to identify the source of a log message.  It usually identifies
118      *        the class or activity where the log call occurs.
119      * @param msg The message you would like logged.
120      */
v(String tag, String msg)121     public static int v(String tag, String msg) {
122         return println_native(LOG_ID_MAIN, VERBOSE, tag, msg);
123     }
124 
125     /**
126      * Send a {@link #VERBOSE} log message and log the exception.
127      * @param tag Used to identify the source of a log message.  It usually identifies
128      *        the class or activity where the log call occurs.
129      * @param msg The message you would like logged.
130      * @param tr An exception to log
131      */
v(String tag, String msg, Throwable tr)132     public static int v(String tag, String msg, Throwable tr) {
133         return printlns(LOG_ID_MAIN, VERBOSE, tag, msg, tr);
134     }
135 
136     /**
137      * Send a {@link #DEBUG} log message.
138      * @param tag Used to identify the source of a log message.  It usually identifies
139      *        the class or activity where the log call occurs.
140      * @param msg The message you would like logged.
141      */
d(String tag, String msg)142     public static int d(String tag, String msg) {
143         return println_native(LOG_ID_MAIN, DEBUG, tag, msg);
144     }
145 
146     /**
147      * Send a {@link #DEBUG} log message and log the exception.
148      * @param tag Used to identify the source of a log message.  It usually identifies
149      *        the class or activity where the log call occurs.
150      * @param msg The message you would like logged.
151      * @param tr An exception to log
152      */
d(String tag, String msg, Throwable tr)153     public static int d(String tag, String msg, Throwable tr) {
154         return printlns(LOG_ID_MAIN, DEBUG, tag, msg, tr);
155     }
156 
157     /**
158      * Send an {@link #INFO} log message.
159      * @param tag Used to identify the source of a log message.  It usually identifies
160      *        the class or activity where the log call occurs.
161      * @param msg The message you would like logged.
162      */
i(String tag, String msg)163     public static int i(String tag, String msg) {
164         return println_native(LOG_ID_MAIN, INFO, tag, msg);
165     }
166 
167     /**
168      * Send a {@link #INFO} log message and log the exception.
169      * @param tag Used to identify the source of a log message.  It usually identifies
170      *        the class or activity where the log call occurs.
171      * @param msg The message you would like logged.
172      * @param tr An exception to log
173      */
i(String tag, String msg, Throwable tr)174     public static int i(String tag, String msg, Throwable tr) {
175         return printlns(LOG_ID_MAIN, INFO, tag, msg, tr);
176     }
177 
178     /**
179      * Send a {@link #WARN} log message.
180      * @param tag Used to identify the source of a log message.  It usually identifies
181      *        the class or activity where the log call occurs.
182      * @param msg The message you would like logged.
183      */
w(String tag, String msg)184     public static int w(String tag, String msg) {
185         return println_native(LOG_ID_MAIN, WARN, tag, msg);
186     }
187 
188     /**
189      * Send a {@link #WARN} log message and log the exception.
190      * @param tag Used to identify the source of a log message.  It usually identifies
191      *        the class or activity where the log call occurs.
192      * @param msg The message you would like logged.
193      * @param tr An exception to log
194      */
w(String tag, String msg, Throwable tr)195     public static int w(String tag, String msg, Throwable tr) {
196         return printlns(LOG_ID_MAIN, WARN, tag, msg, tr);
197     }
198 
199     /**
200      * Checks to see whether or not a log for the specified tag is loggable at the specified level.
201      *
202      *  The default level of any tag is set to INFO. This means that any level above and including
203      *  INFO will be logged. Before you make any calls to a logging method you should check to see
204      *  if your tag should be logged. You can change the default level by setting a system property:
205      *      'setprop log.tag.&lt;YOUR_LOG_TAG> &lt;LEVEL>'
206      *  Where level is either VERBOSE, DEBUG, INFO, WARN, ERROR, ASSERT, or SUPPRESS. SUPPRESS will
207      *  turn off all logging for your tag. You can also create a local.prop file that with the
208      *  following in it:
209      *      'log.tag.&lt;YOUR_LOG_TAG>=&lt;LEVEL>'
210      *  and place that in /data/local.prop.
211      *
212      * @param tag The tag to check.
213      * @param level The level to check.
214      * @return Whether or not that this is allowed to be logged.
215      * @throws IllegalArgumentException is thrown if the tag.length() > 23
216      *         for Nougat (7.0) releases (API <= 23) and prior, there is no
217      *         tag limit of concern after this API level.
218      */
isLoggable(String tag, int level)219     public static native boolean isLoggable(String tag, int level);
220 
221     /*
222      * Send a {@link #WARN} log message and log the exception.
223      * @param tag Used to identify the source of a log message.  It usually identifies
224      *        the class or activity where the log call occurs.
225      * @param tr An exception to log
226      */
w(String tag, Throwable tr)227     public static int w(String tag, Throwable tr) {
228         return printlns(LOG_ID_MAIN, WARN, tag, "", tr);
229     }
230 
231     /**
232      * Send an {@link #ERROR} log message.
233      * @param tag Used to identify the source of a log message.  It usually identifies
234      *        the class or activity where the log call occurs.
235      * @param msg The message you would like logged.
236      */
e(String tag, String msg)237     public static int e(String tag, String msg) {
238         return println_native(LOG_ID_MAIN, ERROR, tag, msg);
239     }
240 
241     /**
242      * Send a {@link #ERROR} log message and log the exception.
243      * @param tag Used to identify the source of a log message.  It usually identifies
244      *        the class or activity where the log call occurs.
245      * @param msg The message you would like logged.
246      * @param tr An exception to log
247      */
e(String tag, String msg, Throwable tr)248     public static int e(String tag, String msg, Throwable tr) {
249         return printlns(LOG_ID_MAIN, ERROR, tag, msg, tr);
250     }
251 
252     /**
253      * What a Terrible Failure: Report a condition that should never happen.
254      * The error will always be logged at level ASSERT with the call stack.
255      * Depending on system configuration, a report may be added to the
256      * {@link android.os.DropBoxManager} and/or the process may be terminated
257      * immediately with an error dialog.
258      * @param tag Used to identify the source of a log message.
259      * @param msg The message you would like logged.
260      */
wtf(String tag, String msg)261     public static int wtf(String tag, String msg) {
262         return wtf(LOG_ID_MAIN, tag, msg, null, false, false);
263     }
264 
265     /**
266      * Like {@link #wtf(String, String)}, but also writes to the log the full
267      * call stack.
268      * @hide
269      */
wtfStack(String tag, String msg)270     public static int wtfStack(String tag, String msg) {
271         return wtf(LOG_ID_MAIN, tag, msg, null, true, false);
272     }
273 
274     /**
275      * What a Terrible Failure: Report an exception that should never happen.
276      * Similar to {@link #wtf(String, String)}, with an exception to log.
277      * @param tag Used to identify the source of a log message.
278      * @param tr An exception to log.
279      */
wtf(String tag, Throwable tr)280     public static int wtf(String tag, Throwable tr) {
281         return wtf(LOG_ID_MAIN, tag, tr.getMessage(), tr, false, false);
282     }
283 
284     /**
285      * What a Terrible Failure: Report an exception that should never happen.
286      * Similar to {@link #wtf(String, Throwable)}, with a message as well.
287      * @param tag Used to identify the source of a log message.
288      * @param msg The message you would like logged.
289      * @param tr An exception to log.  May be null.
290      */
wtf(String tag, String msg, Throwable tr)291     public static int wtf(String tag, String msg, Throwable tr) {
292         return wtf(LOG_ID_MAIN, tag, msg, tr, false, false);
293     }
294 
wtf(int logId, String tag, String msg, Throwable tr, boolean localStack, boolean system)295     static int wtf(int logId, String tag, String msg, Throwable tr, boolean localStack,
296             boolean system) {
297         TerribleFailure what = new TerribleFailure(msg, tr);
298         // Only mark this as ERROR, do not use ASSERT since that should be
299         // reserved for cases where the system is guaranteed to abort.
300         // The onTerribleFailure call does not always cause a crash.
301         int bytes = printlns(logId, ERROR, tag, msg, localStack ? what : tr);
302         sWtfHandler.onTerribleFailure(tag, what, system);
303         return bytes;
304     }
305 
wtfQuiet(int logId, String tag, String msg, boolean system)306     static void wtfQuiet(int logId, String tag, String msg, boolean system) {
307         TerribleFailure what = new TerribleFailure(msg, null);
308         sWtfHandler.onTerribleFailure(tag, what, system);
309     }
310 
311     /**
312      * Sets the terrible failure handler, for testing.
313      *
314      * @return the old handler
315      *
316      * @hide
317      */
setWtfHandler(TerribleFailureHandler handler)318     public static TerribleFailureHandler setWtfHandler(TerribleFailureHandler handler) {
319         if (handler == null) {
320             throw new NullPointerException("handler == null");
321         }
322         TerribleFailureHandler oldHandler = sWtfHandler;
323         sWtfHandler = handler;
324         return oldHandler;
325     }
326 
327     /**
328      * Handy function to get a loggable stack trace from a Throwable
329      * @param tr An exception to log
330      */
getStackTraceString(Throwable tr)331     public static String getStackTraceString(Throwable tr) {
332         if (tr == null) {
333             return "";
334         }
335 
336         // This is to reduce the amount of log spew that apps do in the non-error
337         // condition of the network being unavailable.
338         Throwable t = tr;
339         while (t != null) {
340             if (t instanceof UnknownHostException) {
341                 return "";
342             }
343             t = t.getCause();
344         }
345 
346         StringWriter sw = new StringWriter();
347         PrintWriter pw = new FastPrintWriter(sw, false, 256);
348         tr.printStackTrace(pw);
349         pw.flush();
350         return sw.toString();
351     }
352 
353     /**
354      * Low-level logging call.
355      * @param priority The priority/type of this log message
356      * @param tag Used to identify the source of a log message.  It usually identifies
357      *        the class or activity where the log call occurs.
358      * @param msg The message you would like logged.
359      * @return The number of bytes written.
360      */
println(int priority, String tag, String msg)361     public static int println(int priority, String tag, String msg) {
362         return println_native(LOG_ID_MAIN, priority, tag, msg);
363     }
364 
365     /** @hide */ public static final int LOG_ID_MAIN = 0;
366     /** @hide */ public static final int LOG_ID_RADIO = 1;
367     /** @hide */ public static final int LOG_ID_EVENTS = 2;
368     /** @hide */ public static final int LOG_ID_SYSTEM = 3;
369     /** @hide */ public static final int LOG_ID_CRASH = 4;
370 
println_native(int bufID, int priority, String tag, String msg)371     /** @hide */ public static native int println_native(int bufID,
372             int priority, String tag, String msg);
373 
374     /**
375      * Return the maximum payload the log daemon accepts without truncation.
376      * @return LOGGER_ENTRY_MAX_PAYLOAD.
377      */
logger_entry_max_payload_native()378     private static native int logger_entry_max_payload_native();
379 
380     /**
381      * Helper function for long messages. Uses the LineBreakBufferedWriter to break
382      * up long messages and stacktraces along newlines, but tries to write in large
383      * chunks. This is to avoid truncation.
384      * @hide
385      */
printlns(int bufID, int priority, String tag, String msg, Throwable tr)386     public static int printlns(int bufID, int priority, String tag, String msg,
387             Throwable tr) {
388         ImmediateLogWriter logWriter = new ImmediateLogWriter(bufID, priority, tag);
389         // Acceptable buffer size. Get the native buffer size, subtract two zero terminators,
390         // and the length of the tag.
391         // Note: we implicitly accept possible truncation for Modified-UTF8 differences. It
392         //       is too expensive to compute that ahead of time.
393         int bufferSize = NoPreloadHolder.LOGGER_ENTRY_MAX_PAYLOAD  // Base.
394                 - 2                                                // Two terminators.
395                 - (tag != null ? tag.length() : 0)                 // Tag length.
396                 - 32;                                              // Some slack.
397         // At least assume you can print *some* characters (tag is not too large).
398         bufferSize = Math.max(bufferSize, 100);
399 
400         LineBreakBufferedWriter lbbw = new LineBreakBufferedWriter(logWriter, bufferSize);
401 
402         lbbw.println(msg);
403 
404         if (tr != null) {
405             // This is to reduce the amount of log spew that apps do in the non-error
406             // condition of the network being unavailable.
407             Throwable t = tr;
408             while (t != null) {
409                 if (t instanceof UnknownHostException) {
410                     break;
411                 }
412                 if (t instanceof DeadSystemException) {
413                     lbbw.println("DeadSystemException: The system died; "
414                             + "earlier logs will point to the root cause");
415                     break;
416                 }
417                 t = t.getCause();
418             }
419             if (t == null) {
420                 tr.printStackTrace(lbbw);
421             }
422         }
423 
424         lbbw.flush();
425 
426         return logWriter.getWritten();
427     }
428 
429     /**
430      * NoPreloadHelper class. Caches the LOGGER_ENTRY_MAX_PAYLOAD value to avoid
431      * a JNI call during logging.
432      */
433     static class NoPreloadHolder {
434         public final static int LOGGER_ENTRY_MAX_PAYLOAD =
435                 logger_entry_max_payload_native();
436     }
437 
438     /**
439      * Helper class to write to the logcat. Different from LogWriter, this writes
440      * the whole given buffer and does not break along newlines.
441      */
442     private static class ImmediateLogWriter extends Writer {
443 
444         private int bufID;
445         private int priority;
446         private String tag;
447 
448         private int written = 0;
449 
450         /**
451          * Create a writer that immediately writes to the log, using the given
452          * parameters.
453          */
ImmediateLogWriter(int bufID, int priority, String tag)454         public ImmediateLogWriter(int bufID, int priority, String tag) {
455             this.bufID = bufID;
456             this.priority = priority;
457             this.tag = tag;
458         }
459 
getWritten()460         public int getWritten() {
461             return written;
462         }
463 
464         @Override
write(char[] cbuf, int off, int len)465         public void write(char[] cbuf, int off, int len) {
466             // Note: using String here has a bit of overhead as a Java object is created,
467             //       but using the char[] directly is not easier, as it needs to be translated
468             //       to a C char[] for logging.
469             written += println_native(bufID, priority, tag, new String(cbuf, off, len));
470         }
471 
472         @Override
flush()473         public void flush() {
474             // Ignored.
475         }
476 
477         @Override
close()478         public void close() {
479             // Ignored.
480         }
481     }
482 }
483