Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 日誌工具 Log 五個方法完整說明

編輯:Android 開發教學

android.util.Log 是每個 Android 開發者最早認識、也最常用的除錯夥伴。它一共提供五個靜態方法:Log.v()、Log.d()、Log.i()、Log.w() 與 Log.e(),五個字母分別對應 VERBOSE、DEBUG、INFO、WARN、ERROR 五個層級。

五個層級的差異

Log.v:最囉嗦的一級,任何訊息都會被印出,顏色顯示為黑色。日常寫法就是 Log.v("標籤", "內容")。

Log.d:藍色輸出,專門用來印除錯資訊。由於它涵蓋範圍廣,實務上多半靠 DDMS 的 Logcat 分頁或過濾器來篩選。

Log.i:綠色輸出,代表一般性的提示訊息。它不會顯示 v 與 d 的內容,但會顯示 i、w、e 三級。

Log.w:橙色輸出,代表警告。看到它通常意味著程式碼有值得優化的地方,同時它也會把 e 級訊息一起帶出來。

Log.e:紅色輸出,代表錯誤。這一級只顯示錯誤本身,需要認真對照堆疊追蹤才能定位問題。

動手做一個 LogDemo

Step 1:打開 LogCat 視窗。在 Eclipse 中開啟 Window 選單、選擇 Show View,於對話框中確認後,控制台區域就會出現 LogCat 分頁。

Step 2:建立一個名為 LogDemo 的 Android 專案。

Step 3:設計版面。這裡只放一顆按鈕,按下後輸出一段日誌,用來觀察不同層級的顯示效果。

main.xml 的內容如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello"
    />
<Button
 android:id="@+id/bt"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:text="Presse Me Look Log"
/>
</LinearLayout>

完成按鈕的事件綁定後,在其中依序呼叫五個層級的輸出,再回到 LogCat 切換不同層級觀察顏色與內容的變化,就能很直觀地掌握各方法的定位。實務建議是:正式環境中把 v 與 d 的輸出關閉,僅保留 i 以上層級,避免無謂的效能損耗與資訊外洩。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved