2011-10-30 70 views
11

當我爲Android應用程序編寫日誌包裝器時,我注意到了Android Log.isLoggable方法的奇怪行爲。執行下面的代碼:Log.isLoggable是否返回錯誤的值?

final String TAG = "Test"; 
Log.v(TAG, "verbose is active: " + Log.isLoggable(TAG, Log.VERBOSE)); 
Log.d(TAG, "debug is active: " + Log.isLoggable(TAG, Log.DEBUG)); 
Log.i(TAG, "info is active: " + Log.isLoggable(TAG, Log.INFO)); 
Log.w(TAG, "warn is active: " + Log.isLoggable(TAG, Log.WARN)); 
Log.e(TAG, "error is active: " + Log.isLoggable(TAG, Log.ERROR)); 

產生以下的logcat輸出:

VERBOSE/Test(598): verbose is active: false 
DEBUG/Test(598): debug is active: false 
INFO/Test(598): info is active: true 
WARN/Test(598): warn is active: true 
ERROR/Test(598): error is active: true 

爲什麼我得到詳細和調試不活躍,雖然我產生使用詳細和調試日誌記錄這些輸出?

回答

6

無論當前日誌級別是什麼,所有日誌級別都寫入logcat。 isLogabble()方法可用作應用程序的優化,以防止將不需要的日誌語句發送到logcat。即使日誌記錄設置爲詳細(請參閱https://developer.android.com/studio/debug/am-logcat.html),也可以使用adb logcat命令過濾日誌記錄級別的子集。

+0

斷開的鏈接,請更新。 –

2

您應該使用

if (Log.isLoggable(TAG, Log.VERBOSE)) { 
    Log.v(TAG, "verbose is active: " + Log.isLoggable(TAG, Log.VERBOSE)); 
} 
12

如果你讀Log.isLoggable()的信息,你會發現默認的日誌記錄級別是INFO。小於此值(DEBUGVERBOSE)將導致此方法返回false。這就是爲什麼你的結果輸出顯示這兩個爲false

所有Log.*調用都記錄到logcat。調用Log.isLoggable()只是一種調整日誌記錄的方法。這不是必需的。通常情況下,您會在實際撥打Log.*之前致電Log.isLoggable()以確定是否記錄。

如果您選擇使用prop文件或adb,您可以根據TAG調整日誌記錄。關於這一點的好處是,您可以動態地在您的應用程序中爲每個人TAG啓用/關閉/關閉日誌記錄,而無需手動註釋日誌行或實施自己的檢查。

0

無論Log.isloggable()返回什麼,LOG都將始終打印在logcat中。