diff --git a/k9mail/build.gradle b/k9mail/build.gradle index f7fb3c39d..474b76102 100644 --- a/k9mail/build.gradle +++ b/k9mail/build.gradle @@ -34,6 +34,7 @@ dependencies { compile 'de.cketti.safecontentresolver:safe-content-resolver-v14:0.9.0' compile 'com.github.amlcurran.showcaseview:library:5.4.1' compile 'com.squareup.moshi:moshi:1.2.0' + compile 'com.jakewharton.timber:timber:4.5.1' androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.2' diff --git a/k9mail/src/main/java/com/fsck/k9/Account.java b/k9mail/src/main/java/com/fsck/k9/Account.java index 3ac2916db..07cd50b3b 100644 --- a/k9mail/src/main/java/com/fsck/k9/Account.java +++ b/k9mail/src/main/java/com/fsck/k9/Account.java @@ -19,7 +19,7 @@ import android.content.Context; import android.database.Cursor; import android.graphics.Color; import android.net.Uri; -import android.util.Log; +import timber.log.Timber; import com.fsck.k9.activity.setup.AccountSetupCheckSettings.CheckDirection; import com.fsck.k9.helper.Utility; @@ -760,7 +760,7 @@ public class Account implements BaseAccount, StoreConfig { try { getLocalStore().resetVisibleLimits(getDisplayCount()); } catch (MessagingException e) { - Log.e(K9.LOG_TAG, "Unable to reset visible limits", e); + Timber.e(e, "Unable to reset visible limits"); } } @@ -953,8 +953,7 @@ public class Account implements BaseAccount, StoreConfig { switchLocalStorage(id); successful = true; } catch (MessagingException e) { - Log.e(K9.LOG_TAG, "Switching local storage provider from " + - mLocalStorageProviderId + " to " + id + " failed.", e); + Timber.e(e, "Switching local storage provider from %s to %s failed.", mLocalStorageProviderId, id); } // if migration to/from SD-card failed once, it will fail again. diff --git a/k9mail/src/main/java/com/fsck/k9/K9.java b/k9mail/src/main/java/com/fsck/k9/K9.java index 0815a2dde..d2288cfe7 100644 --- a/k9mail/src/main/java/com/fsck/k9/K9.java +++ b/k9mail/src/main/java/com/fsck/k9/K9.java @@ -24,7 +24,6 @@ import android.os.Handler; import android.os.Looper; import android.os.StrictMode; import android.text.format.Time; -import android.util.Log; import com.fsck.k9.Account.SortType; import com.fsck.k9.activity.MessageCompose; @@ -45,6 +44,9 @@ import com.fsck.k9.service.MailService; import com.fsck.k9.service.ShutdownReceiver; import com.fsck.k9.service.StorageGoneReceiver; import com.fsck.k9.widget.list.MessageListWidgetProvider; +import timber.log.Timber; +import timber.log.Timber.DebugTree; + public class K9 extends Application { /** @@ -135,7 +137,7 @@ public class K9 extends Application { * Log.d, including protocol dumps. * Controlled by Preferences at run-time */ - public static boolean DEBUG = false; + private static boolean DEBUG = false; /** * If this is enabled than logging that normally hides sensitive information @@ -416,7 +418,7 @@ public class K9 extends Application { try { queue.put(new Handler()); } catch (InterruptedException e) { - Log.e(K9.LOG_TAG, "", e); + Timber.e(e); } Looper.loop(); } @@ -426,13 +428,13 @@ public class K9 extends Application { try { final Handler storageGoneHandler = queue.take(); registerReceiver(receiver, filter, null, storageGoneHandler); - Log.i(K9.LOG_TAG, "Registered: unmount receiver"); + Timber.i("Registered: unmount receiver"); } catch (InterruptedException e) { - Log.e(K9.LOG_TAG, "Unable to register unmount receiver", e); + Timber.e(e, "Unable to register unmount receiver"); } registerReceiver(new ShutdownReceiver(), new IntentFilter(Intent.ACTION_SHUTDOWN)); - Log.i(K9.LOG_TAG, "Registered: shutdown receiver"); + Timber.i("Registered: shutdown receiver"); } public static void save(StorageEditor editor) { @@ -565,21 +567,19 @@ public class K9 extends Application { intent.putExtra(K9.Intents.EmailReceived.EXTRA_SUBJECT, message.getSubject()); intent.putExtra(K9.Intents.EmailReceived.EXTRA_FROM_SELF, account.isAnIdentity(message.getFrom())); K9.this.sendBroadcast(intent); - if (K9.DEBUG) - Log.d(K9.LOG_TAG, "Broadcasted: action=" + action - + " account=" + account.getDescription() - + " folder=" + folder - + " message uid=" + message.getUid() - ); + + Timber.d("Broadcasted: action=%s account=%s folder=%s message uid=%s", + action, + account.getDescription(), + folder, + message.getUid()); } private void updateUnreadWidget() { try { UnreadWidgetProvider.updateUnreadCount(K9.this); } catch (Exception e) { - if (K9.DEBUG) { - Log.e(LOG_TAG, "Error while updating unread widget(s)", e); - } + Timber.e(e, "Error while updating unread widget(s)"); } } @@ -589,8 +589,8 @@ public class K9 extends Application { } catch (RuntimeException e) { if (BuildConfig.DEBUG) { throw e; - } else if (K9.DEBUG) { - Log.e(LOG_TAG, "Error while updating message list widget", e); + } else { + Timber.e(e, "Error while updating message list widget"); } } } @@ -671,7 +671,7 @@ public class K9 extends Application { */ public static void loadPrefs(Preferences prefs) { Storage storage = prefs.getStorage(); - DEBUG = storage.getBoolean("enableDebugLogging", BuildConfig.DEVELOPER_MODE); + setDebug(storage.getBoolean("enableDebugLogging", BuildConfig.DEVELOPER_MODE)); DEBUG_SENSITIVE = storage.getBoolean("enableSensitiveLogging", false); mAnimations = storage.getBoolean("animations", true); mGesturesEnabled = storage.getBoolean("gesturesEnabled", false); @@ -799,13 +799,12 @@ public class K9 extends Application { protected void notifyObservers() { synchronized (observers) { for (final ApplicationAware aware : observers) { - if (K9.DEBUG) { - Log.v(K9.LOG_TAG, "Initializing observer: " + aware); - } + Timber.v("Initializing observer: %s", aware); + try { aware.initializeComponent(this); } catch (Exception e) { - Log.w(K9.LOG_TAG, "Failure when notifying " + aware, e); + Timber.w(e, "Failure when notifying %s", aware); } } @@ -1017,7 +1016,14 @@ public class K9 extends Application { return false; } + public static void setDebug(boolean debug) { + K9.DEBUG = debug; + updateLoggingStatus(); + } + public static boolean isDebug() { + return DEBUG; + } public static boolean startIntegratedInbox() { return mStartIntegratedInbox; @@ -1419,4 +1425,13 @@ public class K9 extends Application { editor.commit(); } } + + private static void updateLoggingStatus() { + Timber.uprootAll(); + boolean enableDebugLogging = BuildConfig.DEBUG || DEBUG; + if (enableDebugLogging) { + Timber.plant(new DebugTree()); + } + } + } diff --git a/k9mail/src/main/java/com/fsck/k9/Preferences.java b/k9mail/src/main/java/com/fsck/k9/Preferences.java index fae65309d..57a4bb229 100644 --- a/k9mail/src/main/java/com/fsck/k9/Preferences.java +++ b/k9mail/src/main/java/com/fsck/k9/Preferences.java @@ -10,13 +10,14 @@ import java.util.List; import java.util.Map; import android.content.Context; -import android.util.Log; +import timber.log.Timber; import com.fsck.k9.mail.store.RemoteStore; import com.fsck.k9.mailstore.LocalStore; import com.fsck.k9.preferences.StorageEditor; import com.fsck.k9.preferences.Storage; + public class Preferences { private static Preferences preferences; @@ -40,7 +41,7 @@ public class Preferences { mStorage = Storage.getStorage(context); mContext = context; if (mStorage.isEmpty()) { - Log.i(K9.LOG_TAG, "Preferences storage is zero-size, importing from Android-style preferences"); + Timber.i("Preferences storage is zero-size, importing from Android-style preferences"); StorageEditor editor = mStorage.edit(); editor.copy(context.getSharedPreferences("AndroidMail.Main", Context.MODE_PRIVATE)); editor.commit(); @@ -128,7 +129,7 @@ public class Preferences { try { RemoteStore.removeInstance(account); } catch (Exception e) { - Log.e(K9.LOG_TAG, "Failed to reset remote store for account " + account.getUuid(), e); + Timber.e(e, "Failed to reset remote store for account %s", account.getUuid()); } LocalStore.removeAccount(account); @@ -176,8 +177,8 @@ public class Preferences { try { return Enum.valueOf(defaultEnum.getDeclaringClass(), stringPref); } catch (IllegalArgumentException ex) { - Log.w(K9.LOG_TAG, "Unable to convert preference key [" + key + - "] value [" + stringPref + "] to enum of type " + defaultEnum.getDeclaringClass(), ex); + Timber.w(ex, "Unable to convert preference key [%s] value [%s] to enum of type %s", + key, stringPref, defaultEnum.getDeclaringClass()); return defaultEnum; } diff --git a/k9mail/src/main/java/com/fsck/k9/Throttle.java b/k9mail/src/main/java/com/fsck/k9/Throttle.java index 6e6b2dcad..d18d57fb9 100644 --- a/k9mail/src/main/java/com/fsck/k9/Throttle.java +++ b/k9mail/src/main/java/com/fsck/k9/Throttle.java @@ -16,12 +16,15 @@ package com.fsck.k9; -import android.os.Handler; -import android.util.Log; import java.util.Timer; import java.util.TimerTask; +import android.os.Handler; + +import timber.log.Timber; + + /** * This class used to "throttle" a flow of events. * @@ -94,7 +97,7 @@ public class Throttle { } private void debugLog(String message) { - Log.d(K9.LOG_TAG, "Throttle: [" + mName + "] " + message); + Timber.d("Throttle: [%s] %s", mName, message); } private boolean isCallbackScheduled() { diff --git a/k9mail/src/main/java/com/fsck/k9/activity/Accounts.java b/k9mail/src/main/java/com/fsck/k9/activity/Accounts.java index 2734172f1..74765fd86 100644 --- a/k9mail/src/main/java/com/fsck/k9/activity/Accounts.java +++ b/k9mail/src/main/java/com/fsck/k9/activity/Accounts.java @@ -33,7 +33,7 @@ import android.os.Bundle; import android.os.Handler; import android.text.Editable; import android.text.TextWatcher; -import android.util.Log; +import timber.log.Timber; import android.util.SparseBooleanArray; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; @@ -256,12 +256,12 @@ public class Accounts extends K9ListActivity implements OnItemClickListener { try { AccountStats stats = account.getStats(Accounts.this); if (stats == null) { - Log.w(K9.LOG_TAG, "Unable to get account stats"); + Timber.w("Unable to get account stats"); } else { accountStatusChanged(account, stats); } } catch (Exception e) { - Log.e(K9.LOG_TAG, "Unable to get account stats", e); + Timber.e(e, "Unable to get account stats"); } } @Override @@ -652,7 +652,7 @@ public class Accounts extends K9ListActivity implements OnItemClickListener { Toast toast = Toast.makeText(getApplication(), toastText, Toast.LENGTH_SHORT); toast.show(); - Log.i(K9.LOG_TAG, "refusing to open account that is not available"); + Timber.i("refusing to open account that is not available"); return false; } if (K9.FOLDER_NONE.equals(realAccount.getAutoExpandFolderName())) { @@ -995,7 +995,7 @@ public class Accounts extends K9ListActivity implements OnItemClickListener { // Get list of folders from remote server MessagingController.getInstance(mApplication).listFolders(mAccount, true, null); } catch (Exception e) { - Log.e(K9.LOG_TAG, "Something went while setting account passwords", e); + Timber.e(e, "Something went while setting account passwords"); } return null; } @@ -1411,7 +1411,7 @@ public class Accounts extends K9ListActivity implements OnItemClickListener { @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { - Log.i(K9.LOG_TAG, "onActivityResult requestCode = " + requestCode + ", resultCode = " + resultCode + ", data = " + data); + Timber.i("onActivityResult requestCode = %d, resultCode = %s, data = %s", requestCode, resultCode, data); if (resultCode != RESULT_OK) return; if (data == null) { @@ -1926,7 +1926,7 @@ public class Accounts extends K9ListActivity implements OnItemClickListener { mFileName = SettingsExporter.exportToFile(mContext, mIncludeGlobals, mAccountUuids); } catch (SettingsImportExportException e) { - Log.w(K9.LOG_TAG, "Exception during export", e); + Timber.w(e, "Exception during export"); return false; } return true; @@ -1993,13 +1993,13 @@ public class Accounts extends K9ListActivity implements OnItemClickListener { } } } catch (SettingsImportExportException e) { - Log.w(K9.LOG_TAG, "Exception during import", e); + Timber.w(e, "Exception during import"); return false; } catch (FileNotFoundException e) { - Log.w(K9.LOG_TAG, "Couldn't open import file", e); + Timber.w(e, "Couldn't open import file"); return false; } catch (Exception e) { - Log.w(K9.LOG_TAG, "Unknown error", e); + Timber.w(e, "Unknown error"); return false; } return true; @@ -2066,10 +2066,10 @@ public class Accounts extends K9ListActivity implements OnItemClickListener { } } } catch (SettingsImportExportException e) { - Log.w(K9.LOG_TAG, "Exception during export", e); + Timber.w(e, "Exception during export"); return false; } catch (FileNotFoundException e) { - Log.w(K9.LOG_TAG, "Couldn't read content from URI " + mUri); + Timber.w("Couldn't read content from URI %s", mUri); return false; } return true; diff --git a/k9mail/src/main/java/com/fsck/k9/activity/ActivityListener.java b/k9mail/src/main/java/com/fsck/k9/activity/ActivityListener.java index 1dfc9b0ca..1d494bc8d 100644 --- a/k9mail/src/main/java/com/fsck/k9/activity/ActivityListener.java +++ b/k9mail/src/main/java/com/fsck/k9/activity/ActivityListener.java @@ -45,7 +45,7 @@ public class ActivityListener extends SimpleMessagingListener { return context.getString(R.string.status_next_poll, DateUtils.getRelativeTimeSpanString(nextPollTime, System.currentTimeMillis(), DateUtils.MINUTE_IN_MILLIS, 0)); - } else if (K9.DEBUG && MailService.isSyncDisabled()) { + } else if (K9.isDebug() && MailService.isSyncDisabled()) { if (MailService.hasNoConnectivity()) { return context.getString(R.string.status_no_network); } else if (MailService.isSyncNoBackground()) { diff --git a/k9mail/src/main/java/com/fsck/k9/activity/FolderList.java b/k9mail/src/main/java/com/fsck/k9/activity/FolderList.java index 0a374dd62..13bf372b6 100644 --- a/k9mail/src/main/java/com/fsck/k9/activity/FolderList.java +++ b/k9mail/src/main/java/com/fsck/k9/activity/FolderList.java @@ -15,7 +15,7 @@ import android.os.Handler; import android.os.PowerManager; import android.text.TextUtils.TruncateAt; import android.text.format.DateUtils; -import android.util.Log; +import timber.log.Timber; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.KeyEvent; @@ -379,7 +379,7 @@ public class FolderList extends K9ListActivity { super.onResume(); if (!mAccount.isAvailable(this)) { - Log.i(K9.LOG_TAG, "account unavaliabale, not showing folder-list but account-list"); + Timber.i("account unavaliabale, not showing folder-list but account-list"); Accounts.listAccounts(this); finish(); return; @@ -800,7 +800,7 @@ public class FolderList extends K9ListActivity { try { if (account != null && folderName != null) { if (!account.isAvailable(FolderList.this)) { - Log.i(K9.LOG_TAG, "not refreshing folder of unavailable account"); + Timber.i("not refreshing folder of unavailable account"); return; } localFolder = account.getLocalStore().getFolder(folderName); @@ -813,7 +813,7 @@ public class FolderList extends K9ListActivity { } } } catch (Exception e) { - Log.e(K9.LOG_TAG, "Exception while populating folder", e); + Timber.e(e, "Exception while populating folder"); } finally { if (localFolder != null) { localFolder.close(); @@ -939,8 +939,7 @@ public class FolderList extends K9ListActivity { if (position <= getCount()) { return getItemView(position, convertView, parent); } else { - Log.e(K9.LOG_TAG, "getView with illegal positon=" + position - + " called! count is only " + getCount()); + Timber.e("getView with illegal position=%d called! count is only %d", position, getCount()); return null; } } @@ -1019,8 +1018,7 @@ public class FolderList extends K9ListActivity { try { folder.unreadMessageCount = folder.folder.getUnreadMessageCount(); } catch (Exception e) { - Log.e(K9.LOG_TAG, "Unable to get unreadMessageCount for " + mAccount.getDescription() + ":" - + folder.name); + Timber.e("Unable to get unreadMessageCount for %s:%s", mAccount.getDescription(), folder.name); } } if (folder.unreadMessageCount > 0) { @@ -1039,11 +1037,9 @@ public class FolderList extends K9ListActivity { try { folder.flaggedMessageCount = folder.folder.getFlaggedMessageCount(); } catch (Exception e) { - Log.e(K9.LOG_TAG, "Unable to get flaggedMessageCount for " + mAccount.getDescription() + ":" - + folder.name); + Timber.e("Unable to get flaggedMessageCount for %s:%s", mAccount.getDescription(), folder.name); } - - } + } if (K9.messageListStars() && folder.flaggedMessageCount > 0) { holder.flaggedMessageCount.setText(String.format("%d", folder.flaggedMessageCount)); diff --git a/k9mail/src/main/java/com/fsck/k9/activity/FolderListFilter.java b/k9mail/src/main/java/com/fsck/k9/activity/FolderListFilter.java index 9941a72c2..5314532bb 100644 --- a/k9mail/src/main/java/com/fsck/k9/activity/FolderListFilter.java +++ b/k9mail/src/main/java/com/fsck/k9/activity/FolderListFilter.java @@ -4,7 +4,7 @@ import java.util.ArrayList; import java.util.List; import java.util.Locale; -import android.util.Log; +import timber.log.Timber; import android.widget.ArrayAdapter; import android.widget.Filter; @@ -113,7 +113,7 @@ public class FolderListFilter extends Filter { } } } else { - Log.w(K9.LOG_TAG, "FolderListFilter.publishResults - null search-result "); + Timber.w("FolderListFilter.publishResults - null search-result "); } // Send notification that the data set changed now diff --git a/k9mail/src/main/java/com/fsck/k9/activity/MessageCompose.java b/k9mail/src/main/java/com/fsck/k9/activity/MessageCompose.java index 4ccbb28e9..7e26c99ea 100644 --- a/k9mail/src/main/java/com/fsck/k9/activity/MessageCompose.java +++ b/k9mail/src/main/java/com/fsck/k9/activity/MessageCompose.java @@ -28,7 +28,7 @@ import android.support.annotation.Nullable; import android.support.annotation.StringRes; import android.text.TextUtils; import android.text.TextWatcher; -import android.util.Log; +import timber.log.Timber; import android.util.TypedValue; import android.view.ContextThemeWrapper; import android.view.LayoutInflater; @@ -345,7 +345,7 @@ public class MessageCompose extends K9Activity implements OnClickListener, this.action = Action.EDIT_DRAFT; } else { // This shouldn't happen - Log.w(K9.LOG_TAG, "MessageCompose was started with an unsupported action"); + Timber.w("MessageCompose was started with an unsupported action"); this.action = Action.COMPOSE; } } @@ -764,7 +764,7 @@ public class MessageCompose extends K9Activity implements OnClickListener, if ((requestCode & REQUEST_MASK_MESSAGE_BUILDER) == REQUEST_MASK_MESSAGE_BUILDER) { requestCode ^= REQUEST_MASK_MESSAGE_BUILDER; if (currentMessageBuilder == null) { - Log.e(K9.LOG_TAG, "Got a message builder activity result for no message builder, " + + Timber.e("Got a message builder activity result for no message builder, " + "this is an illegal state!"); return; } @@ -792,9 +792,7 @@ public class MessageCompose extends K9Activity implements OnClickListener, private void onAccountChosen(Account account, Identity identity) { if (!this.account.equals(account)) { - if (K9.DEBUG) { - Log.v(K9.LOG_TAG, "Switching account from " + this.account + " to " + account); - } + Timber.v("Switching account from %s to %s", this.account, account); // on draft edit, make sure we don't keep previous message UID if (action == Action.EDIT_DRAFT) { @@ -812,15 +810,12 @@ public class MessageCompose extends K9Activity implements OnClickListener, // actual account switch this.account = account; - if (K9.DEBUG) { - Log.v(K9.LOG_TAG, "Account switch, saving new draft in new account"); - } + Timber.v("Account switch, saving new draft in new account"); checkToSaveDraftImplicitly(); if (previousDraftId != INVALID_DRAFT_ID) { - if (K9.DEBUG) { - Log.v(K9.LOG_TAG, "Account switch, deleting draft from previous account: " + previousDraftId); - } + Timber.v("Account switch, deleting draft from previous account: %d", previousDraftId); + MessagingController.getInstance(getApplication()).deleteDraft(previousAccount, previousDraftId); } @@ -1148,7 +1143,7 @@ public class MessageCompose extends K9Activity implements OnClickListener, break; } default: { - Log.w(K9.LOG_TAG, "processSourceMessage() called with unsupported action"); + Timber.w("processSourceMessage() called with unsupported action"); break; } } @@ -1157,7 +1152,7 @@ public class MessageCompose extends K9Activity implements OnClickListener, * Let the user continue composing their message even if we have a problem processing * the source message. Log it as an error, though. */ - Log.e(K9.LOG_TAG, "Error while processing source message: ", me); + Timber.e(me, "Error while processing source message: "); } finally { relatedMessageProcessed = true; changesMadeSinceLastSave = false; @@ -1199,9 +1194,7 @@ public class MessageCompose extends K9Activity implements OnClickListener, } } else { - if (K9.DEBUG) { - Log.d(K9.LOG_TAG, "could not get Message-ID."); - } + Timber.d("could not get Message-ID."); } // Quote the message and setup the UI. @@ -1235,9 +1228,7 @@ public class MessageCompose extends K9Activity implements OnClickListener, repliedToMessageId = message.getMessageId(); referencedMessageIds = repliedToMessageId; } else { - if (K9.DEBUG) { - Log.d(K9.LOG_TAG, "could not get Message-ID."); - } + Timber.d("could not get Message-ID."); } // Quote the message and setup the UI. @@ -1352,7 +1343,7 @@ public class MessageCompose extends K9Activity implements OnClickListener, contacts.markAsContacted(message.getRecipients(RecipientType.BCC)); updateReferencedMessage(); } catch (Exception e) { - Log.e(K9.LOG_TAG, "Failed to mark contact as contacted.", e); + Timber.e(e, "Failed to mark contact as contacted."); } MessagingController.getInstance(context).sendMessage(account, message, null); @@ -1369,12 +1360,11 @@ public class MessageCompose extends K9Activity implements OnClickListener, **/ private void updateReferencedMessage() { if (messageReference != null && messageReference.getFlag() != null) { - if (K9.DEBUG) { - Log.d(K9.LOG_TAG, "Setting referenced message (" + - messageReference.getFolderName() + ", " + - messageReference.getUid() + ") flag to " + - messageReference.getFlag()); - } + Timber.d("Setting referenced message (%s, %s) flag to %s", + messageReference.getFolderName(), + messageReference.getUid(), + messageReference.getFlag()); + final Account account = Preferences.getPreferences(context) .getAccount(messageReference.getAccountUuid()); final String folderName = messageReference.getFolderName(); @@ -1481,7 +1471,7 @@ public class MessageCompose extends K9Activity implements OnClickListener, @Override public void onMessageBuildException(MessagingException me) { - Log.e(K9.LOG_TAG, "Error sending message", me); + Timber.e(me, "Error sending message"); Toast.makeText(MessageCompose.this, getString(R.string.send_failed_reason, me.getLocalizedMessage()), Toast.LENGTH_LONG).show(); currentMessageBuilder = null; @@ -1494,7 +1484,7 @@ public class MessageCompose extends K9Activity implements OnClickListener, try { startIntentSenderForResult(pendingIntent.getIntentSender(), requestCode, null, 0, 0, 0); } catch (SendIntentException e) { - Log.e(K9.LOG_TAG, "Error starting pending intent from builder!", e); + Timber.e(e, "Error starting pending intent from builder!"); } } @@ -1518,7 +1508,7 @@ public class MessageCompose extends K9Activity implements OnClickListener, } catch (MessagingException e) { // Hm, if we couldn't populate the UI after source reprocessing, let's just delete it? quotedMessagePresenter.showOrHideQuotedText(QuotedTextMode.HIDE); - Log.e(K9.LOG_TAG, "Could not re-process source message; deleting quoted text to be safe.", e); + Timber.e(e, "Could not re-process source message; deleting quoted text to be safe."); } updateMessageFormat(); } else { @@ -1563,7 +1553,7 @@ public class MessageCompose extends K9Activity implements OnClickListener, requestCode |= REQUEST_MASK_LOADER_HELPER; startIntentSenderForResult(si, requestCode, fillIntent, flagsMask, flagValues, extraFlags); } catch (SendIntentException e) { - Log.e(K9.LOG_TAG, "Irrecoverable error calling PendingIntent!", e); + Timber.e(e, "Irrecoverable error calling PendingIntent!"); } } diff --git a/k9mail/src/main/java/com/fsck/k9/activity/MessageList.java b/k9mail/src/main/java/com/fsck/k9/activity/MessageList.java index 0eeb95d57..f1addf57f 100644 --- a/k9mail/src/main/java/com/fsck/k9/activity/MessageList.java +++ b/k9mail/src/main/java/com/fsck/k9/activity/MessageList.java @@ -19,7 +19,7 @@ import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Parcelable; -import android.util.Log; +import timber.log.Timber; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; @@ -479,7 +479,7 @@ public class MessageList extends K9Activity implements MessageListFragmentListen mSingleFolderMode = mSingleAccountMode && (mSearch.getFolderNames().size() == 1); if (mSingleAccountMode && (mAccount == null || !mAccount.isAvailable(this))) { - Log.i(K9.LOG_TAG, "not opening MessageList of unavailable account"); + Timber.i("not opening MessageList of unavailable account"); onAccountUnavailable(); return false; } @@ -757,8 +757,7 @@ public class MessageList extends K9Activity implements MessageListFragmentListen // Swallow these events too to avoid the audible notification of a volume change if (K9.useVolumeKeysForListNavigationEnabled()) { if ((keyCode == KeyEvent.KEYCODE_VOLUME_UP) || (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)) { - if (K9.DEBUG) - Log.v(K9.LOG_TAG, "Swallowed key up."); + Timber.v("Swallowed key up."); return true; } } diff --git a/k9mail/src/main/java/com/fsck/k9/activity/MessageLoaderHelper.java b/k9mail/src/main/java/com/fsck/k9/activity/MessageLoaderHelper.java index 412c4d7e4..4b02b3e15 100644 --- a/k9mail/src/main/java/com/fsck/k9/activity/MessageLoaderHelper.java +++ b/k9mail/src/main/java/com/fsck/k9/activity/MessageLoaderHelper.java @@ -13,7 +13,7 @@ import android.os.Parcelable; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.annotation.UiThread; -import android.util.Log; +import timber.log.Timber; import com.fsck.k9.Account; import com.fsck.k9.K9; @@ -111,7 +111,7 @@ public class MessageLoaderHelper { if (cachedDecryptionResult instanceof OpenPgpDecryptionResult) { this.cachedDecryptionResult = (OpenPgpDecryptionResult) cachedDecryptionResult; } else { - Log.e(K9.LOG_TAG, "Got decryption result of unknown type - ignoring"); + Timber.e("Got decryption result of unknown type - ignoring"); } } @@ -182,12 +182,12 @@ public class MessageLoaderHelper { boolean isLoaderStale = (loader == null) || !loader.isCreatedFor(messageReference); if (isLoaderStale) { - Log.d(K9.LOG_TAG, "Creating new local message loader"); + Timber.d("Creating new local message loader"); cancelAndClearCryptoOperation(); cancelAndClearDecodeLoader(); loaderManager.restartLoader(LOCAL_MESSAGE_LOADER_ID, null, localMessageLoaderCallback); } else { - Log.d(K9.LOG_TAG, "Reusing local message loader"); + Timber.d("Reusing local message loader"); loaderManager.initLoader(LOCAL_MESSAGE_LOADER_ID, null, localMessageLoaderCallback); } } @@ -336,10 +336,10 @@ public class MessageLoaderHelper { boolean isLoaderStale = (loader == null) || !loader.isCreatedFor(localMessage, messageCryptoAnnotations); if (isLoaderStale) { - Log.d(K9.LOG_TAG, "Creating new decode message loader"); + Timber.d("Creating new decode message loader"); loaderManager.restartLoader(DECODE_MESSAGE_LOADER_ID, null, decodeMessageLoaderCallback); } else { - Log.d(K9.LOG_TAG, "Reusing decode message loader"); + Timber.d("Reusing decode message loader"); loaderManager.initLoader(DECODE_MESSAGE_LOADER_ID, null, decodeMessageLoaderCallback); } } diff --git a/k9mail/src/main/java/com/fsck/k9/activity/MessageReferenceHelper.java b/k9mail/src/main/java/com/fsck/k9/activity/MessageReferenceHelper.java index eb0cd71ef..bfeac4af5 100644 --- a/k9mail/src/main/java/com/fsck/k9/activity/MessageReferenceHelper.java +++ b/k9mail/src/main/java/com/fsck/k9/activity/MessageReferenceHelper.java @@ -4,7 +4,7 @@ package com.fsck.k9.activity; import java.util.ArrayList; import java.util.List; -import android.util.Log; +import timber.log.Timber; import com.fsck.k9.K9; @@ -17,7 +17,7 @@ public class MessageReferenceHelper { if (messageReference != null) { messageReferences.add(messageReference); } else { - Log.w(K9.LOG_TAG, "Invalid message reference: " + messageReferenceString); + Timber.w("Invalid message reference: %s", messageReferenceString); } } diff --git a/k9mail/src/main/java/com/fsck/k9/activity/compose/RecipientPresenter.java b/k9mail/src/main/java/com/fsck/k9/activity/compose/RecipientPresenter.java index e18bc65cd..20d2539b9 100644 --- a/k9mail/src/main/java/com/fsck/k9/activity/compose/RecipientPresenter.java +++ b/k9mail/src/main/java/com/fsck/k9/activity/compose/RecipientPresenter.java @@ -17,7 +17,7 @@ import android.net.Uri; import android.os.Bundle; import android.support.annotation.VisibleForTesting; import android.text.TextUtils; -import android.util.Log; +import timber.log.Timber; import android.view.Menu; import com.fsck.k9.Account; @@ -548,7 +548,7 @@ public class RecipientPresenter implements PermissionPingCallback { void onClickCryptoStatus() { switch (cryptoProviderState) { case UNCONFIGURED: - Log.e(K9.LOG_TAG, "click on crypto status while unconfigured - this should not really happen?!"); + Timber.e("click on crypto status while unconfigured - this should not really happen?!"); return; case OK: if (cachedCryptoStatus.isSignOnly()) { @@ -678,7 +678,7 @@ public class RecipientPresenter implements PermissionPingCallback { // TODO handle error case better recipientMvpView.showErrorOpenPgpConnection(); cryptoProviderState = CryptoProviderState.ERROR; - Log.e(K9.LOG_TAG, "error connecting to crypto provider!", e); + Timber.e(e, "error connecting to crypto provider!"); updateCryptoStatus(); } @@ -714,7 +714,7 @@ public class RecipientPresenter implements PermissionPingCallback { private OpenPgpApi getOpenPgpApi() { if (openPgpServiceConnection == null || !openPgpServiceConnection.isBound()) { - Log.e(K9.LOG_TAG, "obtained openpgpapi object, but service is not bound! inconsistent state?"); + Timber.e("obtained openpgpapi object, but service is not bound! inconsistent state?"); } return new OpenPgpApi(context, openPgpServiceConnection.getService()); } diff --git a/k9mail/src/main/java/com/fsck/k9/activity/loader/AttachmentContentLoader.java b/k9mail/src/main/java/com/fsck/k9/activity/loader/AttachmentContentLoader.java index cf3c8ee0e..e7ffeb5f9 100644 --- a/k9mail/src/main/java/com/fsck/k9/activity/loader/AttachmentContentLoader.java +++ b/k9mail/src/main/java/com/fsck/k9/activity/loader/AttachmentContentLoader.java @@ -7,7 +7,7 @@ import java.io.InputStream; import android.content.AsyncTaskLoader; import android.content.Context; -import android.util.Log; +import timber.log.Timber; import com.fsck.k9.K9; import com.fsck.k9.activity.misc.Attachment; @@ -58,9 +58,7 @@ public class AttachmentContentLoader extends AsyncTaskLoader { File file = File.createTempFile(FILENAME_PREFIX, null, context.getCacheDir()); file.deleteOnExit(); - if (K9.DEBUG) { - Log.v(K9.LOG_TAG, "Saving attachment to " + file.getAbsolutePath()); - } + Timber.v("Saving attachment to %s", file.getAbsolutePath()); SafeContentResolver safeContentResolver = SafeContentResolverCompat.newInstance(context); InputStream in = safeContentResolver.openInputStream(sourceAttachment.uri); @@ -78,7 +76,7 @@ public class AttachmentContentLoader extends AsyncTaskLoader { cachedResultAttachment = sourceAttachment.deriveWithLoadComplete(file.getAbsolutePath()); return cachedResultAttachment; } catch (IOException e) { - Log.e(K9.LOG_TAG, "Error saving attachment!", e); + Timber.e(e, "Error saving attachment!"); } cachedResultAttachment = sourceAttachment.deriveWithLoadCancelled(); diff --git a/k9mail/src/main/java/com/fsck/k9/activity/loader/AttachmentInfoLoader.java b/k9mail/src/main/java/com/fsck/k9/activity/loader/AttachmentInfoLoader.java index cb38c1257..ea5eb3ee5 100644 --- a/k9mail/src/main/java/com/fsck/k9/activity/loader/AttachmentInfoLoader.java +++ b/k9mail/src/main/java/com/fsck/k9/activity/loader/AttachmentInfoLoader.java @@ -8,7 +8,7 @@ import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.provider.OpenableColumns; -import android.util.Log; +import timber.log.Timber; import com.fsck.k9.K9; import com.fsck.k9.activity.misc.Attachment; @@ -87,16 +87,15 @@ public class AttachmentInfoLoader extends AsyncTaskLoader { if (size <= 0) { String uriString = uri.toString(); if (uriString.startsWith("file://")) { - Log.v(K9.LOG_TAG, uriString.substring("file://".length())); File f = new File(uriString.substring("file://".length())); size = f.length(); } else { - Log.v(K9.LOG_TAG, "Not a file: " + uriString); + Timber.v("Not a file: %s", uriString); } } else { - Log.v(K9.LOG_TAG, "old attachment.size: " + size); + Timber.v("old attachment.size: %d", size); } - Log.v(K9.LOG_TAG, "new attachment.size: " + size); + Timber.v("new attachment.size: %d", size); cachedResultAttachment = sourceAttachment.deriveWithMetadataLoaded(usableContentType, name, size); return cachedResultAttachment; diff --git a/k9mail/src/main/java/com/fsck/k9/activity/setup/AccountSettings.java b/k9mail/src/main/java/com/fsck/k9/activity/setup/AccountSettings.java index 8db66b91c..30a570c0e 100644 --- a/k9mail/src/main/java/com/fsck/k9/activity/setup/AccountSettings.java +++ b/k9mail/src/main/java/com/fsck/k9/activity/setup/AccountSettings.java @@ -22,7 +22,7 @@ import android.preference.Preference.OnPreferenceChangeListener; import android.preference.Preference.OnPreferenceClickListener; import android.preference.PreferenceScreen; import android.preference.RingtonePreference; -import android.util.Log; +import timber.log.Timber; import android.widget.Toast; import com.fsck.k9.Account; @@ -219,7 +219,7 @@ public class AccountSettings extends K9PreferenceActivity { mIsExpungeCapable = store.isExpungeCapable(); mIsSeenFlagSupported = store.isSeenFlagSupported(); } catch (Exception e) { - Log.e(K9.LOG_TAG, "Could not get remote store", e); + Timber.e(e, "Could not get remote store"); } addPreferencesFromResource(R.xml.account_settings_preferences); diff --git a/k9mail/src/main/java/com/fsck/k9/activity/setup/AccountSetupAccountType.java b/k9mail/src/main/java/com/fsck/k9/activity/setup/AccountSetupAccountType.java index 14b8fc4f6..9173c5a8c 100644 --- a/k9mail/src/main/java/com/fsck/k9/activity/setup/AccountSetupAccountType.java +++ b/k9mail/src/main/java/com/fsck/k9/activity/setup/AccountSetupAccountType.java @@ -4,7 +4,7 @@ package com.fsck.k9.activity.setup; import android.content.Context; import android.content.Intent; import android.os.Bundle; -import android.util.Log; +import timber.log.Timber; import android.view.View; import android.view.View.OnClickListener; import android.widget.Toast; @@ -125,7 +125,7 @@ public class AccountSetupAccountType extends K9Activity implements OnClickListen } private void failure(Exception use) { - Log.e(K9.LOG_TAG, "Failure", use); + Timber.e(use, "Failure"); String toastText = getString(R.string.account_setup_bad_uri, use.getMessage()); Toast toast = Toast.makeText(getApplication(), toastText, Toast.LENGTH_LONG); diff --git a/k9mail/src/main/java/com/fsck/k9/activity/setup/AccountSetupBasics.java b/k9mail/src/main/java/com/fsck/k9/activity/setup/AccountSetupBasics.java index 10cce4866..0ce978d05 100644 --- a/k9mail/src/main/java/com/fsck/k9/activity/setup/AccountSetupBasics.java +++ b/k9mail/src/main/java/com/fsck/k9/activity/setup/AccountSetupBasics.java @@ -17,7 +17,7 @@ import android.os.Bundle; import android.text.Editable; import android.text.InputType; import android.text.TextWatcher; -import android.util.Log; +import timber.log.Timber; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; @@ -232,7 +232,7 @@ public class AccountSetupBasics extends K9Activity try { name = getDefaultAccountName(); } catch (Exception e) { - Log.e(K9.LOG_TAG, "Could not get default account name", e); + Timber.e(e, "Could not get default account name"); } if (name == null) { @@ -496,7 +496,7 @@ public class AccountSetupBasics extends K9Activity } } } catch (Exception e) { - Log.e(K9.LOG_TAG, "Error while trying to load provider settings.", e); + Timber.e(e, "Error while trying to load provider settings."); } return null; } diff --git a/k9mail/src/main/java/com/fsck/k9/activity/setup/AccountSetupCheckSettings.java b/k9mail/src/main/java/com/fsck/k9/activity/setup/AccountSetupCheckSettings.java index 4d9b3cea7..8cf1b2058 100644 --- a/k9mail/src/main/java/com/fsck/k9/activity/setup/AccountSetupCheckSettings.java +++ b/k9mail/src/main/java/com/fsck/k9/activity/setup/AccountSetupCheckSettings.java @@ -11,7 +11,7 @@ import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; -import android.util.Log; +import timber.log.Timber; import android.view.View; import android.view.View.OnClickListener; import android.widget.ProgressBar; @@ -101,7 +101,7 @@ public class AccountSetupCheckSettings extends K9Activity implements OnClickList } private void handleCertificateValidationException(CertificateValidationException cve) { - Log.e(K9.LOG_TAG, "Error while testing settings", cve); + Timber.e(cve, "Error while testing settings"); X509Certificate[] chain = cve.getCertChain(); // Avoid NullPointerException in acceptKeyDialog() @@ -155,7 +155,7 @@ public class AccountSetupCheckSettings extends K9Activity implements OnClickList try { sha1 = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { - Log.e(K9.LOG_TAG, "Error while initializing MessageDigest", e); + Timber.e(e, "Error while initializing MessageDigest"); } final X509Certificate[] chain = ex.getCertChain(); @@ -188,7 +188,7 @@ public class AccountSetupCheckSettings extends K9Activity implements OnClickList String name; switch (type.intValue()) { case 0: - Log.w(K9.LOG_TAG, "SubjectAltName of type OtherName not supported."); + Timber.w("SubjectAltName of type OtherName not supported."); continue; case 1: // RFC822Name name = (String)value; @@ -197,13 +197,13 @@ public class AccountSetupCheckSettings extends K9Activity implements OnClickList name = (String)value; break; case 3: - Log.w(K9.LOG_TAG, "unsupported SubjectAltName of type x400Address"); + Timber.w("unsupported SubjectAltName of type x400Address"); continue; case 4: - Log.w(K9.LOG_TAG, "unsupported SubjectAltName of type directoryName"); + Timber.w("unsupported SubjectAltName of type directoryName"); continue; case 5: - Log.w(K9.LOG_TAG, "unsupported SubjectAltName of type ediPartyName"); + Timber.w("unsupported SubjectAltName of type ediPartyName"); continue; case 6: // Uri name = (String)value; @@ -212,7 +212,7 @@ public class AccountSetupCheckSettings extends K9Activity implements OnClickList name = (String)value; break; default: - Log.w(K9.LOG_TAG, "unsupported SubjectAltName of unknown type"); + Timber.w("unsupported SubjectAltName of unknown type"); continue; } @@ -232,7 +232,7 @@ public class AccountSetupCheckSettings extends K9Activity implements OnClickList } } catch (Exception e1) { // don't fail just because of subjectAltNames - Log.w(K9.LOG_TAG, "cannot display SubjectAltNames in dialog", e1); + Timber.w(e1, "cannot display SubjectAltNames in dialog"); } chainInfo.append("Issuer: ").append(chain[i].getIssuerDN().toString()).append("\n"); @@ -242,7 +242,7 @@ public class AccountSetupCheckSettings extends K9Activity implements OnClickList String sha1sum = Hex.encodeHex(sha1.digest(chain[i].getEncoded())); chainInfo.append("Fingerprint (SHA-1): ").append(sha1sum).append("\n"); } catch (CertificateEncodingException e) { - Log.e(K9.LOG_TAG, "Error while encoding certificate", e); + Timber.e(e, "Error while encoding certificate"); } } } @@ -429,14 +429,14 @@ public class AccountSetupCheckSettings extends K9Activity implements OnClickList finish(); } catch (AuthenticationFailedException afe) { - Log.e(K9.LOG_TAG, "Error while testing settings", afe); + Timber.e(afe, "Error while testing settings"); showErrorDialog( R.string.account_setup_failed_dlg_auth_message_fmt, afe.getMessage() == null ? "" : afe.getMessage()); } catch (CertificateValidationException cve) { handleCertificateValidationException(cve); } catch (Exception e) { - Log.e(K9.LOG_TAG, "Error while testing settings", e); + Timber.e(e, "Error while testing settings"); String message = e.getMessage() == null ? "" : e.getMessage(); showErrorDialog(R.string.account_setup_failed_dlg_server_message_fmt, message); } diff --git a/k9mail/src/main/java/com/fsck/k9/activity/setup/AccountSetupIncoming.java b/k9mail/src/main/java/com/fsck/k9/activity/setup/AccountSetupIncoming.java index c48f643a4..2fea3592a 100644 --- a/k9mail/src/main/java/com/fsck/k9/activity/setup/AccountSetupIncoming.java +++ b/k9mail/src/main/java/com/fsck/k9/activity/setup/AccountSetupIncoming.java @@ -8,7 +8,7 @@ import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.text.method.DigitsKeyListener; -import android.util.Log; +import timber.log.Timber; import android.view.View; import android.view.View.OnClickListener; import android.widget.*; @@ -494,7 +494,7 @@ public class AccountSetupIncoming extends K9Activity implements OnClickListener Store store = mAccount.getRemoteStore(); isPushCapable = store.isPushCapable(); } catch (Exception e) { - Log.e(K9.LOG_TAG, "Could not get remote store", e); + Timber.e(e, "Could not get remote store"); } if (isPushCapable && mAccount.getFolderPushMode() != FolderMode.NONE) { MailService.actionRestartPushers(this, null); @@ -602,7 +602,7 @@ public class AccountSetupIncoming extends K9Activity implements OnClickListener } private void failure(Exception use) { - Log.e(K9.LOG_TAG, "Failure", use); + Timber.e(use, "Failure"); String toastText = getString(R.string.account_setup_bad_uri, use.getMessage()); Toast toast = Toast.makeText(getApplication(), toastText, Toast.LENGTH_LONG); diff --git a/k9mail/src/main/java/com/fsck/k9/activity/setup/AccountSetupOptions.java b/k9mail/src/main/java/com/fsck/k9/activity/setup/AccountSetupOptions.java index 47cee8a8b..d44e9aa09 100644 --- a/k9mail/src/main/java/com/fsck/k9/activity/setup/AccountSetupOptions.java +++ b/k9mail/src/main/java/com/fsck/k9/activity/setup/AccountSetupOptions.java @@ -4,7 +4,7 @@ package com.fsck.k9.activity.setup; import android.content.Context; import android.content.Intent; import android.os.Bundle; -import android.util.Log; +import timber.log.Timber; import android.view.View; import android.view.View.OnClickListener; import android.widget.ArrayAdapter; @@ -115,7 +115,7 @@ public class AccountSetupOptions extends K9Activity implements OnClickListener { Store store = mAccount.getRemoteStore(); isPushCapable = store.isPushCapable(); } catch (Exception e) { - Log.e(K9.LOG_TAG, "Could not get remote store", e); + Timber.e(e, "Could not get remote store"); } diff --git a/k9mail/src/main/java/com/fsck/k9/activity/setup/AccountSetupOutgoing.java b/k9mail/src/main/java/com/fsck/k9/activity/setup/AccountSetupOutgoing.java index 2069996ef..cf0ed34f7 100644 --- a/k9mail/src/main/java/com/fsck/k9/activity/setup/AccountSetupOutgoing.java +++ b/k9mail/src/main/java/com/fsck/k9/activity/setup/AccountSetupOutgoing.java @@ -7,7 +7,7 @@ import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.text.method.DigitsKeyListener; -import android.util.Log; +import timber.log.Timber; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; @@ -487,7 +487,7 @@ public class AccountSetupOutgoing extends K9Activity implements OnClickListener, } private void failure(Exception use) { - Log.e(K9.LOG_TAG, "Failure", use); + Timber.e(use, "Failure"); String toastText = getString(R.string.account_setup_bad_uri, use.getMessage()); Toast toast = Toast.makeText(getApplication(), toastText, Toast.LENGTH_LONG); diff --git a/k9mail/src/main/java/com/fsck/k9/activity/setup/FolderSettings.java b/k9mail/src/main/java/com/fsck/k9/activity/setup/FolderSettings.java index 682b57921..ffe6de63b 100644 --- a/k9mail/src/main/java/com/fsck/k9/activity/setup/FolderSettings.java +++ b/k9mail/src/main/java/com/fsck/k9/activity/setup/FolderSettings.java @@ -7,7 +7,7 @@ import android.os.Bundle; import android.preference.CheckBoxPreference; import android.preference.ListPreference; import android.preference.Preference; -import android.util.Log; +import timber.log.Timber; import com.fsck.k9.*; import com.fsck.k9.activity.FolderInfoHolder; import com.fsck.k9.activity.K9PreferenceActivity; @@ -62,7 +62,7 @@ public class FolderSettings extends K9PreferenceActivity { mFolder = localStore.getFolder(folderName); mFolder.open(Folder.OPEN_MODE_RW); } catch (MessagingException me) { - Log.e(K9.LOG_TAG, "Unable to edit folder " + folderName + " preferences", me); + Timber.e(me, "Unable to edit folder %s preferences", folderName); return; } @@ -71,7 +71,7 @@ public class FolderSettings extends K9PreferenceActivity { Store store = mAccount.getRemoteStore(); isPushCapable = store.isPushCapable(); } catch (Exception e) { - Log.e(K9.LOG_TAG, "Could not get remote store", e); + Timber.e(e, "Could not get remote store"); } addPreferencesFromResource(R.xml.folder_settings_preferences); @@ -167,7 +167,7 @@ public class FolderSettings extends K9PreferenceActivity { try { saveSettings(); } catch (MessagingException e) { - Log.e(K9.LOG_TAG, "Saving folder settings failed", e); + Timber.e(e, "Saving folder settings failed"); } super.onPause(); diff --git a/k9mail/src/main/java/com/fsck/k9/activity/setup/Prefs.java b/k9mail/src/main/java/com/fsck/k9/activity/setup/Prefs.java index 0f082e0c4..9fed129bc 100644 --- a/k9mail/src/main/java/com/fsck/k9/activity/setup/Prefs.java +++ b/k9mail/src/main/java/com/fsck/k9/activity/setup/Prefs.java @@ -357,7 +357,7 @@ public class Prefs extends K9PreferenceActivity { mHideUserAgent = (CheckBoxPreference)findPreference(PREFERENCE_HIDE_USERAGENT); mHideTimeZone = (CheckBoxPreference)findPreference(PREFERENCE_HIDE_TIMEZONE); - mDebugLogging.setChecked(K9.DEBUG); + mDebugLogging.setChecked(K9.isDebug()); mSensitiveLogging.setChecked(K9.DEBUG_SENSITIVE); mHideUserAgent.setChecked(K9.hideUserAgent()); mHideTimeZone.setChecked(K9.hideTimeZone()); @@ -529,10 +529,10 @@ public class Prefs extends K9PreferenceActivity { K9.setAttachmentDefaultPath(mAttachmentPathPreference.getSummary().toString()); boolean needsRefresh = K9.setBackgroundOps(mBackgroundOps.getValue()); - if (!K9.DEBUG && mDebugLogging.isChecked()) { + if (!K9.isDebug() && mDebugLogging.isChecked()) { Toast.makeText(this, R.string.debug_logging_enabled, Toast.LENGTH_LONG).show(); } - K9.DEBUG = mDebugLogging.isChecked(); + K9.setDebug(mDebugLogging.isChecked()); K9.DEBUG_SENSITIVE = mSensitiveLogging.isChecked(); K9.setHideUserAgent(mHideUserAgent.isChecked()); K9.setHideTimeZone(mHideTimeZone.isChecked()); diff --git a/k9mail/src/main/java/com/fsck/k9/cache/TemporaryAttachmentStore.java b/k9mail/src/main/java/com/fsck/k9/cache/TemporaryAttachmentStore.java index 098e919e9..397de27f2 100644 --- a/k9mail/src/main/java/com/fsck/k9/cache/TemporaryAttachmentStore.java +++ b/k9mail/src/main/java/com/fsck/k9/cache/TemporaryAttachmentStore.java @@ -5,7 +5,7 @@ import java.io.File; import java.io.IOException; import android.content.Context; -import android.util.Log; +import timber.log.Timber; import com.fsck.k9.K9; import com.fsck.k9.helper.FileHelper; @@ -53,11 +53,9 @@ public class TemporaryAttachmentStore { for (File file : files) { if (file.lastModified() < cutOffTime) { if (file.delete()) { - if (K9.DEBUG) { - Log.d(K9.LOG_TAG, "Deleted from temporary attachment store: " + file.getName()); - } + Timber.d("Deleted from temporary attachment store: %s", file.getName()); } else { - Log.w(K9.LOG_TAG, "Couldn't delete from temporary attachment store: " + file.getName()); + Timber.w("Couldn't delete from temporary attachment store: %s", file.getName()); } } } diff --git a/k9mail/src/main/java/com/fsck/k9/controller/MessagingController.java b/k9mail/src/main/java/com/fsck/k9/controller/MessagingController.java index 92a43495a..01facaee7 100644 --- a/k9mail/src/main/java/com/fsck/k9/controller/MessagingController.java +++ b/k9mail/src/main/java/com/fsck/k9/controller/MessagingController.java @@ -42,7 +42,6 @@ import android.os.Process; import android.os.SystemClock; import android.support.annotation.NonNull; import android.support.annotation.VisibleForTesting; -import android.util.Log; import com.fsck.k9.Account; import com.fsck.k9.Account.DeletePolicy; @@ -105,6 +104,10 @@ import com.fsck.k9.search.LocalSearch; import com.fsck.k9.search.SearchAccount; import com.fsck.k9.search.SearchSpecification; import com.fsck.k9.search.SqlQueryBuilder; +import timber.log.Timber; + +import static com.fsck.k9.K9.MAX_SEND_ATTEMPTS; +import static com.fsck.k9.mail.Flag.X_REMOTE_COPY_STARTED; /** @@ -196,10 +199,10 @@ public class MessagingController { if (command != null) { commandDescription = command.description; - if (K9.DEBUG) { - Log.i(K9.LOG_TAG, "Running command '" + command.description + "', seq = " + command.sequence + - "(" + (command.isForegroundPriority ? "foreground" : "background") + "priority)"); - } + Timber.i("Running command '%s', seq = %s (%s priority)", + command.description, + command.sequence, + command.isForegroundPriority ? "foreground" : "background"); try { command.runnable.run(); @@ -212,20 +215,17 @@ public class MessagingController { sleep(30 * 1000); queuedCommands.put(command); } catch (InterruptedException e) { - Log.e(K9.LOG_TAG, "interrupted while putting a pending command for" - + " an unavailable account back into the queue." - + " THIS SHOULD NEVER HAPPEN."); + Timber.e("Interrupted while putting a pending command for an unavailable account " + + "back into the queue. THIS SHOULD NEVER HAPPEN."); } } }.start(); } - if (K9.DEBUG) { - Log.i(K9.LOG_TAG, " Command '" + command.description + "' completed"); - } + Timber.i(" Command '%s' completed", command.description); } } catch (Exception e) { - Log.e(K9.LOG_TAG, "Error running command '" + commandDescription + "'", e); + Timber.e(e, "Error running command '%s'", commandDescription); } } } @@ -376,7 +376,7 @@ public class MessagingController { } List localFolders = null; if (!account.isAvailable(context)) { - Log.i(K9.LOG_TAG, "not listing folders of unavailable account"); + Timber.i("not listing folders of unavailable account"); } else { try { LocalStore localStore = account.getLocalStore(); @@ -557,14 +557,7 @@ public class MessagingController { public Future searchRemoteMessages(final String acctUuid, final String folderName, final String query, final Set requiredFlags, final Set forbiddenFlags, final MessagingListener listener) { - if (K9.DEBUG) { - String msg = "searchRemoteMessages (" - + "acct=" + acctUuid - + ", folderName = " + folderName - + ", query = " + query - + ")"; - Log.i(K9.LOG_TAG, msg); - } + Timber.i("searchRemoteMessages (acct = %s, folderName = %s, query = %s)", acctUuid, folderName, query); return threadPool.submit(new Runnable() { @Override @@ -600,9 +593,7 @@ public class MessagingController { List messages = remoteFolder.search(query, requiredFlags, forbiddenFlags); - if (K9.DEBUG) { - Log.i("Remote Search", "Remote search got " + messages.size() + " results"); - } + Timber.i("Remote search got %d results", messages.size()); // There's no need to fetch messages already completely downloaded List remoteMessages = localFolder.extractNewMessages(messages); @@ -626,9 +617,9 @@ public class MessagingController { } catch (Exception e) { if (Thread.currentThread().isInterrupted()) { - Log.i(K9.LOG_TAG, "Caught exception on aborted remote search; safe to ignore.", e); + Timber.i(e, "Caught exception on aborted remote search; safe to ignore."); } else { - Log.e(K9.LOG_TAG, "Could not complete remote search", e); + Timber.e(e, "Could not complete remote search"); if (listener != null) { listener.remoteSearchFailed(null, e.getMessage()); } @@ -666,7 +657,7 @@ public class MessagingController { loadSearchResultsSynchronous(messages, localFolder, remoteFolder, listener); } catch (MessagingException e) { - Log.e(K9.LOG_TAG, "Exception in loadSearchResults: " + e); + Timber.e(e, "Exception in loadSearchResults"); addErrorMessage(account, null, e); } finally { if (listener != null) { @@ -741,9 +732,7 @@ public class MessagingController { Folder remoteFolder = null; LocalFolder tLocalFolder = null; - if (K9.DEBUG) { - Log.i(K9.LOG_TAG, "Synchronizing folder " + account.getDescription() + ":" + folder); - } + Timber.i("Synchronizing folder %s:%s", account.getDescription(), folder); for (MessagingListener l : getListeners(listener)) { l.synchronizeMailboxStarted(account, folder); @@ -761,16 +750,14 @@ public class MessagingController { Exception commandException = null; try { - if (K9.DEBUG) { - Log.d(K9.LOG_TAG, "SYNC: About to process pending commands for account " + account.getDescription()); - } + Timber.d("SYNC: About to process pending commands for account %s", account.getDescription()); try { processPendingCommandsSynchronous(account); } catch (Exception e) { addErrorMessage(account, null, e); - Log.e(K9.LOG_TAG, "Failure processing command, but allow message sync attempt", e); + Timber.e(e, "Failure processing command, but allow message sync attempt"); commandException = e; } @@ -778,9 +765,7 @@ public class MessagingController { * Get the message list from the local store and create an index of * the uids within the list. */ - if (K9.DEBUG) { - Log.v(K9.LOG_TAG, "SYNC: About to get local folder " + folder); - } + Timber.v("SYNC: About to get local folder %s", folder); final LocalStore localStore = account.getLocalStore(); tLocalFolder = localStore.getFolder(folder); @@ -790,16 +775,12 @@ public class MessagingController { Map localUidMap = localFolder.getAllMessagesAndEffectiveDates(); if (providedRemoteFolder != null) { - if (K9.DEBUG) { - Log.v(K9.LOG_TAG, "SYNC: using providedRemoteFolder " + folder); - } + Timber.v("SYNC: using providedRemoteFolder %s", folder); remoteFolder = providedRemoteFolder; } else { Store remoteStore = account.getRemoteStore(); - if (K9.DEBUG) { - Log.v(K9.LOG_TAG, "SYNC: About to get remote folder " + folder); - } + Timber.v("SYNC: About to get remote folder %s", folder); remoteFolder = remoteStore.getFolder(folder); if (!verifyOrCreateRemoteSpecialFolder(account, folder, remoteFolder, listener)) { @@ -828,15 +809,11 @@ public class MessagingController { /* * Open the remote folder. This pre-loads certain metadata like message count. */ - if (K9.DEBUG) { - Log.v(K9.LOG_TAG, "SYNC: About to open remote folder " + folder); - } + Timber.v("SYNC: About to open remote folder %s", folder); remoteFolder.open(Folder.OPEN_MODE_RW); if (Expunge.EXPUNGE_ON_POLL == account.getExpungePolicy()) { - if (K9.DEBUG) { - Log.d(K9.LOG_TAG, "SYNC: Expunging folder " + account.getDescription() + ":" + folder); - } + Timber.d("SYNC: Expunging folder %s:%s", account.getDescription(), folder); remoteFolder.expunge(); } @@ -858,9 +835,8 @@ public class MessagingController { final List remoteMessages = new ArrayList<>(); Map remoteUidMap = new HashMap<>(); - if (K9.DEBUG) { - Log.v(K9.LOG_TAG, "SYNC: Remote message count for folder " + folder + " is " + remoteMessageCount); - } + Timber.v("SYNC: Remote message count for folder %s is %d", folder, remoteMessageCount); + final Date earliestDate = account.getEarliestPollDate(); long earliestTimestamp = earliestDate != null ? earliestDate.getTime() : 0L; @@ -874,10 +850,8 @@ public class MessagingController { remoteStart = 1; } - if (K9.DEBUG) { - Log.v(K9.LOG_TAG, "SYNC: About to get messages " + remoteStart + " through " + remoteMessageCount + - " for folder " + folder); - } + Timber.v("SYNC: About to get messages %d through %d for folder %s", + remoteStart, remoteMessageCount, folder); final AtomicInteger headerProgress = new AtomicInteger(0); for (MessagingListener l : getListeners(listener)) { @@ -901,9 +875,8 @@ public class MessagingController { remoteUidMap.put(thisMess.getUid(), thisMess); } } - if (K9.DEBUG) { - Log.v(K9.LOG_TAG, "SYNC: Got " + remoteUidMap.size() + " messages for folder " + folder); - } + + Timber.v("SYNC: Got %d messages for folder %s", remoteUidMap.size(), folder); for (MessagingListener l : getListeners(listener)) { l.synchronizeMailboxHeadersFinished(account, folder, headerProgress.get(), remoteUidMap.size()); @@ -960,10 +933,11 @@ public class MessagingController { localFolder.setLastChecked(System.currentTimeMillis()); localFolder.setStatus(null); - if (K9.DEBUG) { - Log.d(K9.LOG_TAG, "Done synchronizing folder " + account.getDescription() + ":" + folder + - " @ " + new Date() + " with " + newMessages + " new messages"); - } + Timber.d("Done synchronizing folder %s:%s @ %tc with %d new messages", + account.getDescription(), + folder, + System.currentTimeMillis(), + newMessages); for (MessagingListener l : getListeners(listener)) { l.synchronizeMailboxFinished(account, folder, remoteMessageCount, newMessages); @@ -972,17 +946,15 @@ public class MessagingController { if (commandException != null) { String rootMessage = getRootCauseMessage(commandException); - Log.e(K9.LOG_TAG, "Root cause failure in " + account.getDescription() + ":" + - tLocalFolder.getName() + " was '" + rootMessage + "'"); + Timber.e("Root cause failure in %s:%s was '%s'", + account.getDescription(), tLocalFolder.getName(), rootMessage); localFolder.setStatus(rootMessage); for (MessagingListener l : getListeners(listener)) { l.synchronizeMailboxFailed(account, folder, rootMessage); } } - if (K9.DEBUG) { - Log.i(K9.LOG_TAG, "Done synchronizing folder " + account.getDescription() + ":" + folder); - } + Timber.i("Done synchronizing folder %s:%s", account.getDescription(), folder); } catch (AuthenticationFailedException e) { handleAuthenticationFailure(account, true); @@ -991,7 +963,7 @@ public class MessagingController { l.synchronizeMailboxFailed(account, folder, "Authentication failure"); } } catch (Exception e) { - Log.e(K9.LOG_TAG, "synchronizeMailbox", e); + Timber.e(e, "synchronizeMailbox"); // If we don't set the last checked, it can try too often during // failure conditions String rootMessage = getRootCauseMessage(e); @@ -1000,8 +972,8 @@ public class MessagingController { tLocalFolder.setStatus(rootMessage); tLocalFolder.setLastChecked(System.currentTimeMillis()); } catch (MessagingException me) { - Log.e(K9.LOG_TAG, "Could not set last checked on folder " + account.getDescription() + ":" + - tLocalFolder.getName(), e); + Timber.e(e, "Could not set last checked on folder %s:%s", + account.getDescription(), tLocalFolder.getName()); } } @@ -1010,8 +982,8 @@ public class MessagingController { } notifyUserIfCertificateProblem(account, e, true); addErrorMessage(account, null, e); - Log.e(K9.LOG_TAG, - "Failed synchronizing folder " + account.getDescription() + ":" + folder + " @ " + new Date()); + Timber.e("Failed synchronizing folder %s:%s @ %tc", account.getDescription(), folder, + System.currentTimeMillis()); } finally { if (providedRemoteFolder == null) { @@ -1063,10 +1035,8 @@ public class MessagingController { for (MessagingListener l : getListeners(listener)) { l.synchronizeMailboxFinished(account, folder, 0, 0); } - if (K9.DEBUG) { - Log.i(K9.LOG_TAG, "Done synchronizing folder " + folder); - } + Timber.i("Done synchronizing folder %s", folder); return false; } } @@ -1103,9 +1073,7 @@ public class MessagingController { Date downloadStarted = new Date(); // now if (earliestDate != null) { - if (K9.DEBUG) { - Log.d(K9.LOG_TAG, "Only syncing messages after " + earliestDate); - } + Timber.d("Only syncing messages after %s", earliestDate); } final String folder = remoteFolder.getName(); @@ -1115,7 +1083,7 @@ public class MessagingController { unreadBeforeStart = stats.unreadMessageCount; } catch (MessagingException e) { - Log.e(K9.LOG_TAG, "Unable to getUnreadMessageCount for account: " + account, e); + Timber.e(e, "Unable to getUnreadMessageCount for account: %s", account); } List syncFlagMessages = new ArrayList<>(); @@ -1135,9 +1103,7 @@ public class MessagingController { l.synchronizeMailboxProgress(account, folder, progress.get(), todo); } - if (K9.DEBUG) { - Log.d(K9.LOG_TAG, "SYNC: Have " + unsyncedMessages.size() + " unsynced messages"); - } + Timber.d("SYNC: Have %d unsynced messages", unsyncedMessages.size()); messages.clear(); final List largeMessages = new ArrayList<>(); @@ -1162,10 +1128,7 @@ public class MessagingController { } fp.add(FetchProfile.Item.ENVELOPE); - if (K9.DEBUG) { - Log.d(K9.LOG_TAG, - "SYNC: About to fetch " + unsyncedMessages.size() + " unsynced messages for folder " + folder); - } + Timber.d("SYNC: About to fetch %d unsynced messages for folder %s", unsyncedMessages.size(), folder); fetchUnsyncedMessages(account, remoteFolder, unsyncedMessages, smallMessages, largeMessages, progress, todo, fp); @@ -1179,17 +1142,12 @@ public class MessagingController { } localFolder.setPushState(updatedPushState); - if (K9.DEBUG) { - Log.d(K9.LOG_TAG, "SYNC: Synced unsynced messages for folder " + folder); - } - } - if (K9.DEBUG) { - Log.d(K9.LOG_TAG, "SYNC: Have " - + largeMessages.size() + " large messages and " - + smallMessages.size() + " small messages out of " - + unsyncedMessages.size() + " unsynced messages"); + Timber.d("SYNC: Synced unsynced messages for folder %s", folder); } + Timber.d("SYNC: Have %d large messages and %d small messages out of %d unsynced messages", + largeMessages.size(), smallMessages.size(), unsyncedMessages.size()); + unsyncedMessages.clear(); /* * Grab the content of the small messages first. This is going to @@ -1220,10 +1178,7 @@ public class MessagingController { refreshLocalMessageFlags(account, remoteFolder, localFolder, syncFlagMessages, progress, todo); - if (K9.DEBUG) { - Log.d(K9.LOG_TAG, - "SYNC: Synced remote messages for folder " + folder + ", " + newMessages.get() + " new messages"); - } + Timber.d("SYNC: Synced remote messages for folder %s, %d new messages", folder, newMessages.get()); if (purgeToVisibleLimit) { localFolder.purgeToVisibleLimit(new MessageRemovalListener() { @@ -1265,9 +1220,8 @@ public class MessagingController { final List syncFlagMessages, boolean flagSyncOnly) throws MessagingException { if (message.isSet(Flag.DELETED)) { - if (K9.DEBUG) { - Log.v(K9.LOG_TAG, "Message with uid " + message.getUid() + " is marked as deleted"); - } + Timber.v("Message with uid %s is marked as deleted", message.getUid()); + syncFlagMessages.add(message); return; } @@ -1277,15 +1231,11 @@ public class MessagingController { if (localMessage == null) { if (!flagSyncOnly) { if (!message.isSet(Flag.X_DOWNLOADED_FULL) && !message.isSet(Flag.X_DOWNLOADED_PARTIAL)) { - if (K9.DEBUG) { - Log.v(K9.LOG_TAG, "Message with uid " + message.getUid() + " has not yet been downloaded"); - } + Timber.v("Message with uid %s has not yet been downloaded", message.getUid()); unsyncedMessages.add(message); } else { - if (K9.DEBUG) { - Log.v(K9.LOG_TAG, "Message with uid " + message.getUid() + " is partially or fully downloaded"); - } + Timber.v("Message with uid %s is partially or fully downloaded", message.getUid()); // Store the updated message locally localFolder.appendMessages(Collections.singletonList(message)); @@ -1303,15 +1253,10 @@ public class MessagingController { } } } else if (!localMessage.isSet(Flag.DELETED)) { - if (K9.DEBUG) { - Log.v(K9.LOG_TAG, "Message with uid " + message.getUid() + " is present in the local store"); - } + Timber.v("Message with uid %s is present in the local store", message.getUid()); if (!localMessage.isSet(Flag.X_DOWNLOADED_FULL) && !localMessage.isSet(Flag.X_DOWNLOADED_PARTIAL)) { - if (K9.DEBUG) { - Log.v(K9.LOG_TAG, "Message with uid " + message.getUid() - + " is not downloaded, even partially; trying again"); - } + Timber.v("Message with uid %s is not downloaded, even partially; trying again", message.getUid()); unsyncedMessages.add(message); } else { @@ -1322,9 +1267,7 @@ public class MessagingController { syncFlagMessages.add(message); } } else { - if (K9.DEBUG) { - Log.v(K9.LOG_TAG, "Local copy of message with uid " + message.getUid() + " is marked as deleted"); - } + Timber.v("Local copy of message with uid %s is marked as deleted", message.getUid()); } } @@ -1344,15 +1287,13 @@ public class MessagingController { public void messageFinished(T message, int number, int ofTotal) { try { if (message.isSet(Flag.DELETED) || message.olderThan(earliestDate)) { - if (K9.DEBUG) { + if (K9.isDebug()) { if (message.isSet(Flag.DELETED)) { - Log.v(K9.LOG_TAG, "Newly downloaded message " + account + ":" + folder + ":" + - message.getUid() - + " was marked deleted on server, skipping"); + Timber.v("Newly downloaded message %s:%s:%s was marked deleted on server, " + + "skipping", account, folder, message.getUid()); } else { - Log.d(K9.LOG_TAG, - "Newly downloaded message " + message.getUid() + " is older than " - + earliestDate + ", skipping"); + Timber.d("Newly downloaded message %s is older than %s, skipping", + message.getUid(), earliestDate); } } progress.incrementAndGet(); @@ -1370,7 +1311,7 @@ public class MessagingController { smallMessages.add(message); } } catch (Exception e) { - Log.e(K9.LOG_TAG, "Error while storing downloaded message.", e); + Timber.e(e, "Error while storing downloaded message."); addErrorMessage(account, null, e); } } @@ -1391,10 +1332,7 @@ public class MessagingController { final Date earliestDate) { if (account.isSearchByDateCapable() && message.olderThan(earliestDate)) { - if (K9.DEBUG) { - Log.d(K9.LOG_TAG, "Message " + message.getUid() + " is older than " - + earliestDate + ", hence not saving"); - } + Timber.d("Message %s is older than %s, hence not saving", message.getUid(), earliestDate); return false; } return true; @@ -1412,9 +1350,7 @@ public class MessagingController { final Date earliestDate = account.getEarliestPollDate(); - if (K9.DEBUG) { - Log.d(K9.LOG_TAG, "SYNC: Fetching " + smallMessages.size() + " small messages for folder " + folder); - } + Timber.d("SYNC: Fetching %d small messages for folder %s", smallMessages.size(), folder); remoteFolder.fetch(smallMessages, fp, new MessageRetrievalListener() { @@ -1442,10 +1378,8 @@ public class MessagingController { newMessages.incrementAndGet(); } - if (K9.DEBUG) { - Log.v(K9.LOG_TAG, "About to notify listeners that we got a new small message " - + account + ":" + folder + ":" + message.getUid()); - } + Timber.v("About to notify listeners that we got a new small message %s:%s:%s", + account, folder, message.getUid()); // Update the listener with what we've found for (MessagingListener l : getListeners()) { @@ -1463,7 +1397,7 @@ public class MessagingController { } catch (MessagingException me) { addErrorMessage(account, null, me); - Log.e(K9.LOG_TAG, "SYNC: fetch small messages", me); + Timber.e(me, "SYNC: fetch small messages"); } } @@ -1476,9 +1410,7 @@ public class MessagingController { } }); - if (K9.DEBUG) { - Log.d(K9.LOG_TAG, "SYNC: Done fetching small messages for folder " + folder); - } + Timber.d("SYNC: Done fetching small messages for folder %s", folder); } private void downloadLargeMessages(final Account account, final Folder remoteFolder, @@ -1491,9 +1423,9 @@ public class MessagingController { FetchProfile fp) throws MessagingException { final String folder = remoteFolder.getName(); final Date earliestDate = account.getEarliestPollDate(); - if (K9.DEBUG) { - Log.d(K9.LOG_TAG, "SYNC: Fetching large messages for folder " + folder); - } + + Timber.d("SYNC: Fetching large messages for folder %s", folder); + remoteFolder.fetch(largeMessages, fp, null); for (T message : largeMessages) { @@ -1507,10 +1439,10 @@ public class MessagingController { } else { downloadPartial(remoteFolder, localFolder, message); } - if (K9.DEBUG) { - Log.v(K9.LOG_TAG, "About to notify listeners that we got a new large message " - + account + ":" + folder + ":" + message.getUid()); - } + + Timber.v("About to notify listeners that we got a new large message %s:%s:%s", + account, folder, message.getUid()); + // Update the listener with what we've found progress.incrementAndGet(); // TODO do we need to re-fetch this here? @@ -1532,10 +1464,8 @@ public class MessagingController { notificationController.addNewMailNotification(account, localMessage, unreadBeforeStart); } } - if (K9.DEBUG) { - Log.d(K9.LOG_TAG, "SYNC: Done fetching large messages for folder " + folder); - } + Timber.d("SYNC: Done fetching large messages for folder %s", folder); } private void downloadPartial(Folder remoteFolder, LocalFolder localFolder, Message message) @@ -1621,10 +1551,7 @@ public class MessagingController { final String folder = remoteFolder.getName(); if (remoteFolder.supportsFetchingFlags()) { - if (K9.DEBUG) { - Log.d(K9.LOG_TAG, "SYNC: About to sync flags for " - + syncFlagMessages.size() + " remote messages for folder " + folder); - } + Timber.d("SYNC: About to sync flags for %d remote messages for folder %s", syncFlagMessages.size(), folder); FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); @@ -1725,11 +1652,11 @@ public class MessagingController { try { processPendingCommandsSynchronous(account); } catch (UnavailableStorageException e) { - Log.i(K9.LOG_TAG, - "Failed to process pending command because storage is not available - trying again later."); + Timber.i("Failed to process pending command because storage is not available - " + + "trying again later."); throw new UnavailableAccountException(e); } catch (MessagingException me) { - Log.e(K9.LOG_TAG, "processPendingCommands", me); + Timber.e(me, "processPendingCommands"); addErrorMessage(account, null, me); @@ -1761,9 +1688,8 @@ public class MessagingController { try { for (PendingCommand command : commands) { processingCommand = command; - if (K9.DEBUG) { - Log.d(K9.LOG_TAG, "Processing pending command '" + command + "'"); - } + Timber.d("Processing pending command '%s'", command); + for (MessagingListener l : getListeners()) { l.pendingCommandStarted(account, command.getCommandName()); } @@ -1776,14 +1702,12 @@ public class MessagingController { command.execute(this, account); localStore.removePendingCommand(command); - if (K9.DEBUG) { - Log.d(K9.LOG_TAG, "Done processing pending command '" + command + "'"); - } + + Timber.d("Done processing pending command '%s'", command); } catch (MessagingException me) { if (me.isPermanentFailure()) { addErrorMessage(account, null, me); - Log.e(K9.LOG_TAG, - "Failure of command '" + command + "' was permanent, removing command from queue"); + Timber.e("Failure of command '%s' was permanent, removing command from queue", command); localStore.removePendingCommand(processingCommand); } else { throw me; @@ -1799,7 +1723,7 @@ public class MessagingController { } catch (MessagingException me) { notifyUserIfCertificateProblem(account, me, true); addErrorMessage(account, null, me); - Log.e(K9.LOG_TAG, "Could not process command '" + processingCommand + "'", me); + Timber.e(me, "Could not process command '%s'", processingCommand); throw me; } finally { for (MessagingListener l : getListeners()) { @@ -1855,15 +1779,13 @@ public class MessagingController { if (remoteMessage == null) { if (localMessage.isSet(Flag.X_REMOTE_COPY_STARTED)) { - Log.w(K9.LOG_TAG, "Local message with uid " + localMessage.getUid() + - " has flag " + Flag.X_REMOTE_COPY_STARTED + - " already set, checking for remote message with " + - " same message id"); + Timber.w("Local message with uid %s has flag %s already set, checking for remote message with " + + "same message id", localMessage.getUid(), X_REMOTE_COPY_STARTED); String rUid = remoteFolder.getUidFromMessageId(localMessage); if (rUid != null) { - Log.w(K9.LOG_TAG, "Local message has flag " + Flag.X_REMOTE_COPY_STARTED + - " already set, and there is a remote message with uid " + - rUid + ", assuming message was already copied and aborting this copy"); + Timber.w("Local message has flag %s already set, and there is a remote message with uid %s, " + + "assuming message was already copied and aborting this copy", + X_REMOTE_COPY_STARTED, rUid); String oldUid = localMessage.getUid(); localMessage.setUid(rUid); @@ -1873,7 +1795,7 @@ public class MessagingController { } return; } else { - Log.w(K9.LOG_TAG, "No remote message with message-id found, proceeding with append"); + Timber.w("No remote message with message-id found, proceeding with append"); } } @@ -1999,18 +1921,13 @@ public class MessagingController { + srcFolder + " read/write", true); } - if (K9.DEBUG) { - Log.d(K9.LOG_TAG, "processingPendingMoveOrCopy: source folder = " + srcFolder - + ", " + messages.size() + " messages, destination folder = " + destFolder + ", isCopy = " + - isCopy); - } + Timber.d("processingPendingMoveOrCopy: source folder = %s, %d messages, destination folder = %s, " + + "isCopy = %s", srcFolder, messages.size(), destFolder, isCopy); Map remoteUidMap = null; if (!isCopy && destFolder.equals(account.getTrashFolderName())) { - if (K9.DEBUG) { - Log.d(K9.LOG_TAG, "processingPendingMoveOrCopy doing special case for deleting message"); - } + Timber.d("processingPendingMoveOrCopy doing special case for deleting message"); String destFolderName = destFolder; if (K9.FOLDER_NONE.equals(destFolderName)) { @@ -2027,11 +1944,7 @@ public class MessagingController { } } if (!isCopy && Expunge.EXPUNGE_IMMEDIATELY == account.getExpungePolicy()) { - if (K9.DEBUG) { - Log.i(K9.LOG_TAG, "processingPendingMoveOrCopy expunging folder " + account.getDescription() + ":" + - srcFolder); - } - + Timber.i("processingPendingMoveOrCopy expunging folder %s:%s", account.getDescription(), srcFolder); remoteSrcFolder.expunge(); } @@ -2133,9 +2046,8 @@ public class MessagingController { if (account.getErrorFolderName().equals(folder)) { return; } - if (K9.DEBUG) { - Log.d(K9.LOG_TAG, "processPendingExpunge: folder = " + folder); - } + + Timber.d("processPendingExpunge: folder = %s", folder); Store remoteStore = account.getRemoteStore(); Folder remoteFolder = remoteStore.getFolder(folder); @@ -2148,9 +2060,8 @@ public class MessagingController { return; } remoteFolder.expunge(); - if (K9.DEBUG) { - Log.d(K9.LOG_TAG, "processPendingExpunge: complete for folder = " + folder); - } + + Timber.d("processPendingExpunge: complete for folder = %s", folder); } finally { closeFolder(remoteFolder); } @@ -2194,7 +2105,7 @@ public class MessagingController { remoteFolder.setFlags(Collections.singleton(Flag.SEEN), true); remoteFolder.close(); } catch (UnsupportedOperationException uoe) { - Log.w(K9.LOG_TAG, "Could not mark all server-side as read because store doesn't support operation", uoe); + Timber.w(uoe, "Could not mark all server-side as read because store doesn't support operation"); } finally { closeFolder(localFolder); closeFolder(remoteFolder); @@ -2228,14 +2139,14 @@ public class MessagingController { addErrorMessage(account, subject, baos.toString()); } catch (Throwable it) { - Log.e(K9.LOG_TAG, "Could not save error message to " + account.getErrorFolderName(), it); + Timber.e(it, "Could not save error message to %s", account.getErrorFolderName()); } } private static AtomicBoolean loopCatch = new AtomicBoolean(); private void addErrorMessage(Account account, String subject, String body) { - if (!K9.DEBUG) { + if (!K9.isDebug()) { return; } if (!loopCatch.compareAndSet(false, true)) { @@ -2265,7 +2176,7 @@ public class MessagingController { localFolder.clearMessagesOlderThan(nowTime - (15 * 60 * 1000)); } catch (Throwable it) { - Log.e(K9.LOG_TAG, "Could not save error message to " + account.getErrorFolderName(), it); + Timber.e(it, "Could not save error message to %s", account.getErrorFolderName()); } finally { loopCatch.set(false); } @@ -2273,10 +2184,8 @@ public class MessagingController { public void markAllMessagesRead(final Account account, final String folder) { + Timber.i("Marking all messages in %s:%s as read", account.getDescription(), folder); - if (K9.DEBUG) { - Log.i(K9.LOG_TAG, "Marking all messages in " + account.getDescription() + ":" + folder + " as read"); - } PendingCommand command = PendingMarkAllAsRead.create(folder); queuePendingCommand(account, command); processPendingCommands(account); @@ -2315,7 +2224,7 @@ public class MessagingController { try { localStore = account.getLocalStore(); } catch (MessagingException e) { - Log.e(K9.LOG_TAG, "Couldn't get LocalStore instance", e); + Timber.e(e, "Couldn't get LocalStore instance"); return; } @@ -2330,7 +2239,7 @@ public class MessagingController { removeFlagFromCache(account, ids, flag); } } catch (MessagingException e) { - Log.e(K9.LOG_TAG, "Couldn't set flags in local database", e); + Timber.e(e, "Couldn't set flags in local database"); } // Read folder name and UID of messages from the database @@ -2338,7 +2247,7 @@ public class MessagingController { try { folderMap = localStore.getFoldersAndUids(ids, threadedList); } catch (MessagingException e) { - Log.e(K9.LOG_TAG, "Couldn't get folder name and UID of messages", e); + Timber.e(e, "Couldn't get folder name and UID of messages"); return; } @@ -2354,7 +2263,7 @@ public class MessagingController { l.folderStatusChanged(account, folderName, unreadMessageCount); } } catch (MessagingException e) { - Log.w(K9.LOG_TAG, "Couldn't get unread count for folder: " + folderName, e); + Timber.w(e, "Couldn't get unread count for folder: %s", folderName); } // The error folder is always a local folder @@ -2474,11 +2383,11 @@ public class MessagingController { public void clearAllPending(final Account account) { try { - Log.w(K9.LOG_TAG, "Clearing pending commands!"); + Timber.w("Clearing pending commands!"); LocalStore localStore = account.getLocalStore(); localStore.removePendingCommands(); } catch (MessagingException me) { - Log.e(K9.LOG_TAG, "Unable to clear pending command", me); + Timber.e(me, "Unable to clear pending command"); addErrorMessage(account, null, me); } } @@ -2516,7 +2425,7 @@ public class MessagingController { LocalMessage message = localFolder.getMessage(uid); if (uid.startsWith(K9.LOCAL_UID_PREFIX)) { - Log.w(K9.LOG_TAG, "Message has local UID so cannot download fully."); + Timber.w("Message has local UID so cannot download fully."); // ASH move toast android.widget.Toast.makeText(context, "Message has local UID so cannot download fully", @@ -2651,9 +2560,7 @@ public class MessagingController { l.loadAttachmentFinished(account, message, part); } } catch (MessagingException me) { - if (K9.DEBUG) { - Log.v(K9.LOG_TAG, "Exception loading attachment", me); - } + Timber.v(me, "Exception loading attachment"); for (MessagingListener l : getListeners(listener)) { l.loadAttachmentFailed(account, message, part, me.getMessage()); @@ -2758,7 +2665,7 @@ public class MessagingController { return true; } } catch (Exception e) { - Log.e(K9.LOG_TAG, "Exception while checking for unsent messages", e); + Timber.e(e, "Exception while checking for unsent messages"); } finally { closeFolder(localFolder); } @@ -2778,9 +2685,7 @@ public class MessagingController { localFolder = localStore.getFolder( account.getOutboxFolderName()); if (!localFolder.exists()) { - if (K9.DEBUG) { - Log.v(K9.LOG_TAG, "Outbox does not exist"); - } + Timber.v("Outbox does not exist"); return; } for (MessagingListener l : getListeners()) { @@ -2802,10 +2707,8 @@ public class MessagingController { fp.add(FetchProfile.Item.ENVELOPE); fp.add(FetchProfile.Item.BODY); - if (K9.DEBUG) { - Log.i(K9.LOG_TAG, "Scanning folder '" + account.getOutboxFolderName() - + "' (" + localFolder.getId() + ") for messages to send"); - } + Timber.i("Scanning folder '%s' (%d) for messages to send", + account.getOutboxFolderName(), localFolder.getId()); Transport transport = transportProvider.getTransport(K9.app, account); @@ -2820,13 +2723,12 @@ public class MessagingController { if (oldCount != null) { count = oldCount; } - if (K9.DEBUG) { - Log.i(K9.LOG_TAG, "Send count for message " + message.getUid() + " is " + count.get()); - } + + Timber.i("Send count for message %s is %d", message.getUid(), count.get()); if (count.incrementAndGet() > K9.MAX_SEND_ATTEMPTS) { - Log.e(K9.LOG_TAG, "Send count for message " + message.getUid() + " can't be delivered after " - + K9.MAX_SEND_ATTEMPTS + " attempts. Giving up until the user restarts the device"); + Timber.e("Send count for message %s can't be delivered after %d attempts. " + + "Giving up until the user restarts the device", message.getUid(), MAX_SEND_ATTEMPTS); notificationController.showSendFailedNotification(account, new MessagingException(message.getSubject())); continue; @@ -2835,16 +2737,16 @@ public class MessagingController { localFolder.fetch(Collections.singletonList(message), fp, null); try { if (message.getHeader(K9.IDENTITY_HEADER).length > 0) { - Log.v(K9.LOG_TAG, "The user has set the Outbox and Drafts folder to the same thing. " + + Timber.v("The user has set the Outbox and Drafts folder to the same thing. " + "This message appears to be a draft, so K-9 will not send it"); continue; } message.setFlag(Flag.X_SEND_IN_PROGRESS, true); - if (K9.DEBUG) { - Log.i(K9.LOG_TAG, "Sending message with UID " + message.getUid()); - } + + Timber.i("Sending message with UID %s", message.getUid()); transport.sendMessage(message); + message.setFlag(Flag.X_SEND_IN_PROGRESS, false); message.setFlag(Flag.SEEN, true); progress++; @@ -2878,7 +2780,7 @@ public class MessagingController { } catch (Exception e) { lastFailure = e; wasPermanentFailure = false; - Log.e(K9.LOG_TAG, "Failed to fetch message for sending", e); + Timber.e(e, "Failed to fetch message for sending"); addErrorMessage(account, "Failed to fetch message for sending", e); notifySynchronizeMailboxFailed(account, localFolder, e); } @@ -2896,12 +2798,11 @@ public class MessagingController { } } } catch (UnavailableStorageException e) { - Log.i(K9.LOG_TAG, "Failed to send pending messages because storage is not available - trying again later."); + Timber.i("Failed to send pending messages because storage is not available - trying again later."); throw new UnavailableAccountException(e); } catch (Exception e) { - if (K9.DEBUG) { - Log.v(K9.LOG_TAG, "Failed to send pending messages", e); - } + Timber.v(e, "Failed to send pending messages"); + for (MessagingListener l : getListeners()) { l.sendPendingMessagesFailed(account); } @@ -2918,23 +2819,15 @@ public class MessagingController { private void moveOrDeleteSentMessage(Account account, LocalStore localStore, LocalFolder localFolder, LocalMessage message) throws MessagingException { if (!account.hasSentFolder()) { - if (K9.DEBUG) { - Log.i(K9.LOG_TAG, "Account does not have a sent mail folder; deleting sent message"); - } + Timber.i("Account does not have a sent mail folder; deleting sent message"); message.setFlag(Flag.DELETED, true); } else { LocalFolder localSentFolder = localStore.getFolder(account.getSentFolderName()); - if (K9.DEBUG) { - Log.i(K9.LOG_TAG, "Moving sent message to folder '" + account.getSentFolderName() + "' (" + - localSentFolder.getId() + ") "); - } + Timber.i("Moving sent message to folder '%s' (%d)", account.getSentFolderName(), localSentFolder.getId()); localFolder.moveMessages(Collections.singletonList(message), localSentFolder); - if (K9.DEBUG) { - Log.i(K9.LOG_TAG, "Moved sent message to folder '" + account.getSentFolderName() + "' (" + - localSentFolder.getId() + ") "); - } + Timber.i("Moved sent message to folder '%s' (%d)", account.getSentFolderName(), localSentFolder.getId()); PendingCommand command = PendingAppend.create(localSentFolder.getName(), message.getUid()); queuePendingCommand(account, command); @@ -2945,7 +2838,7 @@ public class MessagingController { private void handleSendFailure(Account account, Store localStore, Folder localFolder, Message message, Exception exception, boolean permanentFailure) throws MessagingException { - Log.e(K9.LOG_TAG, "Failed to send message", exception); + Timber.e(exception, "Failed to send message"); if (permanentFailure) { moveMessageToDraftsFolder(account, localFolder, localStore, message); @@ -2981,8 +2874,7 @@ public class MessagingController { AccountStats stats = account.getStats(context); listener.accountStatusChanged(account, stats); } catch (MessagingException me) { - Log.e(K9.LOG_TAG, "Count not get unread count for account " + - account.getDescription(), me); + Timber.e(me, "Count not get unread count for account %s", account.getDescription()); } } @@ -3079,7 +2971,7 @@ public class MessagingController { Folder localFolder = account.getLocalStore().getFolder(folderName); unreadMessageCount = localFolder.getUnreadMessageCount(); } catch (MessagingException me) { - Log.e(K9.LOG_TAG, "Count not get unread count for account " + account.getDescription(), me); + Timber.e(me, "Count not get unread count for account %s", account.getDescription()); } l.folderStatusChanged(account, folderName, unreadMessageCount); } @@ -3105,7 +2997,7 @@ public class MessagingController { return localStore.isMoveCapable() && remoteStore.isMoveCapable(); } catch (MessagingException me) { - Log.e(K9.LOG_TAG, "Exception while ascertaining move capability", me); + Timber.e(me, "Exception while ascertaining move capability"); return false; } } @@ -3116,7 +3008,7 @@ public class MessagingController { Store remoteStore = account.getRemoteStore(); return localStore.isCopyCapable() && remoteStore.isCopyCapable(); } catch (MessagingException me) { - Log.e(K9.LOG_TAG, "Exception while ascertaining copy capability", me); + Timber.e(me, "Exception while ascertaining copy capability"); return false; } } @@ -3244,11 +3136,8 @@ public class MessagingController { origUidMap.put(message.getUid(), message); } - if (K9.DEBUG) { - Log.i(K9.LOG_TAG, "moveOrCopyMessageSynchronous: source folder = " + srcFolder - + ", " + messages.size() + " messages, " + ", destination folder = " + destFolder + - ", isCopy = " + isCopy); - } + Timber.i("moveOrCopyMessageSynchronous: source folder = %s, %d messages, destination folder = %s, " + + "isCopy = %s", srcFolder, messages.size(), destFolder, isCopy); Map uidMap; @@ -3296,7 +3185,7 @@ public class MessagingController { processPendingCommands(account); } catch (UnavailableStorageException e) { - Log.i(K9.LOG_TAG, "Failed to move/copy message because storage is not available - trying again later."); + Timber.i("Failed to move/copy message because storage is not available - trying again later."); throw new UnavailableAccountException(e); } catch (MessagingException me) { addErrorMessage(account, null, me); @@ -3357,7 +3246,7 @@ public class MessagingController { deleteMessagesSynchronous(account, folderName, messagesToDelete, null); } catch (MessagingException e) { - Log.e(K9.LOG_TAG, "Something went wrong while deleting threads", e); + Timber.e(e, "Something went wrong while deleting threads"); } } @@ -3450,9 +3339,7 @@ public class MessagingController { localFolder = localStore.getFolder(folder); Map uidMap = null; if (folder.equals(account.getTrashFolderName()) || !account.hasTrashFolder()) { - if (K9.DEBUG) { - Log.d(K9.LOG_TAG, "Deleting messages in trash folder or trash set to -None-, not copying"); - } + Timber.d("Deleting messages in trash folder or trash set to -None-, not copying"); localFolder.setFlags(messages, Collections.singleton(Flag.DELETED), true); } else { @@ -3461,9 +3348,7 @@ public class MessagingController { localTrashFolder.create(Folder.FolderType.HOLDS_MESSAGES); } if (localTrashFolder.exists()) { - if (K9.DEBUG) { - Log.d(K9.LOG_TAG, "Deleting messages in normal folder, moving"); - } + Timber.d("Deleting messages in normal folder, moving"); uidMap = localFolder.moveMessages(messages, localTrashFolder); @@ -3478,10 +3363,7 @@ public class MessagingController { } } - if (K9.DEBUG) { - Log.d(K9.LOG_TAG, - "Delete policy for account " + account.getDescription() + " is " + account.getDeletePolicy()); - } + Timber.d("Delete policy for account %s is %s", account.getDescription(), account.getDeletePolicy()); if (folder.equals(account.getOutboxFolderName())) { for (Message message : messages) { @@ -3502,14 +3384,12 @@ public class MessagingController { queueSetFlag(account, folder, true, Flag.SEEN, uids); processPendingCommands(account); } else { - if (K9.DEBUG) { - Log.d(K9.LOG_TAG, "Delete policy " + account.getDeletePolicy() + " prevents delete from server"); - } + Timber.d("Delete policy %s prevents delete from server", account.getDeletePolicy()); } unsuppressMessages(account, messages); } catch (UnavailableStorageException e) { - Log.i(K9.LOG_TAG, "Failed to delete message because storage is not available - trying again later."); + Timber.i("Failed to delete message because storage is not available - trying again later."); throw new UnavailableAccountException(e); } catch (MessagingException me) { addErrorMessage(account, null, me); @@ -3580,10 +3460,10 @@ public class MessagingController { processPendingCommands(account); } } catch (UnavailableStorageException e) { - Log.i(K9.LOG_TAG, "Failed to empty trash because storage is not available - trying again later."); + Timber.i("Failed to empty trash because storage is not available - trying again later."); throw new UnavailableAccountException(e); } catch (Exception e) { - Log.e(K9.LOG_TAG, "emptyTrash failed", e); + Timber.e(e, "emptyTrash failed"); addErrorMessage(account, null, e); } finally { closeFolder(localFolder); @@ -3609,10 +3489,10 @@ public class MessagingController { localFolder.open(Folder.OPEN_MODE_RW); localFolder.clearAllMessages(); } catch (UnavailableStorageException e) { - Log.i(K9.LOG_TAG, "Failed to clear folder because storage is not available - trying again later."); + Timber.i("Failed to clear folder because storage is not available - trying again later."); throw new UnavailableAccountException(e); } catch (Exception e) { - Log.e(K9.LOG_TAG, "clearFolder failed", e); + Timber.e(e, "clearFolder failed"); addErrorMessage(account, null, e); } finally { closeFolder(localFolder); @@ -3642,10 +3522,8 @@ public class MessagingController { } public void sendAlternate(Context context, Account account, LocalMessage message) { - if (K9.DEBUG) { - Log.d(K9.LOG_TAG, "Got message " + account.getDescription() + ":" + message.getFolder() - + ":" + message.getUid() + " for sendAlternate"); - } + Timber.d("Got message %s:%s:%s for sendAlternate", + account.getDescription(), message.getFolder(), message.getUid()); Intent msg = new Intent(Intent.ACTION_SEND); String quotedText = null; @@ -3713,9 +3591,8 @@ public class MessagingController { public void run() { try { - if (K9.DEBUG) { - Log.i(K9.LOG_TAG, "Starting mail check"); - } + Timber.i("Starting mail check"); + Preferences prefs = Preferences.getPreferences(context); Collection accounts; @@ -3731,16 +3608,14 @@ public class MessagingController { } } catch (Exception e) { - Log.e(K9.LOG_TAG, "Unable to synchronize mail", e); + Timber.e(e, "Unable to synchronize mail"); addErrorMessage(account, null, e); } putBackground("finalize sync", null, new Runnable() { @Override public void run() { - if (K9.DEBUG) { - Log.i(K9.LOG_TAG, "Finished mail sync"); - } + Timber.i("Finished mail sync"); if (wakeLock != null) { wakeLock.release(); @@ -3761,22 +3636,16 @@ public class MessagingController { final boolean ignoreLastCheckedTime, final MessagingListener listener) { if (!account.isAvailable(context)) { - if (K9.DEBUG) { - Log.i(K9.LOG_TAG, "Skipping synchronizing unavailable account " + account.getDescription()); - } + Timber.i("Skipping synchronizing unavailable account %s", account.getDescription()); return; } final long accountInterval = account.getAutomaticCheckIntervalMinutes() * 60 * 1000; if (!ignoreLastCheckedTime && accountInterval <= 0) { - if (K9.DEBUG) { - Log.i(K9.LOG_TAG, "Skipping synchronizing account " + account.getDescription()); - } + Timber.i("Skipping synchronizing account %s", account.getDescription()); return; } - if (K9.DEBUG) { - Log.i(K9.LOG_TAG, "Synchronizing account " + account.getDescription()); - } + Timber.i("Synchronizing account %s", account.getDescription()); account.setRingNotified(false); @@ -3819,15 +3688,14 @@ public class MessagingController { synchronizeFolder(account, folder, ignoreLastCheckedTime, accountInterval, listener); } } catch (MessagingException e) { - Log.e(K9.LOG_TAG, "Unable to synchronize account " + account.getName(), e); + Timber.e(e, "Unable to synchronize account %s", account.getName()); addErrorMessage(account, null, e); } finally { putBackground("clear notification flag for " + account.getDescription(), null, new Runnable() { @Override public void run() { - if (K9.DEBUG) { - Log.v(K9.LOG_TAG, "Clearing notification flag for " + account.getDescription()); - } + Timber.v("Clearing notification flag for %s", account.getDescription()); + account.setRingNotified(false); try { AccountStats stats = account.getStats(context); @@ -3835,7 +3703,7 @@ public class MessagingController { notificationController.clearNewMailNotifications(account); } } catch (MessagingException e) { - Log.e(K9.LOG_TAG, "Unable to getUnreadMessageCount for account: " + account, e); + Timber.e(e, "Unable to getUnreadMessageCount for account: %s", account); } } } @@ -3853,22 +3721,14 @@ public class MessagingController { final long accountInterval, final MessagingListener listener) { + Timber.v("Folder %s was last synced @ %tc", folder.getName(), folder.getLastChecked()); - if (K9.DEBUG) { - Log.v(K9.LOG_TAG, "Folder " + folder.getName() + " was last synced @ " + - new Date(folder.getLastChecked())); - } - - if (!ignoreLastCheckedTime && folder.getLastChecked() > - (System.currentTimeMillis() - accountInterval)) { - if (K9.DEBUG) { - Log.v(K9.LOG_TAG, "Not syncing folder " + folder.getName() - + ", previously synced @ " + new Date(folder.getLastChecked()) - + " which would be too recent for the account period"); - } - + if (!ignoreLastCheckedTime && folder.getLastChecked() > System.currentTimeMillis() - accountInterval) { + Timber.v("Not syncing folder %s, previously synced @ %tc which would be too recent for the account " + + "period", folder.getName(), folder.getLastChecked()); return; } + putBackground("sync" + folder.getName(), null, new Runnable() { @Override public void run() { @@ -3882,11 +3742,9 @@ public class MessagingController { if (!ignoreLastCheckedTime && tLocalFolder.getLastChecked() > (System.currentTimeMillis() - accountInterval)) { - if (K9.DEBUG) { - Log.v(K9.LOG_TAG, "Not running Command for folder " + folder.getName() - + ", previously synced @ " + new Date(folder.getLastChecked()) - + " which would be too recent for the account period"); - } + Timber.v("Not running Command for folder %s, previously synced @ %tc which would " + + "be too recent for the account period", + folder.getName(), folder.getLastChecked()); return; } showFetchingMailNotificationIfNecessary(account, folder); @@ -3896,9 +3754,8 @@ public class MessagingController { clearFetchingMailNotificationIfNecessary(account); } } catch (Exception e) { - - Log.e(K9.LOG_TAG, "Exception while processing folder " + - account.getDescription() + ":" + folder.getName(), e); + Timber.e(e, "Exception while processing folder %s:%s", + account.getDescription(), folder.getName()); addErrorMessage(account, null, e); } finally { closeFolder(tLocalFolder); @@ -3936,11 +3793,10 @@ public class MessagingController { l.accountSizeChanged(account, oldSize, newSize); } } catch (UnavailableStorageException e) { - Log.i(K9.LOG_TAG, - "Failed to compact account because storage is not available - trying again later."); + Timber.i("Failed to compact account because storage is not available - trying again later."); throw new UnavailableAccountException(e); } catch (Exception e) { - Log.e(K9.LOG_TAG, "Failed to compact account " + account.getDescription(), e); + Timber.e(e, "Failed to compact account %s", account.getDescription()); } } }); @@ -3965,10 +3821,10 @@ public class MessagingController { l.accountStatusChanged(account, stats); } } catch (UnavailableStorageException e) { - Log.i(K9.LOG_TAG, "Failed to clear account because storage is not available - trying again later."); + Timber.i("Failed to clear account because storage is not available - trying again later."); throw new UnavailableAccountException(e); } catch (Exception e) { - Log.e(K9.LOG_TAG, "Failed to clear account " + account.getDescription(), e); + Timber.e(e, "Failed to clear account %s", account.getDescription()); } } }); @@ -3993,11 +3849,10 @@ public class MessagingController { l.accountStatusChanged(account, stats); } } catch (UnavailableStorageException e) { - Log.i(K9.LOG_TAG, - "Failed to recreate an account because storage is not available - trying again later."); + Timber.i("Failed to recreate an account because storage is not available - trying again later."); throw new UnavailableAccountException(e); } catch (Exception e) { - Log.e(K9.LOG_TAG, "Failed to recreate account " + account.getDescription(), e); + Timber.e(e, "Failed to recreate account %s", account.getDescription()); } } }); @@ -4057,10 +3912,8 @@ public class MessagingController { try { Integer messageUid = Integer.parseInt(message.getUid()); if (messageUid <= localFolder.getLastUid()) { - if (K9.DEBUG) { - Log.d(K9.LOG_TAG, "Message uid is " + messageUid + ", max message uid is " + - localFolder.getLastUid() + ". Skipping notification."); - } + Timber.d("Message uid is %s, max message uid is %s. Skipping notification.", + messageUid, localFolder.getLastUid()); return false; } } catch (NumberFormatException e) { @@ -4121,7 +3974,7 @@ public class MessagingController { } } catch (MessagingException e) { - Log.e(K9.LOG_TAG, "Unable to save message as draft.", e); + Timber.e(e, "Unable to save message as draft."); addErrorMessage(account, null, e); } return localMessage; @@ -4132,7 +3985,7 @@ public class MessagingController { if (message instanceof LocalMessage) { id = message.getId(); } else { - Log.w(K9.LOG_TAG, "MessagingController.getId() called without a LocalMessage"); + Timber.w("MessagingController.getId() called without a LocalMessage"); id = INVALID_MESSAGE_ID; } @@ -4247,9 +4100,8 @@ public class MessagingController { continue; } - if (K9.DEBUG) { - Log.i(K9.LOG_TAG, "Starting pusher for " + account.getDescription() + ":" + folder.getName()); - } + + Timber.i("Starting pusher for %s:%s", account.getDescription(), folder.getName()); names.add(folder.getName()); } @@ -4259,11 +4111,8 @@ public class MessagingController { int maxPushFolders = account.getMaxPushFolders(); if (names.size() > maxPushFolders) { - if (K9.DEBUG) { - Log.i(K9.LOG_TAG, "Count of folders to push for account " + account.getDescription() + " is " + - names.size() - + ", greater than limit of " + maxPushFolders + ", truncating"); - } + Timber.i("Count of folders to push for account %s is %d, greater than limit of %d, truncating", + account.getDescription(), names.size(), maxPushFolders); names = names.subList(0, maxPushFolders); } @@ -4271,9 +4120,7 @@ public class MessagingController { try { Store store = account.getRemoteStore(); if (!store.isPushCapable()) { - if (K9.DEBUG) { - Log.i(K9.LOG_TAG, "Account " + account.getDescription() + " is not push capable, skipping"); - } + Timber.i("Account %s is not push capable, skipping", account.getDescription()); return false; } @@ -4285,28 +4132,24 @@ public class MessagingController { } } } catch (Exception e) { - Log.e(K9.LOG_TAG, "Could not get remote store", e); + Timber.e(e, "Could not get remote store"); return false; } return true; } else { - if (K9.DEBUG) { - Log.i(K9.LOG_TAG, "No folders are configured for pushing in account " + account.getDescription()); - } + Timber.i("No folders are configured for pushing in account %s", account.getDescription()); return false; } } catch (Exception e) { - Log.e(K9.LOG_TAG, "Got exception while setting up pushing", e); + Timber.e(e, "Got exception while setting up pushing"); } return false; } public void stopAllPushing() { - if (K9.DEBUG) { - Log.i(K9.LOG_TAG, "Stopping all pushers"); - } + Timber.i("Stopping all pushers"); Iterator iter = pushers.values().iterator(); while (iter.hasNext()) { @@ -4318,10 +4161,8 @@ public class MessagingController { public void messagesArrived(final Account account, final Folder remoteFolder, final List messages, final boolean flagSyncOnly) { - if (K9.DEBUG) { - Log.i(K9.LOG_TAG, "Got new pushed email messages for account " + account.getDescription() - + ", folder " + remoteFolder.getName()); - } + Timber.i("Got new pushed email messages for account %s, folder %s", + account.getDescription(), remoteFolder.getName()); final CountDownLatch latch = new CountDownLatch(1); putBackground("Push messageArrived of account " + account.getDescription() @@ -4342,10 +4183,7 @@ public class MessagingController { localFolder.setLastPush(System.currentTimeMillis()); localFolder.setStatus(null); - if (K9.DEBUG) { - Log.i(K9.LOG_TAG, - "messagesArrived newCount = " + newCount + ", unread count = " + unreadMessageCount); - } + Timber.i("messagesArrived newCount = %d, unread count = %d", newCount, unreadMessageCount); if (unreadMessageCount == 0) { notificationController.clearNewMailNotifications(account); @@ -4361,7 +4199,7 @@ public class MessagingController { try { localFolder.setStatus(errorMessage); } catch (Exception se) { - Log.e(K9.LOG_TAG, "Unable to set failed status on localFolder", se); + Timber.e(se, "Unable to set failed status on localFolder"); } for (MessagingListener l : getListeners()) { l.synchronizeMailboxFailed(account, remoteFolder.getName(), errorMessage); @@ -4377,11 +4215,10 @@ public class MessagingController { try { latch.await(); } catch (Exception e) { - Log.e(K9.LOG_TAG, "Interrupted while awaiting latch release", e); - } - if (K9.DEBUG) { - Log.i(K9.LOG_TAG, "MessagingController.messagesArrivedLatch released"); + Timber.e(e, "Interrupted while awaiting latch release"); } + + Timber.i("MessagingController.messagesArrivedLatch released"); } public void systemStatusChanged() { @@ -4467,7 +4304,7 @@ public class MessagingController { List localMessages = messageFolder.getMessagesByReference(messageReferences); actor.act(account, messageFolder, localMessages); } catch (MessagingException e) { - Log.e(K9.LOG_TAG, "Error loading account?!", e); + Timber.e(e, "Error loading account?!"); } } diff --git a/k9mail/src/main/java/com/fsck/k9/controller/MessagingControllerPushReceiver.java b/k9mail/src/main/java/com/fsck/k9/controller/MessagingControllerPushReceiver.java index 4fd0c89cd..802ea64d2 100644 --- a/k9mail/src/main/java/com/fsck/k9/controller/MessagingControllerPushReceiver.java +++ b/k9mail/src/main/java/com/fsck/k9/controller/MessagingControllerPushReceiver.java @@ -1,7 +1,7 @@ package com.fsck.k9.controller; import android.content.Context; -import android.util.Log; +import timber.log.Timber; import com.fsck.k9.Account; import com.fsck.k9.K9; @@ -40,8 +40,8 @@ public class MessagingControllerPushReceiver implements PushReceiver { } public void syncFolder(Folder folder) { - if (K9.DEBUG) - Log.v(K9.LOG_TAG, "syncFolder(" + folder.getName() + ")"); + Timber.v("syncFolder(%s)", folder.getName()); + final CountDownLatch latch = new CountDownLatch(1); controller.synchronizeMailbox(account, folder.getName(), new SimpleMessagingListener() { @Override @@ -57,14 +57,13 @@ public class MessagingControllerPushReceiver implements PushReceiver { } }, folder); - if (K9.DEBUG) - Log.v(K9.LOG_TAG, "syncFolder(" + folder.getName() + ") about to await latch release"); + Timber.v("syncFolder(%s) about to await latch release", folder.getName()); + try { latch.await(); - if (K9.DEBUG) - Log.v(K9.LOG_TAG, "syncFolder(" + folder.getName() + ") got latch release"); + Timber.v("syncFolder(%s) got latch release", folder.getName()); } catch (Exception e) { - Log.e(K9.LOG_TAG, "Interrupted while awaiting latch release", e); + Timber.e(e, "Interrupted while awaiting latch release"); } } @@ -96,8 +95,7 @@ public class MessagingControllerPushReceiver implements PushReceiver { localFolder.open(Folder.OPEN_MODE_RW); return localFolder.getPushState(); } catch (Exception e) { - Log.e(K9.LOG_TAG, "Unable to get push state from account " + account.getDescription() - + ", folder " + folderName, e); + Timber.e(e, "Unable to get push state from account %s, folder %s", account.getDescription(), folderName); return null; } finally { if (localFolder != null) { diff --git a/k9mail/src/main/java/com/fsck/k9/fragment/ConfirmationDialogFragment.java b/k9mail/src/main/java/com/fsck/k9/fragment/ConfirmationDialogFragment.java index 26b922cdc..db08cff6d 100644 --- a/k9mail/src/main/java/com/fsck/k9/fragment/ConfirmationDialogFragment.java +++ b/k9mail/src/main/java/com/fsck/k9/fragment/ConfirmationDialogFragment.java @@ -8,7 +8,7 @@ import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import android.content.DialogInterface.OnClickListener; import android.os.Bundle; -import android.util.Log; +import timber.log.Timber; import com.fsck.k9.K9; @@ -108,8 +108,7 @@ public class ConfirmationDialogFragment extends DialogFragment implements OnClic try { mListener = (ConfirmationDialogFragmentListener) activity; } catch (ClassCastException e) { - if (K9.DEBUG) - Log.d(K9.LOG_TAG, activity.toString() + " did not implement ConfirmationDialogFragmentListener"); + Timber.d("%s did not implement ConfirmationDialogFragmentListener", activity); } } diff --git a/k9mail/src/main/java/com/fsck/k9/fragment/MessageListFragment.java b/k9mail/src/main/java/com/fsck/k9/fragment/MessageListFragment.java index 8277dc422..6848c0ccf 100644 --- a/k9mail/src/main/java/com/fsck/k9/fragment/MessageListFragment.java +++ b/k9mail/src/main/java/com/fsck/k9/fragment/MessageListFragment.java @@ -43,7 +43,7 @@ import android.text.TextUtils; import android.text.format.DateUtils; import android.text.style.AbsoluteSizeSpan; import android.text.style.ForegroundColorSpan; -import android.util.Log; +import timber.log.Timber; import android.util.TypedValue; import android.view.ActionMode; import android.view.ContextMenu; @@ -1164,7 +1164,7 @@ public class MessageListFragment extends Fragment implements OnItemClickListener LocalFolder firstMsgFolder = getFolder(firstMsg.getFolderName(), account); firstMsgFolder.setLastSelectedFolderName(destFolderName); } catch (MessagingException e) { - Log.e(K9.LOG_TAG, "Error getting folder for setLastSelectedFolderName()", e); + Timber.e(e, "Error getting folder for setLastSelectedFolderName()"); } } @@ -2814,11 +2814,11 @@ public class MessageListFragment extends Fragment implements OnItemClickListener // If we represent a remote search, then kill that before going back. if (isRemoteSearch() && mRemoteSearchFuture != null) { try { - Log.i(K9.LOG_TAG, "Remote search in progress, attempting to abort..."); + Timber.i("Remote search in progress, attempting to abort..."); // Canceling the future stops any message fetches in progress. final boolean cancelSuccess = mRemoteSearchFuture.cancel(true); // mayInterruptIfRunning = true if (!cancelSuccess) { - Log.e(K9.LOG_TAG, "Could not cancel remote search future."); + Timber.e("Could not cancel remote search future."); } // Closing the folder will kill off the connection if we're mid-search. final Account searchAccount = mAccount; @@ -2828,7 +2828,7 @@ public class MessageListFragment extends Fragment implements OnItemClickListener mListener.remoteSearchFinished(mCurrentFolder.name, 0, searchAccount.getRemoteSearchNumResults(), null); } catch (Exception e) { // Since the user is going back, log and squash any exceptions. - Log.e(K9.LOG_TAG, "Could not abort remote search before going back", e); + Timber.e(e, "Could not abort remote search before going back"); } } super.onStop(); diff --git a/k9mail/src/main/java/com/fsck/k9/helper/Contacts.java b/k9mail/src/main/java/com/fsck/k9/helper/Contacts.java index b6eeeb7a1..0759e9ec5 100644 --- a/k9mail/src/main/java/com/fsck/k9/helper/Contacts.java +++ b/k9mail/src/main/java/com/fsck/k9/helper/Contacts.java @@ -8,7 +8,7 @@ import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.provider.ContactsContract; -import android.util.Log; +import timber.log.Timber; import com.fsck.k9.K9; import com.fsck.k9.mail.Address; @@ -265,7 +265,7 @@ public class Contacts { Uri person = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, contactId); return Uri.withAppendedPath(person, ContactsContract.Contacts.Photo.CONTENT_DIRECTORY); } catch (Exception e) { - Log.e(K9.LOG_TAG, "Couldn't fetch photo for contact with email " + address, e); + Timber.e(e, "Couldn't fetch photo for contact with email %s", address); return null; } } diff --git a/k9mail/src/main/java/com/fsck/k9/helper/FileHelper.java b/k9mail/src/main/java/com/fsck/k9/helper/FileHelper.java index 29b439a6e..e1a18302a 100644 --- a/k9mail/src/main/java/com/fsck/k9/helper/FileHelper.java +++ b/k9mail/src/main/java/com/fsck/k9/helper/FileHelper.java @@ -7,7 +7,7 @@ import java.io.FileOutputStream; import java.io.IOException; import java.util.Locale; -import android.util.Log; +import timber.log.Timber; import com.fsck.k9.K9; import org.apache.commons.io.IOUtils; @@ -74,15 +74,15 @@ public class FileHelper { try { if (!file.exists()) { if (!file.createNewFile()) { - Log.d(K9.LOG_TAG, "Unable to create file: " + file.getAbsolutePath()); + Timber.d("Unable to create file: %s", file.getAbsolutePath()); } } else { if (!file.setLastModified(System.currentTimeMillis())) { - Log.d(K9.LOG_TAG, "Unable to change last modification date: " + file.getAbsolutePath()); + Timber.d("Unable to change last modification date: %s", file.getAbsolutePath()); } } } catch (Exception e) { - Log.d(K9.LOG_TAG, "Unable to touch file: " + file.getAbsolutePath(), e); + Timber.d(e, "Unable to touch file: %s", file.getAbsolutePath()); } } @@ -111,7 +111,7 @@ public class FileHelper { boolean deleteFromFailed = !from.delete(); if (deleteFromFailed) { - Log.e(K9.LOG_TAG, "Unable to delete source file after copying to destination!"); + Timber.e("Unable to delete source file after copying to destination!"); } } } @@ -133,12 +133,12 @@ public class FileHelper { public static boolean move(final File from, final File to) { if (to.exists()) { if (!to.delete()) { - Log.d(K9.LOG_TAG, "Unable to delete file: " + to.getAbsolutePath()); + Timber.d("Unable to delete file: %s", to.getAbsolutePath()); } } if (!to.getParentFile().mkdirs()) { - Log.d(K9.LOG_TAG, "Unable to make directories: " + to.getParentFile().getAbsolutePath()); + Timber.d("Unable to make directories: %s", to.getParentFile().getAbsolutePath()); } try { @@ -146,11 +146,11 @@ public class FileHelper { boolean deleteFromFailed = !from.delete(); if (deleteFromFailed) { - Log.e(K9.LOG_TAG, "Unable to delete source file after copying to destination!"); + Timber.e("Unable to delete source file after copying to destination!"); } return true; } catch (Exception e) { - Log.w(K9.LOG_TAG, "cannot move " + from.getAbsolutePath() + " to " + to.getAbsolutePath(), e); + Timber.w(e, "cannot move %s to %s", from.getAbsolutePath(), to.getAbsolutePath()); return false; } } @@ -162,11 +162,11 @@ public class FileHelper { if (!fromDir.isDirectory()) { if (toDir.exists()) { if (!toDir.delete()) { - Log.w(K9.LOG_TAG, "cannot delete already existing file/directory " + toDir.getAbsolutePath()); + Timber.w("cannot delete already existing file/directory %s", toDir.getAbsolutePath()); } } if (!fromDir.renameTo(toDir)) { - Log.w(K9.LOG_TAG, "cannot rename " + fromDir.getAbsolutePath() + " to " + toDir.getAbsolutePath() + " - moving instead"); + Timber.w("cannot rename %s to %s - moving instead", fromDir.getAbsolutePath(), toDir.getAbsolutePath()); move(fromDir, toDir); } return; @@ -174,11 +174,11 @@ public class FileHelper { if (!toDir.exists() || !toDir.isDirectory()) { if (toDir.exists()) { if (!toDir.delete()) { - Log.d(K9.LOG_TAG, "Unable to delete file: " + toDir.getAbsolutePath()); + Timber.d("Unable to delete file: %s", toDir.getAbsolutePath()); } } if (!toDir.mkdirs()) { - Log.w(K9.LOG_TAG, "cannot create directory " + toDir.getAbsolutePath()); + Timber.w("cannot create directory %s", toDir.getAbsolutePath()); } } File[] files = fromDir.listFiles(); @@ -186,18 +186,19 @@ public class FileHelper { if (file.isDirectory()) { moveRecursive(file, new File(toDir, file.getName())); if (!file.delete()) { - Log.d(K9.LOG_TAG, "Unable to delete file: " + toDir.getAbsolutePath()); + Timber.d("Unable to delete file: %s", toDir.getAbsolutePath()); } } else { File target = new File(toDir, file.getName()); if (!file.renameTo(target)) { - Log.w(K9.LOG_TAG, "cannot rename " + file.getAbsolutePath() + " to " + target.getAbsolutePath() + " - moving instead"); + Timber.w("cannot rename %s to %s - moving instead", + file.getAbsolutePath(), target.getAbsolutePath()); move(file, target); } } } if (!fromDir.delete()) { - Log.w(K9.LOG_TAG, "cannot delete " + fromDir.getAbsolutePath()); + Timber.w("cannot delete %s", fromDir.getAbsolutePath()); } } diff --git a/k9mail/src/main/java/com/fsck/k9/helper/Utility.java b/k9mail/src/main/java/com/fsck/k9/helper/Utility.java index d694298fb..c6a686294 100644 --- a/k9mail/src/main/java/com/fsck/k9/helper/Utility.java +++ b/k9mail/src/main/java/com/fsck/k9/helper/Utility.java @@ -12,7 +12,7 @@ import android.os.Looper; import android.provider.ContactsContract; import android.text.Editable; import android.text.TextUtils; -import android.util.Log; +import timber.log.Timber; import android.widget.EditText; import android.widget.TextView; @@ -381,15 +381,12 @@ public class Utility { while (imgMatches.find()) { String uriScheme = imgMatches.group(1); if (uriScheme.equals("http") || uriScheme.equals("https")) { - if (K9.DEBUG) { - Log.d(K9.LOG_TAG, "External images found"); - } + Timber.d("External images found"); return true; } } - if (K9.DEBUG) { - Log.d(K9.LOG_TAG, "No external images."); - } + + Timber.d("No external images."); return false; } diff --git a/k9mail/src/main/java/com/fsck/k9/mailstore/AttachmentResolver.java b/k9mail/src/main/java/com/fsck/k9/mailstore/AttachmentResolver.java index 2d49ee4a5..6faea95fb 100644 --- a/k9mail/src/main/java/com/fsck/k9/mailstore/AttachmentResolver.java +++ b/k9mail/src/main/java/com/fsck/k9/mailstore/AttachmentResolver.java @@ -10,7 +10,7 @@ import android.net.Uri; import android.support.annotation.Nullable; import android.support.annotation.VisibleForTesting; import android.support.annotation.WorkerThread; -import android.util.Log; +import timber.log.Timber; import com.fsck.k9.K9; import com.fsck.k9.mail.Body; @@ -72,7 +72,7 @@ public class AttachmentResolver { result.put(contentId, attachmentInfo.internalUri); } } catch (MessagingException e) { - Log.e(K9.LOG_TAG, "Error extracting attachment info", e); + Timber.e(e, "Error extracting attachment info"); } } } diff --git a/k9mail/src/main/java/com/fsck/k9/mailstore/DeferredFileBody.java b/k9mail/src/main/java/com/fsck/k9/mailstore/DeferredFileBody.java index db6cabff4..018408bb8 100644 --- a/k9mail/src/main/java/com/fsck/k9/mailstore/DeferredFileBody.java +++ b/k9mail/src/main/java/com/fsck/k9/mailstore/DeferredFileBody.java @@ -12,7 +12,7 @@ import java.io.OutputStream; import android.support.annotation.Nullable; import android.support.annotation.VisibleForTesting; -import android.util.Log; +import timber.log.Timber; import com.fsck.k9.K9; import com.fsck.k9.mail.MessagingException; @@ -70,11 +70,11 @@ public class DeferredFileBody implements RawDataBody, SizeAware { public InputStream getInputStream() throws MessagingException { try { if (file != null) { - Log.d(K9.LOG_TAG, "Decrypted data is file-backed."); + Timber.d("Decrypted data is file-backed."); return new BufferedInputStream(new FileInputStream(file)); } if (data != null) { - Log.d(K9.LOG_TAG, "Decrypted data is memory-backed."); + Timber.d("Decrypted data is memory-backed."); return new ByteArrayInputStream(data); } @@ -111,7 +111,7 @@ public class DeferredFileBody implements RawDataBody, SizeAware { throw new IllegalStateException("Data must be fully written before it can be read!"); } - Log.d(K9.LOG_TAG, "Writing body to file for attachment access"); + Timber.d("Writing body to file for attachment access"); file = fileFactory.createFile(); FileOutputStream fos = new FileOutputStream(file); diff --git a/k9mail/src/main/java/com/fsck/k9/mailstore/LocalFolder.java b/k9mail/src/main/java/com/fsck/k9/mailstore/LocalFolder.java index 3da3a28dd..ea2559d84 100644 --- a/k9mail/src/main/java/com/fsck/k9/mailstore/LocalFolder.java +++ b/k9mail/src/main/java/com/fsck/k9/mailstore/LocalFolder.java @@ -26,7 +26,7 @@ import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.support.annotation.NonNull; -import android.util.Log; +import timber.log.Timber; import com.fsck.k9.Account; import com.fsck.k9.K9; @@ -166,7 +166,7 @@ public class LocalFolder extends Folder implements Serializable { open(cursor); } } else { - Log.w(K9.LOG_TAG, "Creating folder " + getName() + " with existing id " + getId()); + Timber.w("Creating folder %s with existing id %d", getName(), getId()); create(FolderType.HOLDS_MESSAGES); open(mode); } @@ -612,7 +612,7 @@ public class LocalFolder extends Folder implements Serializable { prefHolder.displayClass = FolderClass.valueOf(storage.getString(id + ".displayMode", prefHolder.displayClass.name())); } catch (Exception e) { - Log.e(K9.LOG_TAG, "Unable to load displayMode for " + getName(), e); + Timber.e(e, "Unable to load displayMode for %s", getName()); } if (prefHolder.displayClass == FolderClass.NONE) { prefHolder.displayClass = FolderClass.NO_CLASS; @@ -622,7 +622,7 @@ public class LocalFolder extends Folder implements Serializable { prefHolder.syncClass = FolderClass.valueOf(storage.getString(id + ".syncMode", prefHolder.syncClass.name())); } catch (Exception e) { - Log.e(K9.LOG_TAG, "Unable to load syncMode for " + getName(), e); + Timber.e(e, "Unable to load syncMode for %s", getName()); } if (prefHolder.syncClass == FolderClass.NONE) { @@ -633,7 +633,7 @@ public class LocalFolder extends Folder implements Serializable { prefHolder.notifyClass = FolderClass.valueOf(storage.getString(id + ".notifyMode", prefHolder.notifyClass.name())); } catch (Exception e) { - Log.e(K9.LOG_TAG, "Unable to load notifyMode for " + getName(), e); + Timber.e(e, "Unable to load notifyMode for %s", getName()); } if (prefHolder.notifyClass == FolderClass.NONE) { prefHolder.notifyClass = FolderClass.INHERITED; @@ -643,7 +643,7 @@ public class LocalFolder extends Folder implements Serializable { prefHolder.pushClass = FolderClass.valueOf(storage.getString(id + ".pushMode", prefHolder.pushClass.name())); } catch (Exception e) { - Log.e(K9.LOG_TAG, "Unable to load pushMode for " + getName(), e); + Timber.e(e, "Unable to load pushMode for %s", getName()); } if (prefHolder.pushClass == FolderClass.NONE) { prefHolder.pushClass = FolderClass.INHERITED; @@ -1036,10 +1036,12 @@ public class LocalFolder extends Folder implements Serializable { String oldUID = message.getUid(); - if (K9.DEBUG) { - Log.d(K9.LOG_TAG, "Updating folder_id to " + lDestFolder.getId() + " for message with UID " - + message.getUid() + ", id " + lMessage.getId() + " currently in folder " + getName()); - } + Timber.d("Updating folder_id to %s for message with UID %s, " + + "id %d currently in folder %s", + lDestFolder.getId(), + message.getUid(), + lMessage.getId(), + getName()); String newUid = K9.LOCAL_UID_PREFIX + UUID.randomUUID().toString(); message.setUid(newUid); @@ -1660,7 +1662,7 @@ public class LocalFolder extends Folder implements Serializable { try { updateOrInsertMessagePart(db, new ContentValues(), part, messagePartId); } catch (Exception e) { - Log.e(K9.LOG_TAG, "Error writing message part", e); + Timber.e(e, "Error writing message part"); } return null; @@ -1708,7 +1710,7 @@ public class LocalFolder extends Folder implements Serializable { try { message.setFlags(flags, value); } catch (MessagingException e) { - Log.e(K9.LOG_TAG, "Something went wrong while setting flag", e); + Timber.e(e, "Something went wrong while setting flag"); } } @@ -1871,8 +1873,8 @@ public class LocalFolder extends Folder implements Serializable { String messagePartId = cursor.getString(0); File file = localStore.getAttachmentFile(messagePartId); if (file.exists()) { - if (!file.delete() && K9.DEBUG) { - Log.d(K9.LOG_TAG, "Couldn't delete message part file: " + file.getAbsolutePath()); + if (!file.delete() && K9.isDebug()) { + Timber.d("Couldn't delete message part file: %s", file.getAbsolutePath()); } } } @@ -1924,15 +1926,15 @@ public class LocalFolder extends Folder implements Serializable { return cursor.getInt(0); } } catch (Exception e) { - Log.e(K9.LOG_TAG, "Unable to updateLastUid: ", e); + Timber.e(e, "Unable to updateLastUid: "); } finally { Utility.closeQuietly(cursor); } return null; } }); - if (K9.DEBUG) - Log.d(K9.LOG_TAG, "Updated last UID for folder " + mName + " to " + lastUid); + + Timber.d("Updated last UID for folder %s to %s", mName, lastUid); mLastUid = lastUid; } @@ -1949,7 +1951,7 @@ public class LocalFolder extends Folder implements Serializable { return cursor.getLong(0); } } catch (Exception e) { - Log.e(K9.LOG_TAG, "Unable to fetch oldest message date: ", e); + Timber.e(e, "Unable to fetch oldest message date: "); } finally { Utility.closeQuietly(cursor); } diff --git a/k9mail/src/main/java/com/fsck/k9/mailstore/LocalMessage.java b/k9mail/src/main/java/com/fsck/k9/mailstore/LocalMessage.java index 7cbadf521..aa00de2e3 100644 --- a/k9mail/src/main/java/com/fsck/k9/mailstore/LocalMessage.java +++ b/k9mail/src/main/java/com/fsck/k9/mailstore/LocalMessage.java @@ -10,7 +10,7 @@ import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.support.annotation.VisibleForTesting; -import android.util.Log; +import timber.log.Timber; import com.fsck.k9.Account; import com.fsck.k9.BuildConfig; @@ -77,7 +77,7 @@ public class LocalMessage extends MimeMessage { catch (Exception e) { if (!"X_BAD_FLAG".equals(flag)) { - Log.w(K9.LOG_TAG, "Unable to parse flag " + flag); + Timber.w("Unable to parse flag %s", flag); } } } @@ -129,7 +129,7 @@ public class LocalMessage extends MimeMessage { if (header != null) { MessageHeaderParser.parse(this, new ByteArrayInputStream(header)); } else { - Log.d(K9.LOG_TAG, "No headers available for this message!"); + Timber.d("No headers available for this message!"); } headerNeedsUpdating = false; diff --git a/k9mail/src/main/java/com/fsck/k9/mailstore/LocalStore.java b/k9mail/src/main/java/com/fsck/k9/mailstore/LocalStore.java index 931ce494a..c1aa977e9 100644 --- a/k9mail/src/main/java/com/fsck/k9/mailstore/LocalStore.java +++ b/k9mail/src/main/java/com/fsck/k9/mailstore/LocalStore.java @@ -29,7 +29,7 @@ import android.database.sqlite.SQLiteDatabase; import android.net.Uri; import android.support.annotation.Nullable; import android.text.TextUtils; -import android.util.Log; +import timber.log.Timber; import com.fsck.k9.Account; import com.fsck.k9.K9; @@ -249,7 +249,7 @@ public class LocalStore extends Store implements Serializable { try { removeInstance(account); } catch (Exception e) { - Log.e(K9.LOG_TAG, "Failed to reset local store for account " + account.getUuid(), e); + Timber.e(e, "Failed to reset local store for account %s", account.getUuid()); } } @@ -301,8 +301,9 @@ public class LocalStore extends Store implements Serializable { } public void compact() throws MessagingException { - if (K9.DEBUG) - Log.i(K9.LOG_TAG, "Before compaction size = " + getSize()); + if (K9.isDebug()) { + Timber.i("Before compaction size = %d", getSize()); + } database.execute(false, new DbCallback() { @Override @@ -311,23 +312,25 @@ public class LocalStore extends Store implements Serializable { return null; } }); - if (K9.DEBUG) - Log.i(K9.LOG_TAG, "After compaction size = " + getSize()); + + if (K9.isDebug()) { + Timber.i("After compaction size = %d", getSize()); + } } public void clear() throws MessagingException { - if (K9.DEBUG) - Log.i(K9.LOG_TAG, "Before prune size = " + getSize()); + if (K9.isDebug()) { + Timber.i("Before prune size = %d", getSize()); + } deleteAllMessageDataFromDisk(); - if (K9.DEBUG) { - Log.i(K9.LOG_TAG, "After prune / before compaction size = " + getSize()); - Log.i(K9.LOG_TAG, "Before clear folder count = " + getFolderCount()); - Log.i(K9.LOG_TAG, "Before clear message count = " + getMessageCount()); - - Log.i(K9.LOG_TAG, "After prune / before clear size = " + getSize()); + if (K9.isDebug()) { + Timber.i("After prune / before compaction size = %d", getSize()); + Timber.i("Before clear folder count = %d", getFolderCount()); + Timber.i("Before clear message count = %d", getMessageCount()); + Timber.i("After prune / before clear size = %d", getSize()); } database.execute(false, new DbCallback() { @@ -349,10 +352,9 @@ public class LocalStore extends Store implements Serializable { compact(); - if (K9.DEBUG) { - Log.i(K9.LOG_TAG, "After clear message count = " + getMessageCount()); - - Log.i(K9.LOG_TAG, "After clear size = " + getSize()); + if (K9.isDebug()) { + Timber.i("After clear message count = %d", getMessageCount()); + Timber.i("After clear size = %d", getSize()); } } @@ -582,9 +584,7 @@ public class LocalStore extends Store implements Serializable { ((!TextUtils.isEmpty(where)) ? " AND (" + where + ")" : "") + " ORDER BY date DESC"; - if (K9.DEBUG) { - Log.d(K9.LOG_TAG, "Query = " + sqlQuery); - } + Timber.d("Query = %s", sqlQuery); return getMessages(retrievalListener, null, sqlQuery, selectionArgs); } @@ -631,7 +631,7 @@ public class LocalStore extends Store implements Serializable { i++; } } catch (Exception e) { - Log.d(K9.LOG_TAG, "Got an exception", e); + Timber.d(e, "Got an exception"); } finally { Utility.closeQuietly(cursor); } diff --git a/k9mail/src/main/java/com/fsck/k9/mailstore/LockableDatabase.java b/k9mail/src/main/java/com/fsck/k9/mailstore/LockableDatabase.java index f7a05d3eb..2c7d3b727 100644 --- a/k9mail/src/main/java/com/fsck/k9/mailstore/LockableDatabase.java +++ b/k9mail/src/main/java/com/fsck/k9/mailstore/LockableDatabase.java @@ -10,12 +10,15 @@ import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import android.os.Build; -import android.util.Log; +import timber.log.Timber; import com.fsck.k9.K9; import com.fsck.k9.helper.FileHelper; import com.fsck.k9.mail.MessagingException; +import static java.lang.System.currentTimeMillis; + + public class LockableDatabase { /** @@ -72,9 +75,7 @@ public class LockableDatabase { return; } - if (K9.DEBUG) { - Log.d(K9.LOG_TAG, "LockableDatabase: Closing DB " + uUid + " due to unmount event on StorageProvider: " + providerId); - } + Timber.d("LockableDatabase: Closing DB %s due to unmount event on StorageProvider: %s", uUid, providerId); try { lockWrite(); @@ -84,7 +85,7 @@ public class LockableDatabase { unlockWrite(); } } catch (UnavailableStorageException e) { - Log.w(K9.LOG_TAG, "Unable to writelock on unmount", e); + Timber.w(e, "Unable to writelock on unmount"); } } @@ -94,14 +95,12 @@ public class LockableDatabase { return; } - if (K9.DEBUG) { - Log.d(K9.LOG_TAG, "LockableDatabase: Opening DB " + uUid + " due to mount event on StorageProvider: " + providerId); - } + Timber.d("LockableDatabase: Opening DB %s due to mount event on StorageProvider: %s", uUid, providerId); try { openOrCreateDataspace(); } catch (UnavailableStorageException e) { - Log.e(K9.LOG_TAG, "Unable to open DB on mount", e); + Timber.e(e, "Unable to open DB on mount"); } } } @@ -266,7 +265,7 @@ public class LockableDatabase { lockRead(); final boolean doTransaction = transactional && inTransaction.get() == null; try { - final boolean debug = K9.DEBUG; + final boolean debug = K9.isDebug(); if (doTransaction) { inTransaction.set(Boolean.TRUE); mDb.beginTransaction(); @@ -288,7 +287,9 @@ public class LockableDatabase { // not doing endTransaction in the same 'finally' block of unlockRead() because endTransaction() may throw an exception mDb.endTransaction(); if (debug) { - Log.v(K9.LOG_TAG, "LockableDatabase: Transaction ended, took " + Long.toString(System.currentTimeMillis() - begin) + "ms / " + new Exception().getStackTrace()[1].toString()); + Timber.v("LockableDatabase: Transaction ended, took %d ms / %s", + currentTimeMillis() - begin, + new Exception().getStackTrace()[1]); } } } @@ -307,7 +308,7 @@ public class LockableDatabase { */ public void switchProvider(final String newProviderId) throws MessagingException { if (newProviderId.equals(mStorageProviderId)) { - Log.v(K9.LOG_TAG, "LockableDatabase: Ignoring provider switch request as they are equal: " + newProviderId); + Timber.v("LockableDatabase: Ignoring provider switch request as they are equal: %s", newProviderId); return; } @@ -319,7 +320,7 @@ public class LockableDatabase { try { mDb.close(); } catch (Exception e) { - Log.i(K9.LOG_TAG, "Unable to close DB on local store migration", e); + Timber.i(e, "Unable to close DB on local store migration"); } final StorageManager storageManager = getStorageManager(); @@ -371,9 +372,9 @@ public class LockableDatabase { doOpenOrCreateDb(databaseFile); } catch (SQLiteException e) { // TODO handle this error in a better way! - Log.w(K9.LOG_TAG, "Unable to open DB " + databaseFile + " - removing file and retrying", e); + Timber.w(e, "Unable to open DB %s - removing file and retrying", databaseFile); if (databaseFile.exists() && !databaseFile.delete()) { - Log.d(K9.LOG_TAG, "Failed to remove " + databaseFile + " that couldn't be opened"); + Timber.d("Failed to remove %s that couldn't be opened", databaseFile); } doOpenOrCreateDb(databaseFile); } @@ -458,8 +459,7 @@ public class LockableDatabase { try { mDb.close(); } catch (Exception e) { - if (K9.DEBUG) - Log.d(K9.LOG_TAG, "Exception caught in DB close: " + e.getMessage()); + Timber.d("Exception caught in DB close: %s", e.getMessage()); } final StorageManager storageManager = getStorageManager(); try { @@ -468,25 +468,24 @@ public class LockableDatabase { for (File attachment : attachments) { if (attachment.exists()) { boolean attachmentWasDeleted = attachment.delete(); - if (!attachmentWasDeleted && K9.DEBUG) { - Log.d(K9.LOG_TAG, "Attachment was not deleted!"); + if (!attachmentWasDeleted) { + Timber.d("Attachment was not deleted!"); } } } if (attachmentDirectory.exists()) { boolean attachmentDirectoryWasDeleted = attachmentDirectory.delete(); - if (!attachmentDirectoryWasDeleted && K9.DEBUG) { - Log.d(K9.LOG_TAG, "Attachment directory was not deleted!"); + if (!attachmentDirectoryWasDeleted) { + Timber.d("Attachment directory was not deleted!"); } } } catch (Exception e) { - if (K9.DEBUG) - Log.d(K9.LOG_TAG, "Exception caught in clearing attachments: " + e.getMessage()); + Timber.d("Exception caught in clearing attachments: %s", e.getMessage()); } try { deleteDatabase(storageManager.getDatabase(uUid, mStorageProviderId)); } catch (Exception e) { - Log.i(K9.LOG_TAG, "LockableDatabase: delete(): Unable to delete backing DB file", e); + Timber.i(e, "LockableDatabase: delete(): Unable to delete backing DB file"); } if (recreate) { @@ -510,8 +509,7 @@ public class LockableDatabase { deleted |= new File(database.getPath() + "-journal").delete(); } if (!deleted) { - Log.i(K9.LOG_TAG, - "LockableDatabase: deleteDatabase(): No files deleted."); + Timber.i("LockableDatabase: deleteDatabase(): No files deleted."); } } } diff --git a/k9mail/src/main/java/com/fsck/k9/mailstore/MessageViewInfoExtractor.java b/k9mail/src/main/java/com/fsck/k9/mailstore/MessageViewInfoExtractor.java index 88c2bb5bb..ff72e52c8 100644 --- a/k9mail/src/main/java/com/fsck/k9/mailstore/MessageViewInfoExtractor.java +++ b/k9mail/src/main/java/com/fsck/k9/mailstore/MessageViewInfoExtractor.java @@ -10,7 +10,7 @@ import android.content.Context; import android.support.annotation.Nullable; import android.support.annotation.VisibleForTesting; import android.support.annotation.WorkerThread; -import android.util.Log; +import timber.log.Timber; import com.fsck.k9.Globals; import com.fsck.k9.K9; @@ -82,7 +82,7 @@ public class MessageViewInfoExtractor { extraParts = cryptoMessageParts.extraParts; } else { if (annotations != null && !annotations.isEmpty()) { - Log.e(K9.LOG_TAG, "Got message annotations but no crypto root part!"); + Timber.e("Got message annotations but no crypto root part!"); } rootPart = message; cryptoResultAnnotation = null; diff --git a/k9mail/src/main/java/com/fsck/k9/mailstore/StorageManager.java b/k9mail/src/main/java/com/fsck/k9/mailstore/StorageManager.java index b476e0c13..5fa8dbb11 100644 --- a/k9mail/src/main/java/com/fsck/k9/mailstore/StorageManager.java +++ b/k9mail/src/main/java/com/fsck/k9/mailstore/StorageManager.java @@ -15,7 +15,7 @@ import java.util.concurrent.locks.ReentrantReadWriteLock; import android.content.Context; import android.os.Build; import android.os.Environment; -import android.util.Log; +import timber.log.Timber; import com.fsck.k9.K9; import com.fsck.k9.R; @@ -204,7 +204,7 @@ public class StorageManager { return isMountPoint(root) && Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()); } catch (IOException e) { - Log.w(K9.LOG_TAG, "Specified root isn't ready: " + mRoot, e); + Timber.w(e, "Specified root isn't ready: %s", mRoot); return false; } } @@ -608,7 +608,7 @@ public class StorageManager { public boolean isReady(final String providerId) { StorageProvider provider = getProvider(providerId); if (provider == null) { - Log.w(K9.LOG_TAG, "Storage-Provider \"" + providerId + "\" does not exist"); + Timber.w("Storage-Provider \"%s\" does not exist", providerId); return false; } return provider.isReady(context); @@ -632,7 +632,7 @@ public class StorageManager { * @param path */ public void onBeforeUnmount(final String path) { - Log.i(K9.LOG_TAG, "storage path \"" + path + "\" unmounting"); + Timber.i("storage path \"%s\" unmounting", path); final StorageProvider provider = resolveProvider(path); if (provider == null) { return; @@ -641,7 +641,7 @@ public class StorageManager { try { listener.onUnmount(provider.getId()); } catch (Exception e) { - Log.w(K9.LOG_TAG, "Error while notifying StorageListener", e); + Timber.w(e, "Error while notifying StorageListener"); } } final SynchronizationAid sync = mProviderLocks.get(resolveProvider(path)); @@ -651,7 +651,7 @@ public class StorageManager { } public void onAfterUnmount(final String path) { - Log.i(K9.LOG_TAG, "storage path \"" + path + "\" unmounted"); + Timber.i("storage path \"%s\" unmounted", path); final StorageProvider provider = resolveProvider(path); if (provider == null) { return; @@ -669,7 +669,7 @@ public class StorageManager { * @param readOnly */ public void onMount(final String path, final boolean readOnly) { - Log.i(K9.LOG_TAG, "storage path \"" + path + "\" mounted readOnly=" + readOnly); + Timber.i("storage path \"%s\" mounted readOnly=%s", path, readOnly); if (readOnly) { return; } @@ -682,7 +682,7 @@ public class StorageManager { try { listener.onMount(provider.getId()); } catch (Exception e) { - Log.w(K9.LOG_TAG, "Error while notifying StorageListener", e); + Timber.w(e, "Error while notifying StorageListener"); } } diff --git a/k9mail/src/main/java/com/fsck/k9/mailstore/StoreSchemaDefinition.java b/k9mail/src/main/java/com/fsck/k9/mailstore/StoreSchemaDefinition.java index 7737c6112..3dd4ae1ca 100644 --- a/k9mail/src/main/java/com/fsck/k9/mailstore/StoreSchemaDefinition.java +++ b/k9mail/src/main/java/com/fsck/k9/mailstore/StoreSchemaDefinition.java @@ -6,7 +6,7 @@ import java.util.Locale; import android.content.Context; import android.database.sqlite.SQLiteDatabase; -import android.util.Log; +import timber.log.Timber; import com.fsck.k9.Account; import com.fsck.k9.BuildConfig; @@ -17,6 +17,10 @@ import com.fsck.k9.mailstore.migrations.Migrations; import com.fsck.k9.mailstore.migrations.MigrationsHelper; import com.fsck.k9.preferences.Storage; +import static com.fsck.k9.mailstore.LocalStore.DB_VERSION; +import static java.lang.String.format; +import static java.util.Locale.US; + class StoreSchemaDefinition implements LockableDatabase.SchemaDefinition { private final LocalStore localStore; @@ -40,15 +44,14 @@ class StoreSchemaDefinition implements LockableDatabase.SchemaDefinition { throw new Error("Exception while upgrading database", e); } - Log.e(K9.LOG_TAG, "Exception while upgrading database. Resetting the DB to v0", e); + Timber.e(e, "Exception while upgrading database. Resetting the DB to v0"); db.setVersion(0); upgradeDatabase(db); } } private void upgradeDatabase(final SQLiteDatabase db) { - Log.i(K9.LOG_TAG, String.format(Locale.US, "Upgrading database from version %d to version %d", - db.getVersion(), LocalStore.DB_VERSION)); + Timber.i("Upgrading database from version %d to version %d", db.getVersion(), DB_VERSION); db.beginTransaction(); try { diff --git a/k9mail/src/main/java/com/fsck/k9/mailstore/migrations/MigrationTo35.java b/k9mail/src/main/java/com/fsck/k9/mailstore/migrations/MigrationTo35.java index 196d0209f..ddda3ea4b 100644 --- a/k9mail/src/main/java/com/fsck/k9/mailstore/migrations/MigrationTo35.java +++ b/k9mail/src/main/java/com/fsck/k9/mailstore/migrations/MigrationTo35.java @@ -3,7 +3,7 @@ package com.fsck.k9.mailstore.migrations; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; -import android.util.Log; +import timber.log.Timber; import com.fsck.k9.K9; @@ -13,7 +13,7 @@ class MigrationTo35 { try { db.execSQL("update messages set flags = replace(flags, 'X_NO_SEEN_INFO', 'X_BAD_FLAG')"); } catch (SQLiteException e) { - Log.e(K9.LOG_TAG, "Unable to get rid of obsolete flag X_NO_SEEN_INFO", e); + Timber.e(e, "Unable to get rid of obsolete flag X_NO_SEEN_INFO"); } } } diff --git a/k9mail/src/main/java/com/fsck/k9/mailstore/migrations/MigrationTo36.java b/k9mail/src/main/java/com/fsck/k9/mailstore/migrations/MigrationTo36.java index 20a3736f4..261327377 100644 --- a/k9mail/src/main/java/com/fsck/k9/mailstore/migrations/MigrationTo36.java +++ b/k9mail/src/main/java/com/fsck/k9/mailstore/migrations/MigrationTo36.java @@ -3,7 +3,7 @@ package com.fsck.k9.mailstore.migrations; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; -import android.util.Log; +import timber.log.Timber; import com.fsck.k9.K9; @@ -13,7 +13,7 @@ class MigrationTo36 { try { db.execSQL("ALTER TABLE attachments ADD content_id TEXT"); } catch (SQLiteException e) { - Log.e(K9.LOG_TAG, "Unable to add content_id column to attachments"); + Timber.e("Unable to add content_id column to attachments"); } } } diff --git a/k9mail/src/main/java/com/fsck/k9/mailstore/migrations/MigrationTo37.java b/k9mail/src/main/java/com/fsck/k9/mailstore/migrations/MigrationTo37.java index 17cef82e4..5fc7319d0 100644 --- a/k9mail/src/main/java/com/fsck/k9/mailstore/migrations/MigrationTo37.java +++ b/k9mail/src/main/java/com/fsck/k9/mailstore/migrations/MigrationTo37.java @@ -3,7 +3,7 @@ package com.fsck.k9.mailstore.migrations; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; -import android.util.Log; +import timber.log.Timber; import com.fsck.k9.K9; @@ -13,7 +13,7 @@ class MigrationTo37 { try { db.execSQL("ALTER TABLE attachments ADD content_disposition TEXT"); } catch (SQLiteException e) { - Log.e(K9.LOG_TAG, "Unable to add content_disposition column to attachments"); + Timber.e("Unable to add content_disposition column to attachments"); } } } diff --git a/k9mail/src/main/java/com/fsck/k9/mailstore/migrations/MigrationTo39.java b/k9mail/src/main/java/com/fsck/k9/mailstore/migrations/MigrationTo39.java index e37b44250..ea6b101cb 100644 --- a/k9mail/src/main/java/com/fsck/k9/mailstore/migrations/MigrationTo39.java +++ b/k9mail/src/main/java/com/fsck/k9/mailstore/migrations/MigrationTo39.java @@ -3,7 +3,7 @@ package com.fsck.k9.mailstore.migrations; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; -import android.util.Log; +import timber.log.Timber; import com.fsck.k9.K9; @@ -13,7 +13,7 @@ class MigrationTo39 { try { db.execSQL("DELETE FROM headers WHERE id in (SELECT headers.id FROM headers LEFT JOIN messages ON headers.message_id = messages.id WHERE messages.id IS NULL)"); } catch (SQLiteException e) { - Log.e(K9.LOG_TAG, "Unable to remove extra header data from the database"); + Timber.e("Unable to remove extra header data from the database"); } } } diff --git a/k9mail/src/main/java/com/fsck/k9/mailstore/migrations/MigrationTo40.java b/k9mail/src/main/java/com/fsck/k9/mailstore/migrations/MigrationTo40.java index 8bcfef611..9c4253d8d 100644 --- a/k9mail/src/main/java/com/fsck/k9/mailstore/migrations/MigrationTo40.java +++ b/k9mail/src/main/java/com/fsck/k9/mailstore/migrations/MigrationTo40.java @@ -3,7 +3,7 @@ package com.fsck.k9.mailstore.migrations; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; -import android.util.Log; +import timber.log.Timber; import com.fsck.k9.K9; @@ -13,7 +13,7 @@ class MigrationTo40 { try { db.execSQL("ALTER TABLE messages ADD mime_type TEXT"); } catch (SQLiteException e) { - Log.e(K9.LOG_TAG, "Unable to add mime_type column to messages"); + Timber.e("Unable to add mime_type column to messages"); } } } diff --git a/k9mail/src/main/java/com/fsck/k9/mailstore/migrations/MigrationTo41.java b/k9mail/src/main/java/com/fsck/k9/mailstore/migrations/MigrationTo41.java index 05c76282d..95f82eadb 100644 --- a/k9mail/src/main/java/com/fsck/k9/mailstore/migrations/MigrationTo41.java +++ b/k9mail/src/main/java/com/fsck/k9/mailstore/migrations/MigrationTo41.java @@ -4,7 +4,7 @@ package com.fsck.k9.mailstore.migrations; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; -import android.util.Log; +import timber.log.Timber; import com.fsck.k9.Account; import com.fsck.k9.K9; @@ -38,11 +38,11 @@ class MigrationTo41 { String name = cursor.getString(1); update41Metadata(db, migrationsHelper, id, name); } catch (Exception e) { - Log.e(K9.LOG_TAG, " error trying to ugpgrade a folder class", e); + Timber.e(e, " error trying to ugpgrade a folder class"); } } } catch (SQLiteException e) { - Log.e(K9.LOG_TAG, "Exception while upgrading database to v41. folder classes may have vanished", e); + Timber.e(e, "Exception while upgrading database to v41. folder classes may have vanished"); } finally { Utility.closeQuietly(cursor); } @@ -73,7 +73,7 @@ class MigrationTo41 { inTopGroup = storage.getBoolean(accountUuid + "." + name + ".inTopGroup", inTopGroup); integrate = storage.getBoolean(accountUuid + "." + name + ".integrate", integrate); } catch (Exception e) { - Log.e(K9.LOG_TAG, " Throwing away an error while trying to upgrade folder metadata", e); + Timber.e(e, " Throwing away an error while trying to upgrade folder metadata"); } if (displayClass == Folder.FolderClass.NONE) { diff --git a/k9mail/src/main/java/com/fsck/k9/mailstore/migrations/MigrationTo42.java b/k9mail/src/main/java/com/fsck/k9/mailstore/migrations/MigrationTo42.java index c723eb63a..91de7e230 100644 --- a/k9mail/src/main/java/com/fsck/k9/mailstore/migrations/MigrationTo42.java +++ b/k9mail/src/main/java/com/fsck/k9/mailstore/migrations/MigrationTo42.java @@ -3,7 +3,7 @@ package com.fsck.k9.mailstore.migrations; import java.util.List; -import android.util.Log; +import timber.log.Timber; import com.fsck.k9.K9; import com.fsck.k9.mail.Folder; @@ -32,10 +32,10 @@ class MigrationTo42 { editor.commit(); long endTime = System.currentTimeMillis(); - Log.i(K9.LOG_TAG, "Putting folder preferences for " + folders.size() + - " folders back into Preferences took " + (endTime - startTime) + " ms"); + Timber.i("Putting folder preferences for %d folders back into Preferences took %d ms", + folders.size(), endTime - startTime); } catch (Exception e) { - Log.e(K9.LOG_TAG, "Could not replace Preferences in upgrade from DB_VERSION 41", e); + Timber.e(e, "Could not replace Preferences in upgrade from DB_VERSION 41"); } } } diff --git a/k9mail/src/main/java/com/fsck/k9/mailstore/migrations/MigrationTo43.java b/k9mail/src/main/java/com/fsck/k9/mailstore/migrations/MigrationTo43.java index d8f00fd6c..c0566ed7a 100644 --- a/k9mail/src/main/java/com/fsck/k9/mailstore/migrations/MigrationTo43.java +++ b/k9mail/src/main/java/com/fsck/k9/mailstore/migrations/MigrationTo43.java @@ -7,7 +7,7 @@ import android.content.ContentValues; import android.content.Context; import android.content.SharedPreferences; import android.database.sqlite.SQLiteDatabase; -import android.util.Log; +import timber.log.Timber; import com.fsck.k9.Account; import com.fsck.k9.K9; @@ -17,6 +17,8 @@ import com.fsck.k9.mail.Message; import com.fsck.k9.mailstore.LocalFolder; import com.fsck.k9.mailstore.LocalStore; +import static com.fsck.k9.Account.OUTBOX; + class MigrationTo43 { public static void fixOutboxFolders(SQLiteDatabase db, MigrationsHelper migrationsHelper) { @@ -32,7 +34,7 @@ class MigrationTo43 { ContentValues cv = new ContentValues(); cv.put("name", Account.OUTBOX); db.update("folders", cv, "name = ?", new String[] { "OUTBOX" }); - Log.i(K9.LOG_TAG, "Renamed folder OUTBOX to " + Account.OUTBOX); + Timber.i("Renamed folder OUTBOX to %s", OUTBOX); } // Check if old (pre v3.800) localized outbox folder exists @@ -54,7 +56,7 @@ class MigrationTo43 { obsoleteOutbox.delete(true); } } catch (Exception e) { - Log.e(K9.LOG_TAG, "Error trying to fix the outbox folders", e); + Timber.e(e, "Error trying to fix the outbox folders"); } } } diff --git a/k9mail/src/main/java/com/fsck/k9/mailstore/migrations/MigrationTo51.java b/k9mail/src/main/java/com/fsck/k9/mailstore/migrations/MigrationTo51.java index b46997566..65f0769ab 100644 --- a/k9mail/src/main/java/com/fsck/k9/mailstore/migrations/MigrationTo51.java +++ b/k9mail/src/main/java/com/fsck/k9/mailstore/migrations/MigrationTo51.java @@ -17,7 +17,7 @@ import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.annotation.VisibleForTesting; import android.text.TextUtils; -import android.util.Log; +import timber.log.Timber; import com.fsck.k9.Account; import com.fsck.k9.K9; @@ -73,7 +73,7 @@ class MigrationTo51 { new String[] { "id", "flags", "html_content", "text_content", "mime_type", "attachment_count" }, null, null, null, null, null); try { - Log.d(K9.LOG_TAG, "migrating " + msgCursor.getCount() + " messages"); + Timber.d("migrating %d messages", msgCursor.getCount()); ContentValues cv = new ContentValues(); while (msgCursor.moveToNext()) { long messageId = msgCursor.getLong(0); @@ -124,7 +124,7 @@ class MigrationTo51 { cv.put("attachment_count", attachmentCount); db.update("messages", cv, "id = ?", new String[] { Long.toString(messageId) }); } catch (IOException e) { - Log.e(K9.LOG_TAG, "error inserting into database", e); + Timber.e(e, "error inserting into database"); } } @@ -144,18 +144,18 @@ class MigrationTo51 { boolean moveOk = attachmentDirNew.renameTo(attachmentDirOld); if (!moveOk) { // TODO escalate? - Log.e(K9.LOG_TAG, "Error moving attachment dir! All attachments might be lost!"); + Timber.e("Error moving attachment dir! All attachments might be lost!"); } boolean mkdirOk = attachmentDirNew.mkdir(); if (!mkdirOk) { // TODO escalate? - Log.e(K9.LOG_TAG, "Error creating new attachment dir!"); + Timber.e("Error creating new attachment dir!"); } return attachmentDirOld; } private static void dropOldMessagesTable(SQLiteDatabase db) { - Log.d(K9.LOG_TAG, "Migration succeeded, dropping old tables."); + Timber.d("Migration succeeded, dropping old tables."); db.execSQL("DROP TABLE messages_old"); db.execSQL("DROP TABLE attachments"); db.execSQL("DROP TABLE headers"); @@ -163,19 +163,19 @@ class MigrationTo51 { private static void cleanUpOldAttachmentDirectory(File attachmentDirOld) { if (!attachmentDirOld.exists()) { - Log.d(K9.LOG_TAG, "Old attachment directory doesn't exist: " + attachmentDirOld.getAbsolutePath()); + Timber.d("Old attachment directory doesn't exist: %s", attachmentDirOld.getAbsolutePath()); return; } for (File file : attachmentDirOld.listFiles()) { - Log.d(K9.LOG_TAG, "deleting stale attachment file: " + file.getName()); + Timber.d("deleting stale attachment file: %s", file.getName()); if (file.exists() && !file.delete()) { - Log.d(K9.LOG_TAG, "Failed to delete stale attachement file: " + file.getAbsolutePath()); + Timber.d("Failed to delete stale attachement file: %s", file.getAbsolutePath()); } } - Log.d(K9.LOG_TAG, "deleting old attachment directory"); + Timber.d("deleting old attachment directory"); if (attachmentDirOld.exists() && !attachmentDirOld.delete()) { - Log.d(K9.LOG_TAG, "Failed to delete old attachement directory: " + attachmentDirOld.getAbsolutePath()); + Timber.d("Failed to delete old attachement directory: %s", attachmentDirOld.getAbsolutePath()); } } @@ -255,7 +255,7 @@ class MigrationTo51 { private static MimeStructureState migratePgpMimeEncryptedContent(SQLiteDatabase db, long messageId, File attachmentDirOld, File attachmentDirNew, MimeHeader mimeHeader, MimeStructureState structureState) { - Log.d(K9.LOG_TAG, "Attempting to migrate multipart/encrypted as pgp/mime"); + Timber.d("Attempting to migrate multipart/encrypted as pgp/mime"); // we only handle attachment count == 2 here, so simply sorting application/pgp-encrypted // to the front (and application/octet-stream second) should suffice. @@ -269,7 +269,7 @@ class MigrationTo51 { try { if (cursor.getCount() != 2) { - Log.e(K9.LOG_TAG, "Found multipart/encrypted but bad number of attachments, handling as regular mail"); + Timber.e("Found multipart/encrypted but bad number of attachments, handling as regular mail"); return null; } @@ -283,8 +283,8 @@ class MigrationTo51 { String firstPartContentUriString = cursor.getString(5); if (!MimeUtil.isSameMimeType(firstPartMimeType, "application/pgp-encrypted")) { - Log.e(K9.LOG_TAG, - "First part in multipart/encrypted wasn't application/pgp-encrypted, not handling as pgp/mime"); + Timber.e("First part in multipart/encrypted wasn't application/pgp-encrypted, " + + "not handling as pgp/mime"); return null; } @@ -298,8 +298,7 @@ class MigrationTo51 { String secondPartContentUriString = cursor.getString(5); if (!MimeUtil.isSameMimeType(secondPartMimeType, "application/octet-stream")) { - Log.e(K9.LOG_TAG, - "First part in multipart/encrypted wasn't application/octet-stream, not handling as pgp/mime"); + Timber.e("First part in multipart/encrypted wasn't application/octet-stream, not handling as pgp/mime"); return null; } @@ -342,7 +341,7 @@ class MigrationTo51 { private static MimeStructureState migrateComplexMailContent(SQLiteDatabase db, File attachmentDirOld, File attachmentDirNew, long messageId, String htmlContent, String textContent, MimeHeader mimeHeader, MimeStructureState structureState) throws IOException { - Log.d(K9.LOG_TAG, "Processing mail with complex data structure as multipart/mixed"); + Timber.d("Processing mail with complex data structure as multipart/mixed"); String boundary = MimeUtility.getHeaderParameter( mimeHeader.getFirstHeader(MimeHeader.HEADER_CONTENT_TYPE), "boundary"); @@ -403,7 +402,7 @@ class MigrationTo51 { private static MimeStructureState migrateSimpleMailContent(SQLiteDatabase db, String htmlContent, String textContent, String mimeType, MimeHeader mimeHeader, MimeStructureState structureState) throws IOException { - Log.d(K9.LOG_TAG, "Processing mail with simple structure"); + Timber.d("Processing mail with simple structure"); if (MimeUtil.isSameMimeType(mimeType, "text/plain")) { return insertTextualPartIntoDatabase(db, structureState, mimeHeader, textContent, false); @@ -451,10 +450,13 @@ class MigrationTo51 { private static MimeStructureState insertMimeAttachmentPart(SQLiteDatabase db, File attachmentDirOld, File attachmentDirNew, MimeStructureState structureState, long id, int size, String name, String mimeType, String storeData, String contentUriString, String contentId, String contentDisposition) { - if (K9.DEBUG) { - Log.d(K9.LOG_TAG, "processing attachment " + id + ", " + name + ", " - + mimeType + ", " + storeData + ", " + contentUriString); - } + + Timber.d("processing attachment %d, %s, %s, %s, %s", + id, + name, + mimeType, + storeData, + contentUriString); if (contentDisposition == null) { contentDisposition = "attachment"; @@ -483,10 +485,10 @@ class MigrationTo51 { boolean isExistingAttachmentFile = attachmentFile.exists(); if (!isMatchingAttachmentId) { - Log.e(K9.LOG_TAG, "mismatched attachment id. mark as missing"); + Timber.e("mismatched attachment id. mark as missing"); attachmentFileToMove = null; } else if (!isExistingAttachmentFile) { - Log.e(K9.LOG_TAG, "attached file doesn't exist. mark as missing"); + Timber.e("attached file doesn't exist. mark as missing"); attachmentFileToMove = null; } else { attachmentFileToMove = attachmentFile; @@ -498,8 +500,8 @@ class MigrationTo51 { } else { attachmentFileToMove = null; } - if (K9.DEBUG && attachmentFileToMove == null) { - Log.d(K9.LOG_TAG, "matching attachment is in local cache"); + if (attachmentFileToMove == null) { + Timber.d("matching attachment is in local cache"); } boolean hasContentTypeAndIsInline = !TextUtils.isEmpty(contentId) && "inline".equalsIgnoreCase(contentDisposition); @@ -524,7 +526,7 @@ class MigrationTo51 { if (attachmentFileToMove != null) { boolean moveOk = attachmentFileToMove.renameTo(new File(attachmentDirNew, Long.toString(partId))); if (!moveOk) { - Log.e(K9.LOG_TAG, "Moving attachment to new dir failed!"); + Timber.e("Moving attachment to new dir failed!"); } } return structureState; diff --git a/k9mail/src/main/java/com/fsck/k9/mailstore/migrations/MigrationTo55.java b/k9mail/src/main/java/com/fsck/k9/mailstore/migrations/MigrationTo55.java index e9fb197ab..849630bfc 100644 --- a/k9mail/src/main/java/com/fsck/k9/mailstore/migrations/MigrationTo55.java +++ b/k9mail/src/main/java/com/fsck/k9/mailstore/migrations/MigrationTo55.java @@ -7,7 +7,7 @@ import java.util.List; import android.content.ContentValues; import android.database.sqlite.SQLiteDatabase; import android.text.TextUtils; -import android.util.Log; +import timber.log.Timber; import com.fsck.k9.K9; import com.fsck.k9.mail.FetchProfile; @@ -38,18 +38,18 @@ class MigrationTo55 { String fulltext = fulltextCreator.createFulltext(localMessage); if (!TextUtils.isEmpty(fulltext)) { - Log.d(K9.LOG_TAG, "fulltext for msg id " + localMessage.getId() + " is " + fulltext.length() + " chars long"); + Timber.d("fulltext for msg id %d is %d chars long", localMessage.getId(), fulltext.length()); cv.clear(); cv.put("docid", localMessage.getId()); cv.put("fulltext", fulltext); db.insert("messages_fulltext", null, cv); } else { - Log.d(K9.LOG_TAG, "no fulltext for msg id " + localMessage.getId() + " :("); + Timber.d("no fulltext for msg id %d :(", localMessage.getId()); } } } } catch (MessagingException e) { - Log.e(K9.LOG_TAG, "error indexing fulltext - skipping rest, fts index is incomplete!", e); + Timber.e(e, "error indexing fulltext - skipping rest, fts index is incomplete!"); } } } diff --git a/k9mail/src/main/java/com/fsck/k9/message/IdentityHeaderBuilder.java b/k9mail/src/main/java/com/fsck/k9/message/IdentityHeaderBuilder.java index 256a3595b..343f957bd 100644 --- a/k9mail/src/main/java/com/fsck/k9/message/IdentityHeaderBuilder.java +++ b/k9mail/src/main/java/com/fsck/k9/message/IdentityHeaderBuilder.java @@ -3,7 +3,7 @@ package com.fsck.k9.message; import android.net.Uri; import android.net.Uri.Builder; -import android.util.Log; +import timber.log.Timber; import com.fsck.k9.Account.QuoteStyle; import com.fsck.k9.Identity; @@ -97,10 +97,7 @@ public class IdentityHeaderBuilder { String k9identity = IdentityField.IDENTITY_VERSION_1 + uri.build().getEncodedQuery(); - if (K9.DEBUG) { - Log.d(K9.LOG_TAG, "Generated identity: " + k9identity); - } - + Timber.d("Generated identity: %s", k9identity); return k9identity; } diff --git a/k9mail/src/main/java/com/fsck/k9/message/IdentityHeaderParser.java b/k9mail/src/main/java/com/fsck/k9/message/IdentityHeaderParser.java index 873a3e728..8669bb434 100644 --- a/k9mail/src/main/java/com/fsck/k9/message/IdentityHeaderParser.java +++ b/k9mail/src/main/java/com/fsck/k9/message/IdentityHeaderParser.java @@ -6,7 +6,7 @@ import java.util.Map; import java.util.StringTokenizer; import android.net.Uri; -import android.util.Log; +import timber.log.Timber; import com.fsck.k9.K9; import com.fsck.k9.mail.filter.Base64; @@ -24,9 +24,7 @@ public class IdentityHeaderParser { public static Map parse(final String identityString) { Map identity = new HashMap(); - if (K9.DEBUG) { - Log.d(K9.LOG_TAG, "Decoding identity: " + identityString); - } + Timber.d("Decoding identity: %s", identityString); if (identityString == null || identityString.length() < 1) { return identity; @@ -44,9 +42,7 @@ public class IdentityHeaderParser { } } - if (K9.DEBUG) { - Log.d(K9.LOG_TAG, "Decoded identity: " + identity.toString()); - } + Timber.d("Decoded identity: %s", identity); // Sanity check our Integers so that recipients of this result don't have to. for (IdentityField key : IdentityField.getIntegerFields()) { @@ -54,16 +50,15 @@ public class IdentityHeaderParser { try { Integer.parseInt(identity.get(key)); } catch (NumberFormatException e) { - Log.e(K9.LOG_TAG, "Invalid " + key.name() + " field in identity: " + identity.get(key)); + Timber.e("Invalid %s field in identity: %s", key.name(), identity.get(key)); } } } } else { // Legacy identity - if (K9.DEBUG) { - Log.d(K9.LOG_TAG, "Got a saved legacy identity: " + identityString); - } + Timber.d("Got a saved legacy identity: %s", identityString); + StringTokenizer tokenizer = new StringTokenizer(identityString, ":", false); // First item is the body length. We use this to separate the composed reply from the quoted text. @@ -72,7 +67,7 @@ public class IdentityHeaderParser { try { identity.put(IdentityField.LENGTH, Integer.valueOf(bodyLengthS).toString()); } catch (Exception e) { - Log.e(K9.LOG_TAG, "Unable to parse bodyLength '" + bodyLengthS + "'"); + Timber.e("Unable to parse bodyLength '%s'", bodyLengthS); } } if (tokenizer.hasMoreTokens()) { diff --git a/k9mail/src/main/java/com/fsck/k9/message/MessageBuilder.java b/k9mail/src/main/java/com/fsck/k9/message/MessageBuilder.java index 36412ab3e..b8f1f0053 100644 --- a/k9mail/src/main/java/com/fsck/k9/message/MessageBuilder.java +++ b/k9mail/src/main/java/com/fsck/k9/message/MessageBuilder.java @@ -10,7 +10,7 @@ import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.os.AsyncTask; -import android.util.Log; +import timber.log.Timber; import com.fsck.k9.Account.QuoteStyle; import com.fsck.k9.Identity; @@ -585,7 +585,7 @@ public abstract class MessageBuilder { final protected void deliverResult() { synchronized (callbackLock) { if (asyncCallback == null) { - Log.d(K9.LOG_TAG, "Keeping message builder result in queue for later delivery"); + Timber.d("Keeping message builder result in queue for later delivery"); return; } if (queuedMimeMessage != null) { diff --git a/k9mail/src/main/java/com/fsck/k9/message/PgpMessageBuilder.java b/k9mail/src/main/java/com/fsck/k9/message/PgpMessageBuilder.java index bf2cf0872..46366b0b0 100644 --- a/k9mail/src/main/java/com/fsck/k9/message/PgpMessageBuilder.java +++ b/k9mail/src/main/java/com/fsck/k9/message/PgpMessageBuilder.java @@ -11,7 +11,7 @@ import android.content.Intent; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.annotation.VisibleForTesting; -import android.util.Log; +import timber.log.Timber; import com.fsck.k9.Globals; import com.fsck.k9.K9; @@ -218,7 +218,7 @@ public class PgpMessageBuilder extends MessageBuilder { throw new IllegalStateException( "Got opportunistic error, but encryption wasn't supposed to be opportunistic!"); } - Log.d(K9.LOG_TAG, "Skipping encryption due to opportunistic mode"); + Timber.d("Skipping encryption due to opportunistic mode"); return null; } throw new MessagingException(error.getMessage()); @@ -295,7 +295,7 @@ public class PgpMessageBuilder extends MessageBuilder { String micAlgParameter = result.getStringExtra(OpenPgpApi.RESULT_SIGNATURE_MICALG); contentType += String.format("; micalg=\"%s\"", micAlgParameter); } else { - Log.e(K9.LOG_TAG, "missing micalg parameter for pgp multipart/signed!"); + Timber.e("missing micalg parameter for pgp multipart/signed!"); } currentProcessedMimeMessage.setHeader(MimeHeader.HEADER_CONTENT_TYPE, contentType); } diff --git a/k9mail/src/main/java/com/fsck/k9/message/TextBodyBuilder.java b/k9mail/src/main/java/com/fsck/k9/message/TextBodyBuilder.java index 99c6d341c..869333857 100644 --- a/k9mail/src/main/java/com/fsck/k9/message/TextBodyBuilder.java +++ b/k9mail/src/main/java/com/fsck/k9/message/TextBodyBuilder.java @@ -2,7 +2,7 @@ package com.fsck.k9.message; import android.text.TextUtils; -import android.util.Log; +import timber.log.Timber; import com.fsck.k9.K9; import com.fsck.k9.message.html.HtmlConverter; @@ -47,8 +47,8 @@ class TextBodyBuilder { if (mIncludeQuotedText) { InsertableHtmlContent quotedHtmlContent = getQuotedTextHtml(); - if (K9.DEBUG) { - Log.d(K9.LOG_TAG, "insertable: " + quotedHtmlContent.toDebugString()); + if (K9.isDebug()) { + Timber.d("insertable: %s", quotedHtmlContent.toDebugString()); } if (mAppendSignature) { diff --git a/k9mail/src/main/java/com/fsck/k9/message/extractors/AttachmentInfoExtractor.java b/k9mail/src/main/java/com/fsck/k9/message/extractors/AttachmentInfoExtractor.java index 313bea864..76f96d3fb 100644 --- a/k9mail/src/main/java/com/fsck/k9/message/extractors/AttachmentInfoExtractor.java +++ b/k9mail/src/main/java/com/fsck/k9/message/extractors/AttachmentInfoExtractor.java @@ -10,7 +10,7 @@ import android.content.Context; import android.net.Uri; import android.support.annotation.Nullable; import android.support.annotation.VisibleForTesting; -import android.util.Log; +import timber.log.Timber; import android.support.annotation.WorkerThread; import com.fsck.k9.Globals; @@ -99,7 +99,7 @@ public class AttachmentInfoExtractor { uri = DecryptedFileProvider.getUriForProvidedFile( context, file, decryptedTempFileBody.getEncoding(), mimeType); } catch (IOException e) { - Log.e(K9.LOG_TAG, "Decrypted temp file (no longer?) exists!", e); + Timber.e(e, "Decrypted temp file (no longer?) exists!"); uri = null; } return uri; diff --git a/k9mail/src/main/java/com/fsck/k9/message/extractors/BodyTextExtractor.java b/k9mail/src/main/java/com/fsck/k9/message/extractors/BodyTextExtractor.java index f0f147bcf..4db0973b1 100644 --- a/k9mail/src/main/java/com/fsck/k9/message/extractors/BodyTextExtractor.java +++ b/k9mail/src/main/java/com/fsck/k9/message/extractors/BodyTextExtractor.java @@ -1,7 +1,7 @@ package com.fsck.k9.message.extractors; -import android.util.Log; +import timber.log.Timber; import com.fsck.k9.K9; import com.fsck.k9.mail.Part; @@ -22,17 +22,13 @@ public class BodyTextExtractor { // HTML takes precedence, then text. part = MimeUtility.findFirstPartByMimeType(messagePart, "text/html"); if (part != null) { - if (K9.DEBUG) { - Log.d(K9.LOG_TAG, "getBodyTextFromMessage: HTML requested, HTML found."); - } + Timber.d("getBodyTextFromMessage: HTML requested, HTML found."); return MessageExtractor.getTextFromPart(part); } part = MimeUtility.findFirstPartByMimeType(messagePart, "text/plain"); if (part != null) { - if (K9.DEBUG) { - Log.d(K9.LOG_TAG, "getBodyTextFromMessage: HTML requested, text found."); - } + Timber.d("getBodyTextFromMessage: HTML requested, text found."); String text = MessageExtractor.getTextFromPart(part); return HtmlConverter.textToHtml(text); } @@ -40,17 +36,13 @@ public class BodyTextExtractor { // Text takes precedence, then html. part = MimeUtility.findFirstPartByMimeType(messagePart, "text/plain"); if (part != null) { - if (K9.DEBUG) { - Log.d(K9.LOG_TAG, "getBodyTextFromMessage: Text requested, text found."); - } + Timber.d("getBodyTextFromMessage: Text requested, text found."); return MessageExtractor.getTextFromPart(part); } part = MimeUtility.findFirstPartByMimeType(messagePart, "text/html"); if (part != null) { - if (K9.DEBUG) { - Log.d(K9.LOG_TAG, "getBodyTextFromMessage: Text requested, HTML found."); - } + Timber.d("getBodyTextFromMessage: Text requested, HTML found."); String text = MessageExtractor.getTextFromPart(part); return HtmlConverter.htmlToText(text); } diff --git a/k9mail/src/main/java/com/fsck/k9/message/quote/HtmlQuoteCreator.java b/k9mail/src/main/java/com/fsck/k9/message/quote/HtmlQuoteCreator.java index 971d87ff6..040904637 100644 --- a/k9mail/src/main/java/com/fsck/k9/message/quote/HtmlQuoteCreator.java +++ b/k9mail/src/main/java/com/fsck/k9/message/quote/HtmlQuoteCreator.java @@ -5,7 +5,7 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; import android.content.res.Resources; -import android.util.Log; +import timber.log.Timber; import com.fsck.k9.Account.QuoteStyle; import com.fsck.k9.K9; @@ -149,9 +149,7 @@ public class HtmlQuoteCreator { hasBodyTag = true; } - if (K9.DEBUG) { - Log.d(K9.LOG_TAG, "Open: hasHtmlTag:" + hasHtmlTag + " hasHeadTag:" + hasHeadTag + " hasBodyTag:" + hasBodyTag); - } + Timber.d("Open: hasHtmlTag:%s hasHeadTag:%s hasBodyTag:%s", hasHtmlTag, hasHeadTag, hasBodyTag); // Given our inspections, let's figure out where to start our content. // This is the ideal case -- there's a BODY tag and we insert ourselves just after it. @@ -202,9 +200,7 @@ public class HtmlQuoteCreator { hasBodyEndTag = true; } - if (K9.DEBUG) { - Log.d(K9.LOG_TAG, "Close: hasHtmlEndTag:" + hasHtmlEndTag + " hasBodyEndTag:" + hasBodyEndTag); - } + Timber.d("Close: hasHtmlEndTag:%s hasBodyEndTag:%s", hasHtmlEndTag, hasBodyEndTag); // Now figure out where to put our footer. // This is the ideal case -- there's a BODY tag and we insert ourselves just before it. diff --git a/k9mail/src/main/java/com/fsck/k9/message/signature/HtmlSignatureRemover.java b/k9mail/src/main/java/com/fsck/k9/message/signature/HtmlSignatureRemover.java index 86145b2ea..f3af9cbcf 100644 --- a/k9mail/src/main/java/com/fsck/k9/message/signature/HtmlSignatureRemover.java +++ b/k9mail/src/main/java/com/fsck/k9/message/signature/HtmlSignatureRemover.java @@ -6,7 +6,7 @@ import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; -import android.util.Log; +import timber.log.Timber; import com.fsck.k9.K9; import org.htmlcleaner.CleanerProperties; @@ -36,8 +36,8 @@ public class HtmlSignatureRemover { end.add(blockquoteEnd.start()); } if (start.size() != end.size()) { - Log.d(K9.LOG_TAG, "There are " + start.size() + "
tags, but " + - end.size() + "
tags. Refusing to strip."); + Timber.d("There are %d
tags, but %d
tags. Refusing to strip.", + start.size(), end.size()); } else if (start.size() > 0) { // Ignore quoted signatures in blockquotes. dashSignatureHtml.region(0, start.get(0)); diff --git a/k9mail/src/main/java/com/fsck/k9/notification/NotificationActionService.java b/k9mail/src/main/java/com/fsck/k9/notification/NotificationActionService.java index b2e3b5ba5..ea446b4e7 100644 --- a/k9mail/src/main/java/com/fsck/k9/notification/NotificationActionService.java +++ b/k9mail/src/main/java/com/fsck/k9/notification/NotificationActionService.java @@ -6,7 +6,7 @@ import java.util.List; import android.content.Context; import android.content.Intent; -import android.util.Log; +import timber.log.Timber; import com.fsck.k9.Account; import com.fsck.k9.K9; @@ -122,16 +122,14 @@ public class NotificationActionService extends CoreService { @Override public int startService(Intent intent, int startId) { - if (K9.DEBUG) { - Log.i(K9.LOG_TAG, "NotificationActionService started with startId = " + startId); - } + Timber.i("NotificationActionService started with startId = %d", startId); String accountUuid = intent.getStringExtra(EXTRA_ACCOUNT_UUID); Preferences preferences = Preferences.getPreferences(this); Account account = preferences.getAccount(accountUuid); if (account == null) { - Log.w(K9.LOG_TAG, "Could not find account for notification action."); + Timber.w("Could not find account for notification action."); return START_NOT_STICKY; } @@ -147,9 +145,7 @@ public class NotificationActionService extends CoreService { } else if (ACTION_SPAM.equals(action)) { markMessageAsSpam(intent, account, controller); } else if (ACTION_DISMISS.equals(action)) { - if (K9.DEBUG) { - Log.i(K9.LOG_TAG, "Notification dismissed"); - } + Timber.i("Notification dismissed"); } cancelNotifications(intent, account, controller); @@ -158,9 +154,7 @@ public class NotificationActionService extends CoreService { } private void markMessagesAsRead(Intent intent, Account account, MessagingController controller) { - if (K9.DEBUG) { - Log.i(K9.LOG_TAG, "NotificationActionService marking messages as read"); - } + Timber.i("NotificationActionService marking messages as read"); List messageReferenceStrings = intent.getStringArrayListExtra(EXTRA_MESSAGE_REFERENCES); List messageReferences = toMessageReferenceList(messageReferenceStrings); @@ -172,9 +166,7 @@ public class NotificationActionService extends CoreService { } private void deleteMessages(Intent intent, MessagingController controller) { - if (K9.DEBUG) { - Log.i(K9.LOG_TAG, "NotificationActionService deleting messages"); - } + Timber.i("NotificationActionService deleting messages"); List messageReferenceStrings = intent.getStringArrayListExtra(EXTRA_MESSAGE_REFERENCES); List messageReferences = toMessageReferenceList(messageReferenceStrings); @@ -182,15 +174,13 @@ public class NotificationActionService extends CoreService { } private void archiveMessages(Intent intent, Account account, MessagingController controller) { - if (K9.DEBUG) { - Log.i(K9.LOG_TAG, "NotificationActionService archiving messages"); - } + Timber.i("NotificationActionService archiving messages"); String archiveFolderName = account.getArchiveFolderName(); if (archiveFolderName == null || (archiveFolderName.equals(account.getSpamFolderName()) && K9.confirmSpam()) || !isMovePossible(controller, account, archiveFolderName)) { - Log.w(K9.LOG_TAG, "Can not archive messages"); + Timber.w("Can not archive messages"); return; } @@ -205,14 +195,12 @@ public class NotificationActionService extends CoreService { } private void markMessageAsSpam(Intent intent, Account account, MessagingController controller) { - if (K9.DEBUG) { - Log.i(K9.LOG_TAG, "NotificationActionService moving messages to spam"); - } + Timber.i("NotificationActionService moving messages to spam"); String messageReferenceString = intent.getStringExtra(EXTRA_MESSAGE_REFERENCE); MessageReference messageReference = MessageReference.parse(messageReferenceString); if (messageReference == null) { - Log.w(K9.LOG_TAG, "Invalid message reference: " + messageReferenceString); + Timber.w("Invalid message reference: %s", messageReferenceString); return; } @@ -230,7 +218,7 @@ public class NotificationActionService extends CoreService { if (messageReference != null) { controller.cancelNotificationForMessage(account, messageReference); } else { - Log.w(K9.LOG_TAG, "Invalid message reference: " + messageReferenceString); + Timber.w("Invalid message reference: %s", messageReferenceString); } } else if (intent.hasExtra(EXTRA_MESSAGE_REFERENCES)) { List messageReferenceStrings = intent.getStringArrayListExtra(EXTRA_MESSAGE_REFERENCES); diff --git a/k9mail/src/main/java/com/fsck/k9/notification/NotificationContentCreator.java b/k9mail/src/main/java/com/fsck/k9/notification/NotificationContentCreator.java index 02d5f27f2..0c1251b8e 100644 --- a/k9mail/src/main/java/com/fsck/k9/notification/NotificationContentCreator.java +++ b/k9mail/src/main/java/com/fsck/k9/notification/NotificationContentCreator.java @@ -5,7 +5,7 @@ import android.content.Context; import android.text.SpannableStringBuilder; import android.text.TextUtils; import android.text.style.TextAppearanceSpan; -import android.util.Log; +import timber.log.Timber; import com.fsck.k9.Account; import com.fsck.k9.K9; diff --git a/k9mail/src/main/java/com/fsck/k9/preferences/Settings.java b/k9mail/src/main/java/com/fsck/k9/preferences/Settings.java index df629761a..383edaa22 100644 --- a/k9mail/src/main/java/com/fsck/k9/preferences/Settings.java +++ b/k9mail/src/main/java/com/fsck/k9/preferences/Settings.java @@ -10,7 +10,7 @@ import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; -import android.util.Log; +import timber.log.Timber; import com.fsck.k9.FontSizes; import com.fsck.k9.K9; @@ -66,8 +66,10 @@ public class Settings { boolean useDefaultValue; if (!importedSettings.containsKey(key)) { - Log.v(K9.LOG_TAG, "Key \"" + key + "\" wasn't found in the imported file." + - ((useDefaultValues) ? " Using default value." : "")); + Timber.v("Key \"%s\" wasn't found in the imported file.%s", + key, + (useDefaultValues) ? " Using default value." : ""); + useDefaultValue = useDefaultValues; } else { String prettyValue = importedSettings.get(key); @@ -76,9 +78,11 @@ public class Settings { validatedSettings.put(key, internalValue); useDefaultValue = false; } catch (InvalidSettingValueException e) { - Log.v(K9.LOG_TAG, "Key \"" + key + "\" has invalid value \"" + prettyValue + - "\" in imported file. " + - ((useDefaultValues) ? "Using default value." : "Skipping.")); + Timber.v("Key \"%s\" has invalid value \"%s\" in imported file. %s", + key, + prettyValue, + (useDefaultValues) ? "Using default value." : "Skipping."); + useDefaultValue = useDefaultValues; } } @@ -162,9 +166,9 @@ public class Settings { T defaultValue = setting.getDefaultValue(); validatedSettingsMutable.put(settingName, defaultValue); - if (K9.DEBUG) { + if (K9.isDebug()) { String prettyValue = setting.toPrettyString(defaultValue); - Log.v(K9.LOG_TAG, "Added new setting \"" + settingName + "\" with default value \"" + prettyValue + "\""); + Timber.v("Added new setting \"%s\" with default value \"%s\"", settingName, prettyValue); } } @@ -173,9 +177,7 @@ public class Settings { validatedSettingsMutable.remove(settingName); deletedSettingsMutable.add(settingName); - if (K9.DEBUG) { - Log.v(K9.LOG_TAG, "Removed setting \"" + settingName + "\""); - } + Timber.v("Removed setting \"%s\"", settingName); } /** @@ -207,10 +209,7 @@ public class Settings { serializedSettings.put(settingName, stringValue); } else { - if (K9.DEBUG) { - Log.w(K9.LOG_TAG, "Settings.serialize() called with a setting that should " + - "have been removed: " + settingName); - } + Timber.w("Settings.convert() called with a setting that should have been removed: %s", settingName); } } diff --git a/k9mail/src/main/java/com/fsck/k9/preferences/SettingsExporter.java b/k9mail/src/main/java/com/fsck/k9/preferences/SettingsExporter.java index 1c2c3b2bb..913173cde 100644 --- a/k9mail/src/main/java/com/fsck/k9/preferences/SettingsExporter.java +++ b/k9mail/src/main/java/com/fsck/k9/preferences/SettingsExporter.java @@ -16,7 +16,7 @@ import java.util.TreeMap; import android.content.Context; import android.os.Environment; -import android.util.Log; +import timber.log.Timber; import android.util.Xml; import com.fsck.k9.Account; @@ -84,7 +84,7 @@ public class SettingsExporter { try { File dir = new File(Environment.getExternalStorageDirectory() + File.separator + context.getPackageName()); if (!dir.mkdirs()) { - Log.d(K9.LOG_TAG, "Unable to create directory: " + dir.getAbsolutePath()); + Timber.d("Unable to create directory: %s", dir.getAbsolutePath()); } File file = FileHelper.createUniqueFile(dir, EXPORT_FILENAME); @@ -102,7 +102,7 @@ public class SettingsExporter { try { os.close(); } catch (IOException ioe) { - Log.w(K9.LOG_TAG, "Couldn't close exported settings file: " + filename); + Timber.w("Couldn't close exported settings file: %s", filename); } } } @@ -124,7 +124,7 @@ public class SettingsExporter { serializer.attribute(null, VERSION_ATTRIBUTE, Integer.toString(Settings.VERSION)); serializer.attribute(null, FILE_FORMAT_ATTRIBUTE, Integer.toString(FILE_FORMAT_VERSION)); - Log.i(K9.LOG_TAG, "Exporting preferences"); + Timber.i("Exporting preferences"); Preferences preferences = Preferences.getPreferences(context); Storage storage = preferences.getStorage(); @@ -183,14 +183,11 @@ public class SettingsExporter { try { writeKeyAndPrettyValueFromSetting(serializer, key, setting, valueString); } catch (InvalidSettingValueException e) { - Log.w(K9.LOG_TAG, "Global setting \"" + key + "\" has invalid value \"" + - valueString + "\" in preference storage. This shouldn't happen!"); + Timber.w("Global setting \"%s\" has invalid value \"%s\" in preference storage. " + + "This shouldn't happen!", key, valueString); } } else { - if (K9.DEBUG) { - Log.d(K9.LOG_TAG, "Couldn't find key \"" + key + "\" in preference storage. Using default value."); - } - + Timber.d("Couldn't find key \"%s\" in preference storage. Using default value.", key); writeKeyAndDefaultValueFromSetting(serializer, key, setting); } } @@ -331,9 +328,8 @@ public class SettingsExporter { try { writeKeyAndPrettyValueFromSetting(serializer, keyPart, setting, valueString); } catch (InvalidSettingValueException e) { - Log.w(K9.LOG_TAG, "Account setting \"" + keyPart + "\" (" + - account.getDescription() + ") has invalid value \"" + valueString + - "\" in preference storage. This shouldn't happen!"); + Timber.w("Account setting \"%s\" (%s) has invalid value \"%s\" in preference storage. " + + "This shouldn't happen!", keyPart, account.getDescription(), valueString); } } } @@ -423,8 +419,8 @@ public class SettingsExporter { try { writeKeyAndPrettyValueFromSetting(serializer, identityKey, setting, valueString); } catch (InvalidSettingValueException e) { - Log.w(K9.LOG_TAG, "Identity setting \"" + identityKey + "\" has invalid value \"" + - valueString + "\" in preference storage. This shouldn't happen!"); + Timber.w("Identity setting \"%s\" has invalid value \"%s\" in preference storage. " + + "This shouldn't happen!", identityKey, valueString); } } } @@ -472,8 +468,8 @@ public class SettingsExporter { try { writeKeyAndPrettyValueFromSetting(serializer, folderKey, setting, valueString); } catch (InvalidSettingValueException e) { - Log.w(K9.LOG_TAG, "Folder setting \"" + folderKey + "\" has invalid value \"" + valueString + - "\" in preference storage. This shouldn't happen!"); + Timber.w("Folder setting \"%s\" has invalid value \"%s\" in preference storage. " + + "This shouldn't happen!", folderKey, valueString); } } } diff --git a/k9mail/src/main/java/com/fsck/k9/preferences/SettingsImporter.java b/k9mail/src/main/java/com/fsck/k9/preferences/SettingsImporter.java index c680f3b02..001d3d5f8 100644 --- a/k9mail/src/main/java/com/fsck/k9/preferences/SettingsImporter.java +++ b/k9mail/src/main/java/com/fsck/k9/preferences/SettingsImporter.java @@ -15,7 +15,7 @@ import android.content.Context; import android.content.SharedPreferences; import android.support.annotation.VisibleForTesting; import android.text.TextUtils; -import android.util.Log; +import timber.log.Timber; import com.fsck.k9.Account; import com.fsck.k9.Identity; @@ -180,20 +180,16 @@ public class SettingsImporter { if (imported.globalSettings != null) { importGlobalSettings(storage, editor, imported.contentVersion, imported.globalSettings); } else { - Log.w(K9.LOG_TAG, "Was asked to import global settings but none found."); + Timber.w("Was asked to import global settings but none found."); } if (editor.commit()) { - if (K9.DEBUG) { - Log.v(K9.LOG_TAG, "Committed global settings to the preference storage."); - } + Timber.v("Committed global settings to the preference storage."); globalSettingsImported = true; } else { - if (K9.DEBUG) { - Log.v(K9.LOG_TAG, "Failed to commit global settings to the preference storage"); - } + Timber.v("Failed to commit global settings to the preference storage"); } } catch (Exception e) { - Log.e(K9.LOG_TAG, "Exception while importing global settings", e); + Timber.e(e, "Exception while importing global settings"); } } @@ -209,10 +205,8 @@ public class SettingsImporter { imported.contentVersion, account, overwrite); if (editor.commit()) { - if (K9.DEBUG) { - Log.v(K9.LOG_TAG, "Committed settings for account \"" + - importResult.imported.name + "\" to the settings database."); - } + Timber.v("Committed settings for account \"%s\" to the settings database.", + importResult.imported.name); // Add UUID of the account we just imported to the list of // account UUIDs @@ -236,25 +230,23 @@ public class SettingsImporter { importedAccounts.add(importResult); } else { - if (K9.DEBUG) { - Log.w(K9.LOG_TAG, "Error while committing settings for account \"" + - importResult.original.name + "\" to the settings database."); - } + Timber.w("Error while committing settings for account \"%s\" to the settings " + + "database.", importResult.original.name); + erroneousAccounts.add(importResult.original); } } catch (InvalidSettingValueException e) { - if (K9.DEBUG) { - Log.e(K9.LOG_TAG, "Encountered invalid setting while " + - "importing account \"" + account.name + "\"", e); - } + Timber.e(e, "Encountered invalid setting while importing account \"%s\"", + account.name); + erroneousAccounts.add(new AccountDescription(account.name, account.uuid)); } catch (Exception e) { - Log.e(K9.LOG_TAG, "Exception while importing account \"" + account.name + "\"", e); + Timber.e(e, "Exception while importing account \"%s\"", account.name); erroneousAccounts.add(new AccountDescription(account.name, account.uuid)); } } else { - Log.w(K9.LOG_TAG, "Was asked to import account with UUID " + accountUuid + - ". But this account wasn't found."); + Timber.w("Was asked to import account with UUID %s. But this account wasn't found.", + accountUuid); } } @@ -269,7 +261,7 @@ public class SettingsImporter { throw new SettingsImportExportException("Failed to set default account"); } } else { - Log.w(K9.LOG_TAG, "Was asked to import at least one account but none found."); + Timber.w("Was asked to import at least one account but none found."); } } @@ -617,12 +609,12 @@ public class SettingsImporter { * The new value for the preference. */ private static void putString(StorageEditor editor, String key, String value) { - if (K9.DEBUG) { + if (K9.isDebug()) { String outputValue = value; if (!K9.DEBUG_SENSITIVE && (key.endsWith(".transportUri") || key.endsWith(".storeUri"))) { outputValue = "*sensitive*"; } - Log.v(K9.LOG_TAG, "Setting " + key + "=" + outputValue); + Timber.v("Setting %s=%s", key, outputValue); } editor.putString(key, value); } @@ -650,7 +642,7 @@ public class SettingsImporter { if (SettingsExporter.ROOT_ELEMENT.equals(xpp.getName())) { imported = parseRoot(xpp, globalSettings, accountUuids, overview); } else { - Log.w(K9.LOG_TAG, "Unexpected start tag: " + xpp.getName()); + Timber.w("Unexpected start tag: %s", xpp.getName()); } } eventType = xpp.next(); @@ -707,20 +699,20 @@ public class SettingsImporter { } } else { skipToEndTag(xpp, SettingsExporter.GLOBAL_ELEMENT); - Log.w(K9.LOG_TAG, "More than one global settings element. Only using the first one!"); + Timber.w("More than one global settings element. Only using the first one!"); } } else { skipToEndTag(xpp, SettingsExporter.GLOBAL_ELEMENT); - Log.i(K9.LOG_TAG, "Skipping global settings"); + Timber.i("Skipping global settings"); } } else if (SettingsExporter.ACCOUNTS_ELEMENT.equals(element)) { if (result.accounts == null) { result.accounts = parseAccounts(xpp, accountUuids, overview); } else { - Log.w(K9.LOG_TAG, "More than one accounts element. Only using the first one!"); + Timber.w("More than one accounts element. Only using the first one!"); } } else { - Log.w(K9.LOG_TAG, "Unexpected start tag: " + xpp.getName()); + Timber.w("Unexpected start tag: %s", xpp.getName()); } } eventType = xpp.next(); @@ -786,12 +778,12 @@ public class SettingsImporter { } if (result.settings.containsKey(key)) { - Log.w(K9.LOG_TAG, "Already read key \"" + key + "\". Ignoring value \"" + value + "\""); + Timber.w("Already read key \"%s\". Ignoring value \"%s\"", key, value); } else { result.settings.put(key, value); } } else { - Log.w(K9.LOG_TAG, "Unexpected start tag: " + xpp.getName()); + Timber.w("Unexpected start tag: %s", xpp.getName()); } } eventType = xpp.next(); @@ -821,10 +813,10 @@ public class SettingsImporter { } else if (!accounts.containsKey(account.uuid)) { accounts.put(account.uuid, account); } else { - Log.w(K9.LOG_TAG, "Duplicate account entries with UUID " + account.uuid + ". Ignoring!"); + Timber.w("Duplicate account entries with UUID %s. Ignoring!", account.uuid); } } else { - Log.w(K9.LOG_TAG, "Unexpected start tag: " + xpp.getName()); + Timber.w("Unexpected start tag: %s", xpp.getName()); } } eventType = xpp.next(); @@ -842,7 +834,7 @@ public class SettingsImporter { UUID.fromString(uuid); } catch (Exception e) { skipToEndTag(xpp, SettingsExporter.ACCOUNT_ELEMENT); - Log.w(K9.LOG_TAG, "Skipping account with invalid UUID " + uuid); + Timber.w("Skipping account with invalid UUID %s", uuid); return null; } @@ -883,14 +875,14 @@ public class SettingsImporter { account.folders = parseFolders(xpp); } } else { - Log.w(K9.LOG_TAG, "Unexpected start tag: " + xpp.getName()); + Timber.w("Unexpected start tag: %s", xpp.getName()); } } eventType = xpp.next(); } } else { skipToEndTag(xpp, SettingsExporter.ACCOUNT_ELEMENT); - Log.i(K9.LOG_TAG, "Skipping account with UUID " + uuid); + Timber.i("Skipping account with UUID %s", uuid); } // If we couldn't find an account name use the UUID @@ -929,7 +921,7 @@ public class SettingsImporter { } else if (SettingsExporter.EXTRA_ELEMENT.equals(element)) { server.extras = parseSettings(xpp, SettingsExporter.EXTRA_ELEMENT); } else { - Log.w(K9.LOG_TAG, "Unexpected start tag: " + xpp.getName()); + Timber.w("Unexpected start tag: %s", xpp.getName()); } } eventType = xpp.next(); @@ -954,7 +946,7 @@ public class SettingsImporter { ImportedIdentity identity = parseIdentity(xpp); identities.add(identity); } else { - Log.w(K9.LOG_TAG, "Unexpected start tag: " + xpp.getName()); + Timber.w("Unexpected start tag: %s", xpp.getName()); } } eventType = xpp.next(); @@ -980,7 +972,7 @@ public class SettingsImporter { } else if (SettingsExporter.SETTINGS_ELEMENT.equals(element)) { identity.settings = parseSettings(xpp, SettingsExporter.SETTINGS_ELEMENT); } else { - Log.w(K9.LOG_TAG, "Unexpected start tag: " + xpp.getName()); + Timber.w("Unexpected start tag: %s", xpp.getName()); } } eventType = xpp.next(); @@ -1004,7 +996,7 @@ public class SettingsImporter { ImportedFolder folder = parseFolder(xpp); folders.add(folder); } else { - Log.w(K9.LOG_TAG, "Unexpected start tag: " + xpp.getName()); + Timber.w("Unexpected start tag: %s", xpp.getName()); } } eventType = xpp.next(); diff --git a/k9mail/src/main/java/com/fsck/k9/preferences/Storage.java b/k9mail/src/main/java/com/fsck/k9/preferences/Storage.java index bc0945496..6969d5d2a 100644 --- a/k9mail/src/main/java/com/fsck/k9/preferences/Storage.java +++ b/k9mail/src/main/java/com/fsck/k9/preferences/Storage.java @@ -5,7 +5,7 @@ import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteStatement; -import android.util.Log; +import timber.log.Timber; import com.fsck.k9.K9; import com.fsck.k9.helper.UrlEncodingHelper; @@ -41,7 +41,7 @@ public class Storage { SQLiteDatabase mDb = context.openOrCreateDatabase(DB_NAME, Context.MODE_PRIVATE, null); if (mDb.getVersion() == 1) { - Log.i(K9.LOG_TAG, "Updating preferences to urlencoded username/password"); + Timber.i("Updating preferences to urlencoded username/password"); String accountUuids = readValue(mDb, "accountUuids"); if (accountUuids != null && accountUuids.length() != 0) { @@ -119,7 +119,7 @@ public class Storage { writeValue(mDb, uuid + ".storeUri", newStoreUriStr); } } catch (Exception e) { - Log.e(K9.LOG_TAG, "ooops", e); + Timber.e(e, "ooops"); } } } @@ -128,7 +128,7 @@ public class Storage { } if (mDb.getVersion() != DB_VERSION) { - Log.i(K9.LOG_TAG, "Creating Storage database"); + Timber.i("Creating Storage database"); mDb.execSQL("DROP TABLE IF EXISTS preferences_storage"); mDb.execSQL("CREATE TABLE preferences_storage " + "(primkey TEXT PRIMARY KEY ON CONFLICT REPLACE, value TEXT)"); @@ -141,25 +141,17 @@ public class Storage { public static Storage getStorage(Context context) { Storage tmpStorage = storages.get(context); if (tmpStorage != null) { - if (K9.DEBUG) { - Log.d(K9.LOG_TAG, "Returning already existing Storage"); - } + Timber.d("Returning already existing Storage"); return tmpStorage; } else { - if (K9.DEBUG) { - Log.d(K9.LOG_TAG, "Creating provisional storage"); - } + Timber.d("Creating provisional storage"); tmpStorage = new Storage(context); Storage oldStorage = storages.putIfAbsent(context, tmpStorage); if (oldStorage != null) { - if (K9.DEBUG) { - Log.d(K9.LOG_TAG, "Another thread beat us to creating the Storage, returning that one"); - } + Timber.d("Another thread beat us to creating the Storage, returning that one"); return oldStorage; } else { - if (K9.DEBUG) { - Log.d(K9.LOG_TAG, "Returning the Storage we created"); - } + Timber.d("Returning the Storage we created"); return tmpStorage; } } @@ -167,7 +159,7 @@ public class Storage { private void loadValues() { long startTime = System.currentTimeMillis(); - Log.i(K9.LOG_TAG, "Loading preferences from DB into Storage"); + Timber.i("Loading preferences from DB into Storage"); Cursor cursor = null; SQLiteDatabase mDb = null; try { @@ -177,9 +169,7 @@ public class Storage { while (cursor.moveToNext()) { String key = cursor.getString(0); String value = cursor.getString(1); - if (K9.DEBUG) { - Log.d(K9.LOG_TAG, "Loading key '" + key + "', value = '" + value + "'"); - } + Timber.d("Loading key '%s', value = '%s'", key, value); storage.put(key, value); } } finally { @@ -188,7 +178,7 @@ public class Storage { mDb.close(); } long endTime = System.currentTimeMillis(); - Log.i(K9.LOG_TAG, "Preferences load took " + (endTime - startTime) + "ms"); + Timber.i("Preferences load took %d ms", endTime - startTime); } } @@ -294,7 +284,7 @@ public class Storage { try { return Integer.parseInt(val); } catch (NumberFormatException nfe) { - Log.e(K9.LOG_TAG, "Could not parse int", nfe); + Timber.e(nfe, "Could not parse int"); return defValue; } } @@ -307,7 +297,7 @@ public class Storage { try { return Long.parseLong(val); } catch (NumberFormatException nfe) { - Log.e(K9.LOG_TAG, "Could not parse long", nfe); + Timber.e(nfe, "Could not parse long"); return defValue; } } @@ -335,9 +325,7 @@ public class Storage { if (cursor.moveToNext()) { value = cursor.getString(0); - if (K9.DEBUG) { - Log.d(K9.LOG_TAG, "Loading key '" + key + "', value = '" + value + "'"); - } + Timber.d("Loading key '%s', value = '%s'", key, value); } } finally { Utility.closeQuietly(cursor); @@ -354,7 +342,7 @@ public class Storage { long result = mDb.insert("preferences_storage", "primkey", cv); if (result == -1) { - Log.e(K9.LOG_TAG, "Error writing key '" + key + "', value = '" + value + "'"); + Timber.e("Error writing key '%s', value = '%s'", key, value); } } } diff --git a/k9mail/src/main/java/com/fsck/k9/preferences/StorageEditor.java b/k9mail/src/main/java/com/fsck/k9/preferences/StorageEditor.java index 44aeb18a1..1086ab30b 100644 --- a/k9mail/src/main/java/com/fsck/k9/preferences/StorageEditor.java +++ b/k9mail/src/main/java/com/fsck/k9/preferences/StorageEditor.java @@ -1,6 +1,6 @@ package com.fsck.k9.preferences; -import android.util.Log; +import timber.log.Timber; import com.fsck.k9.K9; import java.util.ArrayList; @@ -29,14 +29,10 @@ public class StorageEditor { String key = entry.getKey(); Object value = entry.getValue(); if (key != null && value != null) { - if (K9.DEBUG) { - Log.d(K9.LOG_TAG, "Copying key '" + key + "', value '" + value + "'"); - } + Timber.d("Copying key '%s', value '%s'", key, value); changes.put(key, "" + value); } else { - if (K9.DEBUG) { - Log.d(K9.LOG_TAG, "Skipping copying key '" + key + "', value '" + value + "'"); - } + Timber.d("Skipping copying key '%s', value '%s'", key, value); } } } @@ -46,14 +42,14 @@ public class StorageEditor { commitChanges(); return true; } catch (Exception e) { - Log.e(K9.LOG_TAG, "Failed to save preferences", e); + Timber.e(e, "Failed to save preferences"); return false; } } private void commitChanges() { long startTime = System.currentTimeMillis(); - Log.i(K9.LOG_TAG, "Committing preference changes"); + Timber.i("Committing preference changes"); Runnable committer = new Runnable() { public void run() { for (String removeKey : removals) { @@ -73,7 +69,7 @@ public class StorageEditor { }; storage.doInTransaction(committer); long endTime = System.currentTimeMillis(); - Log.i(K9.LOG_TAG, "Preferences commit took " + (endTime - startTime) + "ms"); + Timber.i("Preferences commit took %d ms", endTime - startTime); } diff --git a/k9mail/src/main/java/com/fsck/k9/provider/AttachmentProvider.java b/k9mail/src/main/java/com/fsck/k9/provider/AttachmentProvider.java index e270602b0..f01fc573d 100644 --- a/k9mail/src/main/java/com/fsck/k9/provider/AttachmentProvider.java +++ b/k9mail/src/main/java/com/fsck/k9/provider/AttachmentProvider.java @@ -13,7 +13,7 @@ import android.net.Uri; import android.os.ParcelFileDescriptor; import android.support.annotation.NonNull; import android.support.annotation.Nullable; -import android.util.Log; +import timber.log.Timber; import com.fsck.k9.Account; import com.fsck.k9.BuildConfig; @@ -96,14 +96,12 @@ public class AttachmentProvider extends ContentProvider { final Account account = Preferences.getPreferences(getContext()).getAccount(accountUuid); attachmentInfo = LocalStore.getInstance(account, getContext()).getAttachmentInfo(id); } catch (MessagingException e) { - Log.e(K9.LOG_TAG, "Unable to retrieve attachment info from local store for ID: " + id, e); + Timber.e(e, "Unable to retrieve attachment info from local store for ID: %s", id); return null; } if (attachmentInfo == null) { - if (K9.DEBUG) { - Log.d(K9.LOG_TAG, "No attachment info for ID: " + id); - } + Timber.d("No attachment info for ID: %s", id); return null; } @@ -154,7 +152,7 @@ public class AttachmentProvider extends ContentProvider { type = attachmentInfo.type; } } catch (MessagingException e) { - Log.e(K9.LOG_TAG, "Unable to retrieve LocalStore for " + account, e); + Timber.e(e, "Unable to retrieve LocalStore for %s", account); type = MimeUtility.DEFAULT_ATTACHMENT_MIME_TYPE; } @@ -166,15 +164,15 @@ public class AttachmentProvider extends ContentProvider { try { OpenPgpDataSource openPgpDataSource = getAttachmentDataSource(accountUuid, attachmentId); if (openPgpDataSource == null) { - Log.e(K9.LOG_TAG, "Error getting data source for attachment (part doesn't exist?)"); + Timber.e("Error getting data source for attachment (part doesn't exist?)"); return null; } return openPgpDataSource.startPumpThread(); } catch (MessagingException e) { - Log.e(K9.LOG_TAG, "Error getting InputStream for attachment", e); + Timber.e(e, "Error getting InputStream for attachment"); return null; } catch (IOException e) { - Log.e(K9.LOG_TAG, "Error creating ParcelFileDescriptor", e); + Timber.e(e, "Error creating ParcelFileDescriptor"); return null; } } diff --git a/k9mail/src/main/java/com/fsck/k9/provider/AttachmentTempFileProvider.java b/k9mail/src/main/java/com/fsck/k9/provider/AttachmentTempFileProvider.java index f81631732..182b1d5a8 100644 --- a/k9mail/src/main/java/com/fsck/k9/provider/AttachmentTempFileProvider.java +++ b/k9mail/src/main/java/com/fsck/k9/provider/AttachmentTempFileProvider.java @@ -18,7 +18,7 @@ import android.support.annotation.MainThread; import android.support.annotation.NonNull; import android.support.annotation.WorkerThread; import android.support.v4.content.FileProvider; -import android.util.Log; +import timber.log.Timber; import com.fsck.k9.BuildConfig; import com.fsck.k9.K9; @@ -101,15 +101,15 @@ public class AttachmentTempFileProvider extends FileProvider { if (lastModified < deletionThreshold) { boolean fileDeleted = tempFile.delete(); if (!fileDeleted) { - Log.e(K9.LOG_TAG, "Failed to delete temporary file"); + Timber.e("Failed to delete temporary file"); // TODO really do this? might cause our service to stay up indefinitely if a file can't be deleted allFilesDeleted = false; } } else { - if (K9.DEBUG) { + if (K9.isDebug()) { String timeLeftStr = String.format( Locale.ENGLISH, "%.2f", (lastModified - deletionThreshold) / 1000 / 60.0); - Log.e(K9.LOG_TAG, "Not deleting temp file (for another " + timeLeftStr + " minutes)"); + Timber.e("Not deleting temp file (for another %s minutes)", timeLeftStr); } allFilesDeleted = false; } @@ -122,7 +122,7 @@ public class AttachmentTempFileProvider extends FileProvider { File directory = new File(context.getCacheDir(), CACHE_DIRECTORY); if (!directory.exists()) { if (!directory.mkdir()) { - Log.e(K9.LOG_TAG, "Error creating directory: " + directory.getAbsolutePath()); + Timber.e("Error creating directory: %s", directory.getAbsolutePath()); } } @@ -167,9 +167,7 @@ public class AttachmentTempFileProvider extends FileProvider { return; } - if (K9.DEBUG) { - Log.d(K9.LOG_TAG, "Unregistering temp file cleanup receiver"); - } + Timber.d("Unregistering temp file cleanup receiver"); context.unregisterReceiver(cleanupReceiver); cleanupReceiver = null; } @@ -180,9 +178,8 @@ public class AttachmentTempFileProvider extends FileProvider { if (cleanupReceiver != null) { return; } - if (K9.DEBUG) { - Log.d(K9.LOG_TAG, "Registering temp file cleanup receiver"); - } + + Timber.d("Registering temp file cleanup receiver"); cleanupReceiver = new AttachmentTempFileProviderCleanupReceiver(); IntentFilter intentFilter = new IntentFilter(); @@ -199,9 +196,7 @@ public class AttachmentTempFileProvider extends FileProvider { throw new IllegalArgumentException("onReceive called with action that isn't screen off!"); } - if (K9.DEBUG) { - Log.d(K9.LOG_TAG, "Cleaning up temp files"); - } + Timber.d("Cleaning up temp files"); boolean allFilesDeleted = deleteOldTemporaryFiles(context); if (allFilesDeleted) { diff --git a/k9mail/src/main/java/com/fsck/k9/provider/DecryptedFileProvider.java b/k9mail/src/main/java/com/fsck/k9/provider/DecryptedFileProvider.java index 32f61be99..ec8950697 100644 --- a/k9mail/src/main/java/com/fsck/k9/provider/DecryptedFileProvider.java +++ b/k9mail/src/main/java/com/fsck/k9/provider/DecryptedFileProvider.java @@ -20,7 +20,7 @@ import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.content.FileProvider; import android.text.TextUtils; -import android.util.Log; +import timber.log.Timber; import com.fsck.k9.BuildConfig; import com.fsck.k9.K9; @@ -80,15 +80,15 @@ public class DecryptedFileProvider extends FileProvider { if (lastModified < deletionThreshold) { boolean fileDeleted = tempFile.delete(); if (!fileDeleted) { - Log.e(K9.LOG_TAG, "Failed to delete temporary file"); + Timber.e("Failed to delete temporary file"); // TODO really do this? might cause our service to stay up indefinitely if a file can't be deleted allFilesDeleted = false; } } else { - if (K9.DEBUG) { + if (K9.isDebug()) { String timeLeftStr = String.format( Locale.ENGLISH, "%.2f", (lastModified - deletionThreshold) / 1000 / 60.0); - Log.e(K9.LOG_TAG, "Not deleting temp file (for another " + timeLeftStr + " minutes)"); + Timber.e("Not deleting temp file (for another %s minutes)", timeLeftStr); } allFilesDeleted = false; } @@ -101,7 +101,7 @@ public class DecryptedFileProvider extends FileProvider { File directory = new File(context.getCacheDir(), DECRYPTED_CACHE_DIRECTORY); if (!directory.exists()) { if (!directory.mkdir()) { - Log.e(K9.LOG_TAG, "Error creating directory: " + directory.getAbsolutePath()); + Timber.e("Error creating directory: %s", directory.getAbsolutePath()); } } @@ -132,8 +132,8 @@ public class DecryptedFileProvider extends FileProvider { InputStream inputStream = new ParcelFileDescriptor.AutoCloseInputStream(pfd); decodedInputStream = new QuotedPrintableInputStream(inputStream); } else { // no or unknown encoding - if (K9.DEBUG && !TextUtils.isEmpty(encoding)) { - Log.e(K9.LOG_TAG, "unsupported encoding, returning raw stream"); + if (!TextUtils.isEmpty(encoding)) { + Timber.e("unsupported encoding, returning raw stream"); } return pfd; } @@ -173,9 +173,7 @@ public class DecryptedFileProvider extends FileProvider { return; } - if (K9.DEBUG) { - Log.d(K9.LOG_TAG, "Unregistering temp file cleanup receiver"); - } + Timber.d("Unregistering temp file cleanup receiver"); context.unregisterReceiver(cleanupReceiver); cleanupReceiver = null; } @@ -186,9 +184,8 @@ public class DecryptedFileProvider extends FileProvider { if (cleanupReceiver != null) { return; } - if (K9.DEBUG) { - Log.d(K9.LOG_TAG, "Registering temp file cleanup receiver"); - } + + Timber.d("Registering temp file cleanup receiver"); cleanupReceiver = new DecryptedFileProviderCleanupReceiver(); IntentFilter intentFilter = new IntentFilter(); @@ -205,9 +202,7 @@ public class DecryptedFileProvider extends FileProvider { throw new IllegalArgumentException("onReceive called with action that isn't screen off!"); } - if (K9.DEBUG) { - Log.d(K9.LOG_TAG, "Cleaning up temp files"); - } + Timber.d("Cleaning up temp files"); boolean allFilesDeleted = deleteOldTemporaryFiles(context); if (allFilesDeleted) { diff --git a/k9mail/src/main/java/com/fsck/k9/provider/MessageProvider.java b/k9mail/src/main/java/com/fsck/k9/provider/MessageProvider.java index 5306e0375..aab721055 100644 --- a/k9mail/src/main/java/com/fsck/k9/provider/MessageProvider.java +++ b/k9mail/src/main/java/com/fsck/k9/provider/MessageProvider.java @@ -34,7 +34,7 @@ import android.os.Binder; import android.os.Build; import android.os.Bundle; import android.provider.BaseColumns; -import android.util.Log; +import timber.log.Timber; import com.fsck.k9.Account; import com.fsck.k9.AccountStats; @@ -103,7 +103,7 @@ public class MessageProvider extends ContentProvider { K9.registerApplicationAware(new K9.ApplicationAware() { @Override public void initializeComponent(final Application application) { - Log.v(K9.LOG_TAG, "Registering content resolver notifier"); + Timber.v("Registering content resolver notifier"); MessagingController.getInstance(application).addListener(new SimpleMessagingListener() { @Override @@ -123,9 +123,7 @@ public class MessageProvider extends ContentProvider { return null; } - if (K9.DEBUG) { - Log.v(K9.LOG_TAG, "MessageProvider/getType: " + uri); - } + Timber.v("MessageProvider/getType: %s", uri); return null; } @@ -136,9 +134,7 @@ public class MessageProvider extends ContentProvider { return null; } - if (K9.DEBUG) { - Log.v(K9.LOG_TAG, "MessageProvider/query: " + uri); - } + Timber.v("MessageProvider/query: %s", uri); int code = uriMatcher.match(uri); if (code == -1) { @@ -150,7 +146,7 @@ public class MessageProvider extends ContentProvider { QueryHandler handler = queryHandlers.get(code); cursor = handler.query(uri, projection, selection, selectionArgs, sortOrder); } catch (Exception e) { - Log.e(K9.LOG_TAG, "Unable to execute query for URI: " + uri, e); + Timber.e(e, "Unable to execute query for URI: %s", uri); return null; } @@ -163,9 +159,7 @@ public class MessageProvider extends ContentProvider { return 0; } - if (K9.DEBUG) { - Log.v(K9.LOG_TAG, "MessageProvider/delete: " + uri); - } + Timber.v("MessageProvider/delete: %s", uri); // Note: can only delete a message @@ -180,14 +174,14 @@ public class MessageProvider extends ContentProvider { if (account.getAccountNumber() == accountId) { myAccount = account; if (!account.isAvailable(getContext())) { - Log.w(K9.LOG_TAG, "not deleting messages because account is unavailable at the moment"); + Timber.w("not deleting messages because account is unavailable at the moment"); return 0; } } } if (myAccount == null) { - Log.e(K9.LOG_TAG, "Could not find account with id " + accountId); + Timber.e("Could not find account with id %d", accountId); } if (myAccount != null) { @@ -206,9 +200,7 @@ public class MessageProvider extends ContentProvider { return null; } - if (K9.DEBUG) { - Log.v(K9.LOG_TAG, "MessageProvider/insert: " + uri); - } + Timber.v("MessageProvider/insert: %s", uri); return null; } @@ -219,9 +211,7 @@ public class MessageProvider extends ContentProvider { return 0; } - if (K9.DEBUG) { - Log.v(K9.LOG_TAG, "MessageProvider/update: " + uri); - } + Timber.v("MessageProvider/update: %s", uri); // TBD @@ -712,7 +702,7 @@ public class MessageProvider extends ContentProvider { values[1] = myAccountStats.unreadMessageCount; } } catch (MessagingException e) { - Log.e(K9.LOG_TAG, e.getMessage()); + Timber.e(e.getMessage()); values[0] = "Unknown"; values[1] = 0; } @@ -750,7 +740,7 @@ public class MessageProvider extends ContentProvider { public void close() { if (closed.compareAndSet(false, true)) { cursor.close(); - Log.d(K9.LOG_TAG, "Cursor closed, null'ing & releasing semaphore"); + Timber.d("Cursor closed, null'ing & releasing semaphore"); cursor = null; semaphore.release(); } @@ -1055,7 +1045,7 @@ public class MessageProvider extends ContentProvider { // Android content resolvers can only process CrossProcessCursor instances if (!(cursor instanceof CrossProcessCursor)) { - Log.w(K9.LOG_TAG, "Unsupported cursor, returning null: " + cursor); + Timber.w("Unsupported cursor, returning null: %s", cursor); semaphore.release(); return null; } @@ -1072,11 +1062,11 @@ public class MessageProvider extends ContentProvider { public void run() { MonitoredCursor monitored = weakReference.get(); if (monitored != null && !monitored.isClosed()) { - Log.w(K9.LOG_TAG, "Forcibly closing remotely exposed cursor"); + Timber.w("Forcibly closing remotely exposed cursor"); try { monitored.close(); } catch (Exception e) { - Log.w(K9.LOG_TAG, "Exception while forcibly closing cursor", e); + Timber.w(e, "Exception while forcibly closing cursor"); } } } @@ -1119,7 +1109,7 @@ public class MessageProvider extends ContentProvider { try { queue.put(holders); } catch (InterruptedException e) { - Log.e(K9.LOG_TAG, "Unable to return message list back to caller", e); + Timber.e(e, "Unable to return message list back to caller"); } } } diff --git a/k9mail/src/main/java/com/fsck/k9/provider/UnreadWidgetProvider.java b/k9mail/src/main/java/com/fsck/k9/provider/UnreadWidgetProvider.java index f46091f62..3f4d648ed 100644 --- a/k9mail/src/main/java/com/fsck/k9/provider/UnreadWidgetProvider.java +++ b/k9mail/src/main/java/com/fsck/k9/provider/UnreadWidgetProvider.java @@ -19,7 +19,7 @@ import android.appwidget.AppWidgetProvider; import android.content.ComponentName; import android.content.Context; import android.content.Intent; -import android.util.Log; +import timber.log.Timber; import android.view.View; import android.widget.RemoteViews; @@ -99,9 +99,7 @@ public class UnreadWidgetProvider extends AppWidgetProvider { unreadCount = stats.unreadMessageCount; } } catch (Exception e) { - if (K9.DEBUG) { - Log.e(K9.LOG_TAG, "Error getting widget configuration", e); - } + Timber.e(e, "Error getting widget configuration"); } if (unreadCount <= 0) { diff --git a/k9mail/src/main/java/com/fsck/k9/remotecontrol/AccountReceiver.java b/k9mail/src/main/java/com/fsck/k9/remotecontrol/AccountReceiver.java index 309dadbe0..82353e9f4 100644 --- a/k9mail/src/main/java/com/fsck/k9/remotecontrol/AccountReceiver.java +++ b/k9mail/src/main/java/com/fsck/k9/remotecontrol/AccountReceiver.java @@ -4,7 +4,7 @@ import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Bundle; -import android.util.Log; +import timber.log.Timber; class AccountReceiver extends BroadcastReceiver { K9AccountReceptor receptor = null; @@ -18,7 +18,7 @@ class AccountReceiver extends BroadcastReceiver { if (K9RemoteControl.K9_REQUEST_ACCOUNTS.equals(intent.getAction())) { Bundle bundle = getResultExtras(false); if (bundle == null) { - Log.w(K9RemoteControl.LOG_TAG, "Response bundle is empty"); + Timber.w("Response bundle is empty"); return; } receptor.accounts(bundle.getStringArray(K9RemoteControl.K9_ACCOUNT_UUIDS), bundle.getStringArray(K9RemoteControl.K9_ACCOUNT_DESCRIPTIONS)); diff --git a/k9mail/src/main/java/com/fsck/k9/search/SqlQueryBuilder.java b/k9mail/src/main/java/com/fsck/k9/search/SqlQueryBuilder.java index 6ffedef77..3366f0227 100644 --- a/k9mail/src/main/java/com/fsck/k9/search/SqlQueryBuilder.java +++ b/k9mail/src/main/java/com/fsck/k9/search/SqlQueryBuilder.java @@ -2,7 +2,7 @@ package com.fsck.k9.search; import java.util.List; -import android.util.Log; +import timber.log.Timber; import com.fsck.k9.Account; import com.fsck.k9.K9; @@ -78,7 +78,7 @@ public class SqlQueryBuilder { case MESSAGE_CONTENTS: { String fulltextQueryString = condition.value; if (condition.attribute != Attribute.CONTAINS) { - Log.e(K9.LOG_TAG, "message contents can only be matched!"); + Timber.e("message contents can only be matched!"); } query.append("(EXISTS (SELECT docid FROM messages_fulltext WHERE docid = id AND fulltext MATCH ?))"); selectionArgs.add(fulltextQueryString); diff --git a/k9mail/src/main/java/com/fsck/k9/service/BootReceiver.java b/k9mail/src/main/java/com/fsck/k9/service/BootReceiver.java index 5361a4b4f..f81fdb706 100644 --- a/k9mail/src/main/java/com/fsck/k9/service/BootReceiver.java +++ b/k9mail/src/main/java/com/fsck/k9/service/BootReceiver.java @@ -9,7 +9,7 @@ import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.net.Uri; -import android.util.Log; +import timber.log.Timber; import com.fsck.k9.K9; import com.fsck.k9.helper.K9AlarmManager; @@ -25,8 +25,7 @@ public class BootReceiver extends CoreReceiver { @Override public Integer receive(Context context, Intent intent, Integer tmpWakeLockId) { - if (K9.DEBUG) - Log.i(K9.LOG_TAG, "BootReceiver.onReceive" + intent); + Timber.i("BootReceiver.onReceive %s", intent); final String action = intent.getAction(); if (Intent.ACTION_BOOT_COMPLETED.equals(action)) { @@ -50,16 +49,14 @@ public class BootReceiver extends CoreReceiver { } else if (FIRE_INTENT.equals(action)) { Intent alarmedIntent = intent.getParcelableExtra(ALARMED_INTENT); String alarmedAction = alarmedIntent.getAction(); - if (K9.DEBUG) - Log.i(K9.LOG_TAG, "BootReceiver Got alarm to fire alarmedIntent " + alarmedAction); + Timber.i("BootReceiver Got alarm to fire alarmedIntent %s", alarmedAction); alarmedIntent.putExtra(WAKE_LOCK_ID, tmpWakeLockId); tmpWakeLockId = null; context.startService(alarmedIntent); } else if (SCHEDULE_INTENT.equals(action)) { long atTime = intent.getLongExtra(AT_TIME, -1); Intent alarmedIntent = intent.getParcelableExtra(ALARMED_INTENT); - if (K9.DEBUG) - Log.i(K9.LOG_TAG, "BootReceiver Scheduling intent " + alarmedIntent + " for " + new Date(atTime)); + Timber.i("BootReceiver Scheduling intent %s for %tc", alarmedIntent, atTime); PendingIntent pi = buildPendingIntent(context, intent); K9AlarmManager alarmMgr = K9AlarmManager.getAlarmManager(context); @@ -67,8 +64,7 @@ public class BootReceiver extends CoreReceiver { alarmMgr.set(AlarmManager.RTC_WAKEUP, atTime, pi); } else if (CANCEL_INTENT.equals(action)) { Intent alarmedIntent = intent.getParcelableExtra(ALARMED_INTENT); - if (K9.DEBUG) - Log.i(K9.LOG_TAG, "BootReceiver Canceling alarmedIntent " + alarmedIntent); + Timber.i("BootReceiver Canceling alarmedIntent %s", alarmedIntent); PendingIntent pi = buildPendingIntent(context, intent); @@ -94,8 +90,8 @@ public class BootReceiver extends CoreReceiver { } public static void scheduleIntent(Context context, long atTime, Intent alarmedIntent) { - if (K9.DEBUG) - Log.i(K9.LOG_TAG, "BootReceiver Got request to schedule alarmedIntent " + alarmedIntent.getAction()); + Timber.i("BootReceiver Got request to schedule alarmedIntent %s", alarmedIntent.getAction()); + Intent i = new Intent(); i.setClass(context, BootReceiver.class); i.setAction(SCHEDULE_INTENT); @@ -105,8 +101,8 @@ public class BootReceiver extends CoreReceiver { } public static void cancelIntent(Context context, Intent alarmedIntent) { - if (K9.DEBUG) - Log.i(K9.LOG_TAG, "BootReceiver Got request to cancel alarmedIntent " + alarmedIntent.getAction()); + Timber.i("BootReceiver Got request to cancel alarmedIntent %s", alarmedIntent.getAction()); + Intent i = new Intent(); i.setClass(context, BootReceiver.class); i.setAction(CANCEL_INTENT); diff --git a/k9mail/src/main/java/com/fsck/k9/service/CoreReceiver.java b/k9mail/src/main/java/com/fsck/k9/service/CoreReceiver.java index 50b899f2f..a30d1b857 100644 --- a/k9mail/src/main/java/com/fsck/k9/service/CoreReceiver.java +++ b/k9mail/src/main/java/com/fsck/k9/service/CoreReceiver.java @@ -8,7 +8,7 @@ import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.PowerManager; -import android.util.Log; +import timber.log.Timber; import com.fsck.k9.K9; import com.fsck.k9.mail.power.TracingPowerManager; @@ -30,8 +30,7 @@ public class CoreReceiver extends BroadcastReceiver { wakeLock.acquire(K9.BOOT_RECEIVER_WAKE_LOCK_TIMEOUT); Integer tmpWakeLockId = wakeLockSeq.getAndIncrement(); wakeLocks.put(tmpWakeLockId, wakeLock); - if (K9.DEBUG) - Log.v(K9.LOG_TAG, "CoreReceiver Created wakeLock " + tmpWakeLockId); + Timber.v("CoreReceiver Created wakeLock %d", tmpWakeLockId); return tmpWakeLockId; } @@ -39,11 +38,10 @@ public class CoreReceiver extends BroadcastReceiver { if (wakeLockId != null) { TracingWakeLock wl = wakeLocks.remove(wakeLockId); if (wl != null) { - if (K9.DEBUG) - Log.v(K9.LOG_TAG, "CoreReceiver Releasing wakeLock " + wakeLockId); + Timber.v("CoreReceiver Releasing wakeLock %d", wakeLockId); wl.release(); } else { - Log.w(K9.LOG_TAG, "BootReceiver WakeLock " + wakeLockId + " doesn't exist"); + Timber.w("BootReceiver WakeLock %d doesn't exist", wakeLockId); } } } @@ -52,13 +50,12 @@ public class CoreReceiver extends BroadcastReceiver { public void onReceive(Context context, Intent intent) { Integer tmpWakeLockId = CoreReceiver.getWakeLock(context); try { - if (K9.DEBUG) - Log.i(K9.LOG_TAG, "CoreReceiver.onReceive" + intent); + Timber.i("CoreReceiver.onReceive %s", intent); + if (CoreReceiver.WAKE_LOCK_RELEASE.equals(intent.getAction())) { Integer wakeLockId = intent.getIntExtra(WAKE_LOCK_ID, -1); if (wakeLockId != -1) { - if (K9.DEBUG) - Log.v(K9.LOG_TAG, "CoreReceiver Release wakeLock " + wakeLockId); + Timber.v("CoreReceiver Release wakeLock %d", wakeLockId); CoreReceiver.releaseWakeLock(wakeLockId); } } else { @@ -74,8 +71,8 @@ public class CoreReceiver extends BroadcastReceiver { } public static void releaseWakeLock(Context context, int wakeLockId) { - if (K9.DEBUG) - Log.v(K9.LOG_TAG, "CoreReceiver Got request to release wakeLock " + wakeLockId); + Timber.v("CoreReceiver Got request to release wakeLock %d", wakeLockId); + Intent i = new Intent(); i.setClass(context, CoreReceiver.class); i.setAction(WAKE_LOCK_RELEASE); diff --git a/k9mail/src/main/java/com/fsck/k9/service/CoreService.java b/k9mail/src/main/java/com/fsck/k9/service/CoreService.java index 66dee0c1d..1cebcd8ea 100644 --- a/k9mail/src/main/java/com/fsck/k9/service/CoreService.java +++ b/k9mail/src/main/java/com/fsck/k9/service/CoreService.java @@ -11,7 +11,7 @@ import android.content.Context; import android.content.Intent; import android.os.IBinder; import android.os.PowerManager; -import android.util.Log; +import timber.log.Timber; import com.fsck.k9.K9; import com.fsck.k9.controller.MessagingController; import com.fsck.k9.mail.power.TracingPowerManager; @@ -190,9 +190,7 @@ public abstract class CoreService extends Service { @Override public void onCreate() { - if (K9.DEBUG) { - Log.i(K9.LOG_TAG, "CoreService: " + className + ".onCreate()"); - } + Timber.i("CoreService: %s.onCreate()", className); mThreadPool = Executors.newFixedThreadPool(1); // Must be single threaded } @@ -217,9 +215,7 @@ public abstract class CoreService extends Service { TracingWakeLock wakeLock = acquireWakeLock(this, "CoreService onStart", K9.MAIL_SERVICE_WAKE_LOCK_TIMEOUT); - if (K9.DEBUG) { - Log.i(K9.LOG_TAG, "CoreService: " + className + ".onStart(" + intent + ", " + startId + ")"); - } + Timber.i("CoreService: %s.onStart(%s, %d)", className, intent, startId); // If we were started by BootReceiver, release the wake lock acquired there. int wakeLockId = intent.getIntExtra(BootReceiver.WAKE_LOCK_ID, -1); @@ -231,19 +227,14 @@ public abstract class CoreService extends Service { // release it. int coreWakeLockId = intent.getIntExtra(WAKE_LOCK_ID, -1); if (coreWakeLockId != -1) { - if (K9.DEBUG) { - Log.d(K9.LOG_TAG, "Got core wake lock id " + coreWakeLockId); - } + Timber.d("Got core wake lock id %d", coreWakeLockId); // Remove wake lock from the registry TracingWakeLock coreWakeLock = sWakeLocks.remove(coreWakeLockId); // Release wake lock if (coreWakeLock != null) { - if (K9.DEBUG) { - Log.d(K9.LOG_TAG, "Found core wake lock with id " + coreWakeLockId + - ", releasing"); - } + Timber.d("Found core wake lock with id %d, releasing", coreWakeLockId); coreWakeLock.release(); } } @@ -306,10 +297,8 @@ public abstract class CoreService extends Service { // Get the sync status boolean oldIsSyncDisabled = MailService.isSyncDisabled(); - if (K9.DEBUG) { - Log.d(K9.LOG_TAG, "CoreService (" + className + ") running Runnable " + - runner.hashCode() + " with startId " + startId); - } + Timber.d("CoreService (%s) running Runnable %d with startId %d", + className, runner.hashCode(), startId); // Run the supplied code runner.run(); @@ -322,10 +311,9 @@ public abstract class CoreService extends Service { } finally { // Making absolutely sure stopSelf() will be called try { - if (K9.DEBUG) { - Log.d(K9.LOG_TAG, "CoreService (" + className + ") completed " + - "Runnable " + runner.hashCode() + " with startId " + startId); - } + Timber.d("CoreService (%s) completed Runnable %d with startId %d", + className, runner.hashCode(), startId); + wakeLock.release(); } finally { if (autoShutdown && startId != null) { @@ -338,19 +326,15 @@ public abstract class CoreService extends Service { // TODO: remove this. we never set mThreadPool to null if (mThreadPool == null) { - Log.e(K9.LOG_TAG, "CoreService.execute (" + className + ") called with no thread " + - "pool available; running Runnable " + runner.hashCode() + - " in calling thread"); + Timber.e("CoreService.execute (%s) called with no thread pool available; " + + "running Runnable %d in calling thread", className, runner.hashCode()); synchronized (this) { myRunner.run(); serviceShutdownScheduled = startId != null; } } else { - if (K9.DEBUG) { - Log.d(K9.LOG_TAG, "CoreService (" + className + ") queueing Runnable " + - runner.hashCode() + " with startId " + startId); - } + Timber.d("CoreService (%s) queueing Runnable %d with startId %d", className, runner.hashCode(), startId); try { mThreadPool.execute(myRunner); @@ -362,8 +346,8 @@ public abstract class CoreService extends Service { throw e; } - Log.i(K9.LOG_TAG, "CoreService: " + className + " is shutting down, ignoring " + - "rejected execution exception: " + e.getMessage()); + Timber.i("CoreService: %s is shutting down, ignoring rejected execution exception: %s", + className, e.getMessage()); } } @@ -391,7 +375,7 @@ public abstract class CoreService extends Service { @Override public void onLowMemory() { - Log.w(K9.LOG_TAG, "CoreService: " + className + ".onLowMemory() - Running low on memory"); + Timber.w("CoreService: %s.onLowMemory() - Running low on memory", className); } /** @@ -399,9 +383,7 @@ public abstract class CoreService extends Service { */ @Override public void onDestroy() { - if (K9.DEBUG) { - Log.i(K9.LOG_TAG, "CoreService: " + className + ".onDestroy()"); - } + Timber.i("CoreService: %s.onDestroy()", className); // Shut down thread pool mShutdown = true; diff --git a/k9mail/src/main/java/com/fsck/k9/service/DatabaseUpgradeService.java b/k9mail/src/main/java/com/fsck/k9/service/DatabaseUpgradeService.java index fd89659e8..ea1767cfa 100644 --- a/k9mail/src/main/java/com/fsck/k9/service/DatabaseUpgradeService.java +++ b/k9mail/src/main/java/com/fsck/k9/service/DatabaseUpgradeService.java @@ -9,7 +9,7 @@ import android.content.Intent; import android.os.IBinder; import android.os.PowerManager; import android.support.v4.content.LocalBroadcastManager; -import android.util.Log; +import timber.log.Timber; import com.fsck.k9.Account; import com.fsck.k9.K9; @@ -120,10 +120,7 @@ public class DatabaseUpgradeService extends Service { boolean success = mRunning.compareAndSet(false, true); if (success) { // The service wasn't running yet. - - if (K9.DEBUG) { - Log.i(K9.LOG_TAG, "DatabaseUpgradeService started"); - } + Timber.i("DatabaseUpgradeService started"); acquireWakelock(); @@ -159,10 +156,7 @@ public class DatabaseUpgradeService extends Service { */ private void stopService() { stopSelf(); - - if (K9.DEBUG) { - Log.i(K9.LOG_TAG, "DatabaseUpgradeService stopped"); - } + Timber.i("DatabaseUpgradeService stopped"); releaseWakelock(); mRunning.set(false); @@ -200,9 +194,9 @@ public class DatabaseUpgradeService extends Service { // Account.getLocalStore() is blocking and will upgrade the database if necessary account.getLocalStore(); } catch (UnavailableStorageException e) { - Log.e(K9.LOG_TAG, "Database unavailable"); + Timber.e("Database unavailable"); } catch (Exception e) { - Log.e(K9.LOG_TAG, "Error while upgrading database", e); + Timber.e(e, "Error while upgrading database"); } mProgress++; diff --git a/k9mail/src/main/java/com/fsck/k9/service/MailService.java b/k9mail/src/main/java/com/fsck/k9/service/MailService.java index 256ee739c..889936bcb 100644 --- a/k9mail/src/main/java/com/fsck/k9/service/MailService.java +++ b/k9mail/src/main/java/com/fsck/k9/service/MailService.java @@ -8,7 +8,7 @@ import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.os.IBinder; -import android.util.Log; +import timber.log.Timber; import com.fsck.k9.Account; import com.fsck.k9.K9; @@ -20,6 +20,8 @@ import com.fsck.k9.mail.Pusher; import com.fsck.k9.preferences.Storage; import com.fsck.k9.preferences.StorageEditor; +import static java.lang.System.currentTimeMillis; + public class MailService extends CoreService { private static final String ACTION_CHECK_MAIL = "com.fsck.k9.intent.action.MAIL_SERVICE_WAKEUP"; @@ -81,8 +83,7 @@ public class MailService extends CoreService { @Override public void onCreate() { super.onCreate(); - if (K9.DEBUG) - Log.v(K9.LOG_TAG, "***** MailService *****: onCreate"); + Timber.v("***** MailService *****: onCreate"); } @Override @@ -112,40 +113,34 @@ public class MailService extends CoreService { syncNoConnectivity = !hasConnectivity; syncBlocked = !(doBackground && hasConnectivity); - if (K9.DEBUG) - Log.i(K9.LOG_TAG, "MailService.onStart(" + intent + ", " + startId - + "), hasConnectivity = " + hasConnectivity + ", doBackground = " + doBackground); + Timber.i("MailService.onStart(%s, %d), hasConnectivity = %s, doBackground = %s", + intent, startId, hasConnectivity, doBackground); // MessagingController.getInstance(getApplication()).addListener(mListener); if (ACTION_CHECK_MAIL.equals(intent.getAction())) { - if (K9.DEBUG) - Log.i(K9.LOG_TAG, "***** MailService *****: checking mail"); + Timber.i("***** MailService *****: checking mail"); if (hasConnectivity && doBackground) { PollService.startService(this); } reschedulePollInBackground(hasConnectivity, doBackground, startId, false); } else if (ACTION_CANCEL.equals(intent.getAction())) { - if (K9.DEBUG) - Log.v(K9.LOG_TAG, "***** MailService *****: cancel"); + Timber.v("***** MailService *****: cancel"); cancel(); } else if (ACTION_RESET.equals(intent.getAction())) { - if (K9.DEBUG) - Log.v(K9.LOG_TAG, "***** MailService *****: reschedule"); + Timber.v("***** MailService *****: reschedule"); rescheduleAllInBackground(hasConnectivity, doBackground, startId); } else if (ACTION_RESTART_PUSHERS.equals(intent.getAction())) { - if (K9.DEBUG) - Log.v(K9.LOG_TAG, "***** MailService *****: restarting pushers"); + Timber.v("***** MailService *****: restarting pushers"); reschedulePushersInBackground(hasConnectivity, doBackground, startId); } else if (ACTION_RESCHEDULE_POLL.equals(intent.getAction())) { - if (K9.DEBUG) - Log.v(K9.LOG_TAG, "***** MailService *****: rescheduling poll"); + Timber.v("***** MailService *****: rescheduling poll"); reschedulePollInBackground(hasConnectivity, doBackground, startId, true); } else if (ACTION_REFRESH_PUSHERS.equals(intent.getAction())) { refreshPushersInBackground(hasConnectivity, doBackground, startId); } else if (CONNECTIVITY_CHANGE.equals(intent.getAction())) { rescheduleAllInBackground(hasConnectivity, doBackground, startId); - if (K9.DEBUG) - Log.i(K9.LOG_TAG, "Got connectivity action with hasConnectivity = " + hasConnectivity + ", doBackground = " + doBackground); + Timber.i("Got connectivity action with hasConnectivity = %s, doBackground = %s", + hasConnectivity, doBackground); } else if (CANCEL_CONNECTIVITY_NOTICE.equals(intent.getAction())) { /* do nothing */ } @@ -154,16 +149,14 @@ public class MailService extends CoreService { MessagingController.getInstance(getApplication()).systemStatusChanged(); } - if (K9.DEBUG) - Log.i(K9.LOG_TAG, "MailService.onStart took " + (System.currentTimeMillis() - startTime) + "ms"); + Timber.i("MailService.onStart took %d ms", currentTimeMillis() - startTime); return START_NOT_STICKY; } @Override public void onDestroy() { - if (K9.DEBUG) - Log.v(K9.LOG_TAG, "***** MailService *****: onDestroy()"); + Timber.v("***** MailService *****: onDestroy()"); super.onDestroy(); // MessagingController.getInstance(getApplication()).removeListener(mListener); } @@ -179,8 +172,8 @@ public class MailService extends CoreService { public static void saveLastCheckEnd(Context context) { long lastCheckEnd = System.currentTimeMillis(); - if (K9.DEBUG) - Log.i(K9.LOG_TAG, "Saving lastCheckEnd = " + new Date(lastCheckEnd)); + Timber.i("Saving lastCheckEnd = %tc", lastCheckEnd); + Preferences prefs = Preferences.getPreferences(context); Storage storage = prefs.getStorage(); StorageEditor editor = storage.edit(); @@ -237,10 +230,7 @@ public class MailService extends CoreService { boolean considerLastCheckEnd) { if (!(hasConnectivity && doBackground)) { - if (K9.DEBUG) { - Log.i(K9.LOG_TAG, "No connectivity, canceling check for " + - getApplication().getPackageName()); - } + Timber.i("No connectivity, canceling check for %s", getApplication().getPackageName()); nextCheck = -1; cancel(); @@ -253,11 +243,12 @@ public class MailService extends CoreService { int previousInterval = storage.getInt(PREVIOUS_INTERVAL, -1); long lastCheckEnd = storage.getLong(LAST_CHECK_END, -1); - if (lastCheckEnd > System.currentTimeMillis()) { - Log.i(K9.LOG_TAG, "The database claims that the last time mail was checked was in " + - "the future (" + lastCheckEnd + "). To try to get things back to normal, " + - "the last check time has been reset to: " + System.currentTimeMillis()); - lastCheckEnd = System.currentTimeMillis(); + long now = System.currentTimeMillis(); + if (lastCheckEnd > now) { + Timber.i("The database claims that the last time mail was checked was in the future (%tc). To try to get " + + "things back to normal, the last check time has been reset to: %tc", lastCheckEnd, now); + + lastCheckEnd = now; } int shortestInterval = -1; @@ -274,10 +265,7 @@ public class MailService extends CoreService { editor.commit(); if (shortestInterval == -1) { - if (K9.DEBUG) { - Log.i(K9.LOG_TAG, "No next check scheduled for package " + - getApplication().getPackageName()); - } + Timber.i("No next check scheduled for package %s", getApplication().getPackageName()); nextCheck = -1; pollingRequested = false; @@ -288,25 +276,20 @@ public class MailService extends CoreService { !considerLastCheckEnd ? System.currentTimeMillis() : lastCheckEnd); long nextTime = base + delay; - if (K9.DEBUG) { - Log.i(K9.LOG_TAG, "previousInterval = " + previousInterval + - ", shortestInterval = " + shortestInterval + - ", lastCheckEnd = " + new Date(lastCheckEnd) + - ", considerLastCheckEnd = " + considerLastCheckEnd); - } + Timber.i("previousInterval = %d, shortestInterval = %d, lastCheckEnd = %tc, considerLastCheckEnd = %tc", + previousInterval, + shortestInterval, + lastCheckEnd, + considerLastCheckEnd); nextCheck = nextTime; pollingRequested = true; try { - if (K9.DEBUG) { - Log.i(K9.LOG_TAG, "Next check for package " + - getApplication().getPackageName() + " scheduled for " + - new Date(nextTime)); - } + Timber.i("Next check for package %s scheduled for %tc", getApplication().getPackageName(), nextTime); } catch (Exception e) { // I once got a NullPointerException deep in new Date(); - Log.e(K9.LOG_TAG, "Exception while logging", e); + Timber.e(e, "Exception while logging"); } Intent i = new Intent(this, MailService.class); @@ -341,17 +324,12 @@ public class MailService extends CoreService { } private void reschedulePushers(boolean hasConnectivity, boolean doBackground) { - if (K9.DEBUG) { - Log.i(K9.LOG_TAG, "Rescheduling pushers"); - } + Timber.i("Rescheduling pushers"); stopPushers(); if (!(hasConnectivity && doBackground)) { - if (K9.DEBUG) { - Log.i(K9.LOG_TAG, "Not scheduling pushers: connectivity? " + hasConnectivity + - " -- doBackground? " + doBackground); - } + Timber.i("Not scheduling pushers: connectivity? %s -- doBackground? %s", hasConnectivity, doBackground); return; } @@ -363,8 +341,8 @@ public class MailService extends CoreService { private void setupPushers() { boolean pushing = false; for (Account account : Preferences.getPreferences(MailService.this).getAccounts()) { - if (K9.DEBUG) - Log.i(K9.LOG_TAG, "Setting up pushers for account " + account.getDescription()); + Timber.i("Setting up pushers for account %s", account.getDescription()); + if (account.isEnabled() && account.isAvailable(getApplicationContext())) { pushing |= MessagingController.getInstance(getApplication()).setupPushing(account); } else { @@ -380,36 +358,39 @@ public class MailService extends CoreService { private void refreshPushers() { try { long nowTime = System.currentTimeMillis(); - if (K9.DEBUG) - Log.i(K9.LOG_TAG, "Refreshing pushers"); + Timber.i("Refreshing pushers"); + Collection pushers = MessagingController.getInstance(getApplication()).getPushers(); for (Pusher pusher : pushers) { long lastRefresh = pusher.getLastRefresh(); int refreshInterval = pusher.getRefreshInterval(); long sinceLast = nowTime - lastRefresh; if (sinceLast + 10000 > refreshInterval) { // Add 10 seconds to keep pushers in sync, avoid drift - if (K9.DEBUG) { - Log.d(K9.LOG_TAG, "PUSHREFRESH: refreshing lastRefresh = " + lastRefresh + ", interval = " + refreshInterval - + ", nowTime = " + nowTime + ", sinceLast = " + sinceLast); - } + Timber.d("PUSHREFRESH: refreshing lastRefresh = %d, interval = %d, nowTime = %d, " + + "sinceLast = %d", + lastRefresh, + refreshInterval, + nowTime, + sinceLast); + pusher.refresh(); pusher.setLastRefresh(nowTime); } else { - if (K9.DEBUG) { - Log.d(K9.LOG_TAG, "PUSHREFRESH: NOT refreshing lastRefresh = " + lastRefresh + ", interval = " + refreshInterval - + ", nowTime = " + nowTime + ", sinceLast = " + sinceLast); - } + Timber.d("PUSHREFRESH: NOT refreshing lastRefresh = %d, interval = %d, nowTime = %d, " + + "sinceLast = %d", + lastRefresh, + refreshInterval, + nowTime, + sinceLast); } } // Whenever we refresh our pushers, send any unsent messages - if (K9.DEBUG) { - Log.d(K9.LOG_TAG, "PUSHREFRESH: trying to send mail in all folders!"); - } + Timber.d("PUSHREFRESH: trying to send mail in all folders!"); MessagingController.getInstance(getApplication()).sendPendingMessages(null); } catch (Exception e) { - Log.e(K9.LOG_TAG, "Exception while refreshing pushers", e); + Timber.e(e, "Exception while refreshing pushers"); } } @@ -423,13 +404,13 @@ public class MailService extends CoreService { minInterval = interval; } } - if (K9.DEBUG) { - Log.v(K9.LOG_TAG, "Pusher refresh interval = " + minInterval); - } + + Timber.v("Pusher refresh interval = %d", minInterval); + if (minInterval > 0) { long nextTime = System.currentTimeMillis() + minInterval; - if (K9.DEBUG) - Log.d(K9.LOG_TAG, "Next pusher refresh scheduled for " + new Date(nextTime)); + Timber.d("Next pusher refresh scheduled for %tc", nextTime); + Intent i = new Intent(this, MailService.class); i.setAction(ACTION_REFRESH_PUSHERS); BootReceiver.scheduleIntent(MailService.this, nextTime, i); diff --git a/k9mail/src/main/java/com/fsck/k9/service/PollService.java b/k9mail/src/main/java/com/fsck/k9/service/PollService.java index 4ff0d331c..6bf60ac10 100644 --- a/k9mail/src/main/java/com/fsck/k9/service/PollService.java +++ b/k9mail/src/main/java/com/fsck/k9/service/PollService.java @@ -4,7 +4,7 @@ import android.content.Context; import android.content.Intent; import android.os.IBinder; import android.os.PowerManager; -import android.util.Log; +import timber.log.Timber; import com.fsck.k9.*; import com.fsck.k9.controller.MessagingController; import com.fsck.k9.controller.SimpleMessagingListener; @@ -45,27 +45,23 @@ public class PollService extends CoreService { @Override public int startService(Intent intent, int startId) { if (START_SERVICE.equals(intent.getAction())) { - if (K9.DEBUG) - Log.i(K9.LOG_TAG, "PollService started with startId = " + startId); + Timber.i("PollService started with startId = %d", startId); MessagingController controller = MessagingController.getInstance(getApplication()); Listener listener = (Listener)controller.getCheckMailListener(); if (listener == null) { - if (K9.DEBUG) - Log.i(K9.LOG_TAG, "***** PollService *****: starting new check"); + Timber.i("***** PollService *****: starting new check"); mListener.setStartId(startId); mListener.wakeLockAcquire(); controller.setCheckMailListener(mListener); controller.checkMail(this, null, false, false, mListener); } else { - if (K9.DEBUG) - Log.i(K9.LOG_TAG, "***** PollService *****: renewing WakeLock"); + Timber.i("***** PollService *****: renewing WakeLock"); listener.setStartId(startId); listener.wakeLockAcquire(); } } else if (STOP_SERVICE.equals(intent.getAction())) { - if (K9.DEBUG) - Log.i(K9.LOG_TAG, "PollService stopping"); + Timber.i("PollService stopping"); stopSelf(); } @@ -131,17 +127,14 @@ public class PollService extends CoreService { MailService.actionReschedulePoll(PollService.this, null); wakeLockRelease(); - if (K9.DEBUG) - Log.i(K9.LOG_TAG, "PollService stopping with startId = " + startId); + Timber.i("PollService stopping with startId = %d", startId); stopSelf(startId); } @Override public void checkMailFinished(Context context, Account account) { - - if (K9.DEBUG) - Log.v(K9.LOG_TAG, "***** PollService *****: checkMailFinished"); + Timber.v("***** PollService *****: checkMailFinished"); release(); } public int getStartId() { diff --git a/k9mail/src/main/java/com/fsck/k9/service/PushService.java b/k9mail/src/main/java/com/fsck/k9/service/PushService.java index 19de1ecf0..70bbc0bcd 100644 --- a/k9mail/src/main/java/com/fsck/k9/service/PushService.java +++ b/k9mail/src/main/java/com/fsck/k9/service/PushService.java @@ -3,7 +3,7 @@ package com.fsck.k9.service; import android.content.Context; import android.content.Intent; import android.os.IBinder; -import android.util.Log; +import timber.log.Timber; import com.fsck.k9.K9; public class PushService extends CoreService { @@ -30,11 +30,9 @@ public class PushService extends CoreService { public int startService(Intent intent, int startId) { int startFlag = START_STICKY; if (START_SERVICE.equals(intent.getAction())) { - if (K9.DEBUG) - Log.i(K9.LOG_TAG, "PushService started with startId = " + startId); + Timber.i("PushService started with startId = %d", startId); } else if (STOP_SERVICE.equals(intent.getAction())) { - if (K9.DEBUG) - Log.i(K9.LOG_TAG, "PushService stopping with startId = " + startId); + Timber.i("PushService stopping with startId = %d", startId); stopSelf(startId); startFlag = START_NOT_STICKY; } diff --git a/k9mail/src/main/java/com/fsck/k9/service/RemoteControlReceiver.java b/k9mail/src/main/java/com/fsck/k9/service/RemoteControlReceiver.java index ecdbf12d2..754bbe2a4 100644 --- a/k9mail/src/main/java/com/fsck/k9/service/RemoteControlReceiver.java +++ b/k9mail/src/main/java/com/fsck/k9/service/RemoteControlReceiver.java @@ -4,7 +4,7 @@ package com.fsck.k9.service; import android.content.Context; import android.content.Intent; import android.os.Bundle; -import android.util.Log; +import timber.log.Timber; import com.fsck.k9.Account; import com.fsck.k9.K9; @@ -18,8 +18,7 @@ import static com.fsck.k9.remotecontrol.K9RemoteControl.*; public class RemoteControlReceiver extends CoreReceiver { @Override public Integer receive(Context context, Intent intent, Integer tmpWakeLockId) { - if (K9.DEBUG) - Log.i(K9.LOG_TAG, "RemoteControlReceiver.onReceive" + intent); + Timber.i("RemoteControlReceiver.onReceive %s", intent); if (K9RemoteControl.K9_SET.equals(intent.getAction())) { RemoteControlService.set(context, intent, tmpWakeLockId); @@ -41,7 +40,7 @@ public class RemoteControlReceiver extends CoreReceiver { bundle.putStringArray(K9_ACCOUNT_UUIDS, uuids); bundle.putStringArray(K9_ACCOUNT_DESCRIPTIONS, descriptions); } catch (Exception e) { - Log.e(K9.LOG_TAG, "Could not handle K9_RESPONSE_INTENT", e); + Timber.e(e, "Could not handle K9_RESPONSE_INTENT"); } } diff --git a/k9mail/src/main/java/com/fsck/k9/service/RemoteControlService.java b/k9mail/src/main/java/com/fsck/k9/service/RemoteControlService.java index 8588d0635..8d57aaf4d 100644 --- a/k9mail/src/main/java/com/fsck/k9/service/RemoteControlService.java +++ b/k9mail/src/main/java/com/fsck/k9/service/RemoteControlService.java @@ -14,7 +14,7 @@ import static com.fsck.k9.remotecontrol.K9RemoteControl.*; import android.content.Context; import android.content.Intent; -import android.util.Log; +import timber.log.Timber; import android.widget.Toast; import java.util.List; @@ -37,22 +37,18 @@ public class RemoteControlService extends CoreService { @Override public int startService(final Intent intent, final int startId) { - if (K9.DEBUG) - Log.i(K9.LOG_TAG, "RemoteControlService started with startId = " + startId); + Timber.i("RemoteControlService started with startId = %d", startId); final Preferences preferences = Preferences.getPreferences(this); if (RESCHEDULE_ACTION.equals(intent.getAction())) { - if (K9.DEBUG) - Log.i(K9.LOG_TAG, "RemoteControlService requesting MailService poll reschedule"); + Timber.i("RemoteControlService requesting MailService poll reschedule"); MailService.actionReschedulePoll(this, null); } if (PUSH_RESTART_ACTION.equals(intent.getAction())) { - if (K9.DEBUG) - Log.i(K9.LOG_TAG, "RemoteControlService requesting MailService push restart"); + Timber.i("RemoteControlService requesting MailService push restart"); MailService.actionRestartPushers(this, null); } else if (RemoteControlService.SET_ACTION.equals(intent.getAction())) { - if (K9.DEBUG) - Log.i(K9.LOG_TAG, "RemoteControlService got request to change settings"); + Timber.i("RemoteControlService got request to change settings"); execute(getApplication(), new Runnable() { public void run() { try { @@ -60,20 +56,20 @@ public class RemoteControlService extends CoreService { boolean needsPushRestart = false; String uuid = intent.getStringExtra(K9_ACCOUNT_UUID); boolean allAccounts = intent.getBooleanExtra(K9_ALL_ACCOUNTS, false); - if (K9.DEBUG) { - if (allAccounts) { - Log.i(K9.LOG_TAG, "RemoteControlService changing settings for all accounts"); - } else { - Log.i(K9.LOG_TAG, "RemoteControlService changing settings for account with UUID " + uuid); - } + + if (allAccounts) { + Timber.i("RemoteControlService changing settings for all accounts"); + } else { + Timber.i("RemoteControlService changing settings for account with UUID %s", uuid); } + List accounts = preferences.getAccounts(); for (Account account : accounts) { //warning: account may not be isAvailable() if (allAccounts || account.getUuid().equals(uuid)) { - if (K9.DEBUG) - Log.i(K9.LOG_TAG, "RemoteControlService changing settings for account " + account.getDescription()); + Timber.i("RemoteControlService changing settings for account %s", + account.getDescription()); String notificationEnabled = intent.getStringExtra(K9_NOTIFICATION_ENABLED); String ringEnabled = intent.getStringExtra(K9_RING_ENABLED); @@ -109,8 +105,8 @@ public class RemoteControlService extends CoreService { account.save(Preferences.getPreferences(RemoteControlService.this)); } } - if (K9.DEBUG) - Log.i(K9.LOG_TAG, "RemoteControlService changing global settings"); + + Timber.i("RemoteControlService changing global settings"); String backgroundOps = intent.getStringExtra(K9_BACKGROUND_OPERATIONS); if (K9RemoteControl.K9_BACKGROUND_OPERATIONS_ALWAYS.equals(backgroundOps) @@ -146,7 +142,7 @@ public class RemoteControlService extends CoreService { BootReceiver.scheduleIntent(RemoteControlService.this, nextTime, i); } } catch (Exception e) { - Log.e(K9.LOG_TAG, "Could not handle K9_SET", e); + Timber.e(e, "Could not handle K9_SET"); Toast toast = Toast.makeText(RemoteControlService.this, e.getMessage(), Toast.LENGTH_LONG); toast.show(); } diff --git a/k9mail/src/main/java/com/fsck/k9/service/ShutdownReceiver.java b/k9mail/src/main/java/com/fsck/k9/service/ShutdownReceiver.java index 1ce0f7954..77e3120e8 100644 --- a/k9mail/src/main/java/com/fsck/k9/service/ShutdownReceiver.java +++ b/k9mail/src/main/java/com/fsck/k9/service/ShutdownReceiver.java @@ -3,7 +3,7 @@ package com.fsck.k9.service; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; -import android.util.Log; +import timber.log.Timber; import com.fsck.k9.K9; @@ -24,7 +24,7 @@ public class ShutdownReceiver extends BroadcastReceiver { @Override public void onReceive(final Context context, final Intent intent) { if (Intent.ACTION_SHUTDOWN.equals(intent.getAction())) { - Log.i(K9.LOG_TAG, "System is shutting down, releasing resources"); + Timber.i("System is shutting down, releasing resources"); // prevent any scheduled intent from waking up K-9 BootReceiver.purgeSchedule(context); diff --git a/k9mail/src/main/java/com/fsck/k9/service/SleepService.java b/k9mail/src/main/java/com/fsck/k9/service/SleepService.java index ba0b8436e..c88e9471e 100644 --- a/k9mail/src/main/java/com/fsck/k9/service/SleepService.java +++ b/k9mail/src/main/java/com/fsck/k9/service/SleepService.java @@ -2,7 +2,7 @@ package com.fsck.k9.service; import android.content.Context; import android.content.Intent; -import android.util.Log; +import timber.log.Timber; import com.fsck.k9.K9; import com.fsck.k9.mail.power.TracingPowerManager.TracingWakeLock; @@ -11,6 +11,9 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; +import static java.lang.Thread.currentThread; + + public class SleepService extends CoreService { private static String ALARM_FIRED = "com.fsck.k9.service.SleepService.ALARM_FIRED"; @@ -23,8 +26,8 @@ public class SleepService extends CoreService { public static void sleep(Context context, long sleepTime, TracingWakeLock wakeLock, long wakeLockTimeout) { Integer id = latchId.getAndIncrement(); - if (K9.DEBUG) - Log.d(K9.LOG_TAG, "SleepService Preparing CountDownLatch with id = " + id + ", thread " + Thread.currentThread().getName()); + Timber.d("SleepService Preparing CountDownLatch with id = %d, thread %s", id, currentThread().getName()); + SleepDatum sleepDatum = new SleepDatum(); CountDownLatch latch = new CountDownLatch(1); sleepDatum.latch = latch; @@ -45,23 +48,26 @@ public class SleepService extends CoreService { try { boolean countedDown = latch.await(sleepTime, TimeUnit.MILLISECONDS); if (!countedDown) { - if (K9.DEBUG) - Log.d(K9.LOG_TAG, "SleepService latch timed out for id = " + id + ", thread " + Thread.currentThread().getName()); + Timber.d("SleepService latch timed out for id = %d, thread %s", id, currentThread().getName()); } } catch (InterruptedException ie) { - Log.e(K9.LOG_TAG, "SleepService Interrupted while awaiting latch", ie); + Timber.e(ie, "SleepService Interrupted while awaiting latch"); } SleepDatum releaseDatum = sleepData.remove(id); if (releaseDatum == null) { try { - if (K9.DEBUG) - Log.d(K9.LOG_TAG, "SleepService waiting for reacquireLatch for id = " + id + ", thread " + Thread.currentThread().getName()); + Timber.d("SleepService waiting for reacquireLatch for id = %d, thread %s", + id, currentThread().getName()); + if (!sleepDatum.reacquireLatch.await(5000, TimeUnit.MILLISECONDS)) { - Log.w(K9.LOG_TAG, "SleepService reacquireLatch timed out for id = " + id + ", thread " + Thread.currentThread().getName()); - } else if (K9.DEBUG) - Log.d(K9.LOG_TAG, "SleepService reacquireLatch finished for id = " + id + ", thread " + Thread.currentThread().getName()); + Timber.w("SleepService reacquireLatch timed out for id = %d, thread %s", + id, currentThread().getName()); + } else { + Timber.d("SleepService reacquireLatch finished for id = %d, thread %s", + id, currentThread().getName()); + } } catch (InterruptedException ie) { - Log.e(K9.LOG_TAG, "SleepService Interrupted while awaiting reacquireLatch", ie); + Timber.e(ie, "SleepService Interrupted while awaiting reacquireLatch"); } } else { reacquireWakeLock(releaseDatum); @@ -71,10 +77,9 @@ public class SleepService extends CoreService { long actualSleep = endTime - startTime; if (actualSleep < sleepTime) { - Log.w(K9.LOG_TAG, "SleepService sleep time too short: requested was " + sleepTime + ", actual was " + actualSleep); + Timber.w("SleepService sleep time too short: requested was %d, actual was %d", sleepTime, actualSleep); } else { - if (K9.DEBUG) - Log.d(K9.LOG_TAG, "SleepService requested sleep time was " + sleepTime + ", actual was " + actualSleep); + Timber.d("SleepService requested sleep time was %d, actual was %d", sleepTime, actualSleep); } } @@ -84,17 +89,15 @@ public class SleepService extends CoreService { if (sleepDatum != null) { CountDownLatch latch = sleepDatum.latch; if (latch == null) { - Log.e(K9.LOG_TAG, "SleepService No CountDownLatch available with id = " + id); + Timber.e("SleepService No CountDownLatch available with id = %s", id); } else { - if (K9.DEBUG) - Log.d(K9.LOG_TAG, "SleepService Counting down CountDownLatch with id = " + id); + Timber.d("SleepService Counting down CountDownLatch with id = %d", id); latch.countDown(); } reacquireWakeLock(sleepDatum); sleepDatum.reacquireLatch.countDown(); } else { - if (K9.DEBUG) - Log.d(K9.LOG_TAG, "SleepService Sleep for id " + id + " already finished"); + Timber.d("SleepService Sleep for id %d already finished", id); } } } @@ -104,8 +107,7 @@ public class SleepService extends CoreService { if (wakeLock != null) { synchronized (wakeLock) { long timeout = sleepDatum.timeout; - if (K9.DEBUG) - Log.d(K9.LOG_TAG, "SleepService Acquiring wakeLock for " + timeout + "ms"); + Timber.d("SleepService Acquiring wakeLock for %d ms", timeout); wakeLock.acquire(timeout); } } diff --git a/k9mail/src/main/java/com/fsck/k9/service/StorageGoneReceiver.java b/k9mail/src/main/java/com/fsck/k9/service/StorageGoneReceiver.java index 26be4da34..2cf6b91c5 100644 --- a/k9mail/src/main/java/com/fsck/k9/service/StorageGoneReceiver.java +++ b/k9mail/src/main/java/com/fsck/k9/service/StorageGoneReceiver.java @@ -4,7 +4,7 @@ import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.net.Uri; -import android.util.Log; +import timber.log.Timber; import com.fsck.k9.K9; import com.fsck.k9.mailstore.StorageManager; @@ -28,9 +28,7 @@ public class StorageGoneReceiver extends BroadcastReceiver { return; } - if (K9.DEBUG) { - Log.v(K9.LOG_TAG, "StorageGoneReceiver: " + intent.toString()); - } + Timber.v("StorageGoneReceiver: %s", intent); final String path = uri.getPath(); diff --git a/k9mail/src/main/java/com/fsck/k9/service/StorageReceiver.java b/k9mail/src/main/java/com/fsck/k9/service/StorageReceiver.java index 0d34fbb94..33abff752 100644 --- a/k9mail/src/main/java/com/fsck/k9/service/StorageReceiver.java +++ b/k9mail/src/main/java/com/fsck/k9/service/StorageReceiver.java @@ -4,7 +4,7 @@ import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.net.Uri; -import android.util.Log; +import timber.log.Timber; import com.fsck.k9.K9; import com.fsck.k9.mailstore.StorageManager; @@ -23,9 +23,7 @@ public class StorageReceiver extends BroadcastReceiver { return; } - if (K9.DEBUG) { - Log.v(K9.LOG_TAG, "StorageReceiver: " + intent.toString()); - } + Timber.v("StorageReceiver: %s", intent); final String path = uri.getPath(); diff --git a/k9mail/src/main/java/com/fsck/k9/ui/compose/QuotedMessagePresenter.java b/k9mail/src/main/java/com/fsck/k9/ui/compose/QuotedMessagePresenter.java index 53882b65c..1e8beb103 100644 --- a/k9mail/src/main/java/com/fsck/k9/ui/compose/QuotedMessagePresenter.java +++ b/k9mail/src/main/java/com/fsck/k9/ui/compose/QuotedMessagePresenter.java @@ -5,7 +5,7 @@ import java.util.Map; import android.content.res.Resources; import android.os.Bundle; -import android.util.Log; +import timber.log.Timber; import com.fsck.k9.Account; import com.fsck.k9.Account.MessageFormat; @@ -190,7 +190,7 @@ public class QuotedMessagePresenter { try { cursorPosition = Integer.parseInt(k9identity.get(IdentityField.CURSOR_POSITION)); } catch (Exception e) { - Log.e(K9.LOG_TAG, "Could not parse cursor position for MessageCompose; continuing.", e); + Timber.e(e, "Could not parse cursor position for MessageCompose; continuing."); } } @@ -250,14 +250,13 @@ public class QuotedMessagePresenter { if (part != null) { // Shouldn't happen if we were the one who saved it. quotedTextFormat = SimpleMessageFormat.HTML; String text = MessageExtractor.getTextFromPart(part); - if (K9.DEBUG) { - Log.d(K9.LOG_TAG, "Loading message with offset " + bodyOffset + ", length " + bodyLength + - ". Text length is " + text.length() + "."); - } + + Timber.d("Loading message with offset %d, length %d. Text length is %d.", + bodyOffset, bodyLength, text.length()); if (bodyOffset + bodyLength > text.length()) { // The draft was edited outside of K-9 Mail? - Log.d(K9.LOG_TAG, "The identity field from the draft contains an invalid LENGTH/OFFSET"); + Timber.d("The identity field from the draft contains an invalid LENGTH/OFFSET"); bodyOffset = 0; bodyLength = 0; } @@ -291,14 +290,14 @@ public class QuotedMessagePresenter { quotedTextFormat = SimpleMessageFormat.TEXT; processSourceMessageText(messageViewInfo.rootPart, bodyOffset, bodyLength, true); } else { - Log.e(K9.LOG_TAG, "Unhandled message format."); + Timber.e("Unhandled message format."); } // Set the cursor position if we have it. try { view.setMessageContentCursorPosition(cursorPosition); } catch (Exception e) { - Log.e(K9.LOG_TAG, "Could not set cursor position in MessageCompose; ignoring.", e); + Timber.e(e, "Could not set cursor position in MessageCompose; ignoring."); } showOrHideQuotedText(quotedMode); @@ -319,10 +318,9 @@ public class QuotedMessagePresenter { } String messageText = MessageExtractor.getTextFromPart(textPart); - if (K9.DEBUG) { - Log.d(K9.LOG_TAG, "Loading message with offset " + bodyOffset + ", length " + bodyLength + - ". Text length is " + messageText.length() + "."); - } + + Timber.d("Loading message with offset %d, length %d. Text length is %d.", + bodyOffset, bodyLength, messageText.length()); // If we had a body length (and it was valid), separate the composition from the quoted text // and put them in their respective places in the UI. @@ -348,7 +346,7 @@ public class QuotedMessagePresenter { messageText = messageText.substring(bodyOffset, bodyOffset + bodyLength); } catch (IndexOutOfBoundsException e) { // Invalid bodyOffset or bodyLength. The draft was edited outside of K-9 Mail? - Log.d(K9.LOG_TAG, "The identity field from the draft contains an invalid bodyOffset/bodyLength"); + Timber.d("The identity field from the draft contains an invalid bodyOffset/bodyLength"); } } diff --git a/k9mail/src/main/java/com/fsck/k9/ui/crypto/MessageCryptoHelper.java b/k9mail/src/main/java/com/fsck/k9/ui/crypto/MessageCryptoHelper.java index 68715e93e..43ccf6de9 100644 --- a/k9mail/src/main/java/com/fsck/k9/ui/crypto/MessageCryptoHelper.java +++ b/k9mail/src/main/java/com/fsck/k9/ui/crypto/MessageCryptoHelper.java @@ -16,7 +16,7 @@ import android.content.Intent; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.annotation.WorkerThread; -import android.util.Log; +import timber.log.Timber; import com.fsck.k9.K9; import com.fsck.k9.crypto.MessageDecryptVerifier; @@ -226,7 +226,7 @@ public class MessageCryptoHelper { @Override public void onError(Exception e) { // TODO actually handle (hand to ui, offer retry?) - Log.e(K9.LOG_TAG, "Couldn't connect to OpenPgpService", e); + Timber.e(e, "Couldn't connect to OpenPgpService"); } }); openPgpServiceConnection.bindToService(); @@ -276,9 +276,9 @@ public class MessageCryptoHelper { throw new IllegalStateException("Unknown crypto part type: " + cryptoPartType); } catch (IOException e) { - Log.e(K9.LOG_TAG, "IOException", e); + Timber.e(e, "IOException"); } catch (MessagingException e) { - Log.e(K9.LOG_TAG, "MessagingException", e); + Timber.e(e, "MessagingException"); } } @@ -290,7 +290,7 @@ public class MessageCryptoHelper { new IOpenPgpSinkResultCallback() { @Override public void onProgress(int current, int max) { - Log.d(K9.LOG_TAG, "received progress status: " + current + " / " + max); + Timber.d("received progress status: %d / %d", current, max); callbackProgress(current, max); } @@ -321,7 +321,7 @@ public class MessageCryptoHelper { TextBody body = new TextBody(new String(decryptedByteOutputStream.toByteArray())); return new MimeBodyPart(body, "text/plain"); } catch (MessagingException e) { - Log.e(K9.LOG_TAG, "MessagingException", e); + Timber.e(e, "MessagingException"); } return null; @@ -344,7 +344,7 @@ public class MessageCryptoHelper { @Override public void onProgress(int current, int max) { - Log.d(K9.LOG_TAG, "received progress status: " + current + " / " + max); + Timber.d("received progress status: %d / %d", current, max); callbackProgress(current, max); } }); @@ -366,7 +366,7 @@ public class MessageCryptoHelper { @Override public void onProgress(int current, int max) { - Log.d(K9.LOG_TAG, "received progress status: " + current + " / " + max); + Timber.d("received progress status: %d / %d", current, max); callbackProgress(current, max); } }); @@ -379,10 +379,10 @@ public class MessageCryptoHelper { try { Multipart multipartSignedMultipart = (Multipart) signedPart.getBody(); BodyPart signatureBodyPart = multipartSignedMultipart.getBodyPart(0); - Log.d(K9.LOG_TAG, "signed data type: " + signatureBodyPart.getMimeType()); + Timber.d("signed data type: %s", signatureBodyPart.getMimeType()); signatureBodyPart.writeTo(os); } catch (MessagingException e) { - Log.e(K9.LOG_TAG, "Exception while writing message to crypto provider", e); + Timber.e(e, "Exception while writing message to crypto provider"); } } }; @@ -431,7 +431,7 @@ public class MessageCryptoHelper { throw new IllegalStateException("part to stream must be encrypted or inline!"); } } catch (MessagingException e) { - Log.e(K9.LOG_TAG, "MessagingException while writing message to crypto provider", e); + Timber.e(e, "MessagingException while writing message to crypto provider"); } } }; @@ -447,7 +447,7 @@ public class MessageCryptoHelper { DecryptedFileProvider.getFileFactory(context); return MimePartStreamParser.parse(fileFactory, is); } catch (MessagingException e) { - Log.e(K9.LOG_TAG, "Something went wrong while parsing the decrypted MIME part", e); + Timber.e(e, "Something went wrong while parsing the decrypted MIME part"); //TODO: pass error to main thread and display error message to user return null; } @@ -457,7 +457,7 @@ public class MessageCryptoHelper { private void onCryptoOperationReturned(MimeBodyPart decryptedPart) { if (currentCryptoResult == null) { - Log.e(K9.LOG_TAG, "Internal error: we should have a result here!"); + Timber.e("Internal error: we should have a result here!"); return; } @@ -470,13 +470,11 @@ public class MessageCryptoHelper { private void handleCryptoOperationResult(MimeBodyPart outputPart) { int resultCode = currentCryptoResult.getIntExtra(OpenPgpApi.RESULT_CODE, INVALID_OPENPGP_RESULT_CODE); - if (K9.DEBUG) { - Log.d(K9.LOG_TAG, "OpenPGP API decryptVerify result code: " + resultCode); - } + Timber.d("OpenPGP API decryptVerify result code: %d", resultCode); switch (resultCode) { case INVALID_OPENPGP_RESULT_CODE: { - Log.e(K9.LOG_TAG, "Internal error: no result code!"); + Timber.e("Internal error: no result code!"); break; } case OpenPgpApi.RESULT_CODE_USER_INTERACTION_REQUIRED: { @@ -505,9 +503,7 @@ public class MessageCryptoHelper { private void handleCryptoOperationError() { OpenPgpError error = currentCryptoResult.getParcelableExtra(OpenPgpApi.RESULT_ERROR); - if (K9.DEBUG) { - Log.w(K9.LOG_TAG, "OpenPGP API error: " + error.getMessage()); - } + Timber.w("OpenPGP API error: %s", error.getMessage()); onCryptoOperationFailed(error); } @@ -596,7 +592,7 @@ public class MessageCryptoHelper { partsToDecryptOrVerify.removeFirst(); currentCryptoPart = null; } else { - Log.e(K9.LOG_TAG, "Got to onCryptoFinished() with no part in processing!", new Throwable()); + Timber.e(new Throwable(), "Got to onCryptoFinished() with no part in processing!"); } decryptOrVerifyNextPart(); } @@ -634,7 +630,7 @@ public class MessageCryptoHelper { boolean hasCachedResult = queuedResult != null || queuedPendingIntent != null; if (hasCachedResult) { - Log.d(K9.LOG_TAG, "Returning cached result or pending intent to reattached callback"); + Timber.d("Returning cached result or pending intent to reattached callback"); deliverResult(); } } @@ -673,7 +669,7 @@ public class MessageCryptoHelper { } if (callback == null) { - Log.d(K9.LOG_TAG, "Keeping crypto helper result in queue for later delivery"); + Timber.d("Keeping crypto helper result in queue for later delivery"); return; } if (queuedResult != null) { @@ -721,12 +717,12 @@ public class MessageCryptoHelper { String clearsignedText = MessageExtractor.getTextFromPart(part); String replacementText = OpenPgpUtils.extractClearsignedMessage(clearsignedText); if (replacementText == null) { - Log.e(K9.LOG_TAG, "failed to extract clearsigned text for replacement part"); + Timber.e("failed to extract clearsigned text for replacement part"); return NO_REPLACEMENT_PART; } return new MimeBodyPart(new TextBody(replacementText), "text/plain"); } catch (MessagingException e) { - Log.e(K9.LOG_TAG, "failed to create clearsigned text replacement part", e); + Timber.e(e, "failed to create clearsigned text replacement part"); return NO_REPLACEMENT_PART; } } diff --git a/k9mail/src/main/java/com/fsck/k9/ui/message/LocalMessageExtractorLoader.java b/k9mail/src/main/java/com/fsck/k9/ui/message/LocalMessageExtractorLoader.java index e2f153d4a..199ba1053 100644 --- a/k9mail/src/main/java/com/fsck/k9/ui/message/LocalMessageExtractorLoader.java +++ b/k9mail/src/main/java/com/fsck/k9/ui/message/LocalMessageExtractorLoader.java @@ -5,7 +5,7 @@ import android.content.AsyncTaskLoader; import android.content.Context; import android.support.annotation.Nullable; import android.support.annotation.WorkerThread; -import android.util.Log; +import timber.log.Timber; import com.fsck.k9.K9; import com.fsck.k9.mail.Message; @@ -54,7 +54,7 @@ public class LocalMessageExtractorLoader extends AsyncTaskLoader { try { return loadMessageFromDatabase(); } catch (Exception e) { - Log.e(K9.LOG_TAG, "Error while loading message from database", e); + Timber.e(e, "Error while loading message from database"); return null; } } diff --git a/k9mail/src/main/java/com/fsck/k9/ui/messageview/AttachmentController.java b/k9mail/src/main/java/com/fsck/k9/ui/messageview/AttachmentController.java index 86e4dff64..5164e691f 100644 --- a/k9mail/src/main/java/com/fsck/k9/ui/messageview/AttachmentController.java +++ b/k9mail/src/main/java/com/fsck/k9/ui/messageview/AttachmentController.java @@ -18,7 +18,7 @@ import android.net.Uri; import android.os.AsyncTask; import android.os.Environment; import android.support.annotation.WorkerThread; -import android.util.Log; +import timber.log.Timber; import android.widget.Toast; import com.fsck.k9.Account; @@ -181,7 +181,7 @@ public class AttachmentController { try { intentDataUri = AttachmentTempFileProvider.createTempUriForContentUri(context, attachment.internalUri); } catch (IOException e) { - Log.e(K9.LOG_TAG, "Error creating temp file for attachment!", e); + Timber.e(e, "Error creating temp file for attachment!"); return null; } @@ -211,9 +211,7 @@ public class AttachmentController { writeAttachmentToStorage(tempFile); viewIntent = createViewIntentForFileUri(resolvedIntentInfo.getMimeType(), Uri.fromFile(tempFile)); } catch (IOException e) { - if (K9.DEBUG) { - Log.e(K9.LOG_TAG, "Error while saving attachment to use file:// URI with ACTION_VIEW Intent", e); - } + Timber.e(e, "Error while saving attachment to use file:// URI with ACTION_VIEW Intent"); viewIntent = createViewIntentForAttachmentProviderUri(intentDataUri, MimeUtility.DEFAULT_ATTACHMENT_MIME_TYPE); } } else { @@ -332,7 +330,7 @@ public class AttachmentController { try { context.startActivity(intent); } catch (ActivityNotFoundException e) { - Log.e(K9.LOG_TAG, "Could not display attachment of type " + attachment.mimeType, e); + Timber.e(e, "Could not display attachment of type %s", attachment.mimeType); String message = context.getString(R.string.message_view_no_viewer, attachment.mimeType); displayMessageToUser(message); @@ -353,9 +351,7 @@ public class AttachmentController { File directory = params[0]; return saveAttachmentWithUniqueFileName(directory); } catch (IOException e) { - if (K9.DEBUG) { - Log.e(K9.LOG_TAG, "Error saving attachment", e); - } + Timber.e(e, "Error saving attachment"); return null; } } diff --git a/k9mail/src/main/java/com/fsck/k9/ui/messageview/DownloadImageTask.java b/k9mail/src/main/java/com/fsck/k9/ui/messageview/DownloadImageTask.java index 827bf33d3..a28fe3780 100644 --- a/k9mail/src/main/java/com/fsck/k9/ui/messageview/DownloadImageTask.java +++ b/k9mail/src/main/java/com/fsck/k9/ui/messageview/DownloadImageTask.java @@ -13,7 +13,7 @@ import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.os.AsyncTask; -import android.util.Log; +import timber.log.Timber; import android.widget.Toast; import com.fsck.k9.K9; @@ -57,7 +57,7 @@ class DownloadImageTask extends AsyncTask { return fileName; } catch (Exception e) { - Log.e(K9.LOG_TAG, "Error while downloading image", e); + Timber.e(e, "Error while downloading image"); return null; } } diff --git a/k9mail/src/main/java/com/fsck/k9/ui/messageview/MessageCryptoPresenter.java b/k9mail/src/main/java/com/fsck/k9/ui/messageview/MessageCryptoPresenter.java index c1722aefb..6365ed059 100644 --- a/k9mail/src/main/java/com/fsck/k9/ui/messageview/MessageCryptoPresenter.java +++ b/k9mail/src/main/java/com/fsck/k9/ui/messageview/MessageCryptoPresenter.java @@ -12,7 +12,7 @@ import android.os.Bundle; import android.os.Parcelable; import android.support.annotation.Nullable; import android.support.annotation.StringRes; -import android.util.Log; +import timber.log.Timber; import com.fsck.k9.Account; import com.fsck.k9.K9; @@ -200,7 +200,7 @@ public class MessageCryptoPresenter implements OnCryptoClickListener { pendingIntent.getIntentSender(), REQUEST_CODE_UNKNOWN_KEY, null, 0, 0, 0); } } catch (IntentSender.SendIntentException e) { - Log.e(K9.LOG_TAG, "SendIntentException", e); + Timber.e(e, "SendIntentException"); } } @@ -212,7 +212,7 @@ public class MessageCryptoPresenter implements OnCryptoClickListener { pendingIntent.getIntentSender(), null, null, 0, 0, 0); } } catch (IntentSender.SendIntentException e) { - Log.e(K9.LOG_TAG, "SendIntentException", e); + Timber.e(e, "SendIntentException"); } } diff --git a/k9mail/src/main/java/com/fsck/k9/ui/messageview/MessageViewFragment.java b/k9mail/src/main/java/com/fsck/k9/ui/messageview/MessageViewFragment.java index 2211f79cb..35b7bf4cb 100644 --- a/k9mail/src/main/java/com/fsck/k9/ui/messageview/MessageViewFragment.java +++ b/k9mail/src/main/java/com/fsck/k9/ui/messageview/MessageViewFragment.java @@ -18,7 +18,7 @@ import android.os.Bundle; import android.os.Handler; import android.os.Parcelable; import android.text.TextUtils; -import android.util.Log; +import timber.log.Timber; import android.view.ContextThemeWrapper; import android.view.KeyEvent; import android.view.LayoutInflater; @@ -208,9 +208,7 @@ public class MessageViewFragment extends Fragment implements ConfirmationDialogF private void displayMessage(MessageReference messageReference) { mMessageReference = messageReference; - if (K9.DEBUG) { - Log.d(K9.LOG_TAG, "MessageView displaying message " + mMessageReference); - } + Timber.d("MessageView displaying message %s", mMessageReference); mAccount = Preferences.getPreferences(getApplicationContext()).getAccount(mMessageReference.getAccountUuid()); messageLoaderHelper.asyncStartOrResumeLoadingMessage(messageReference, null); @@ -789,7 +787,7 @@ public class MessageViewFragment extends Fragment implements ConfirmationDialogF getActivity().startIntentSenderForResult( si, requestCode, fillIntent, flagsMask, flagValues, extraFlags); } catch (SendIntentException e) { - Log.e(K9.LOG_TAG, "Irrecoverable error calling PendingIntent!", e); + Timber.e(e, "Irrecoverable error calling PendingIntent!"); } } }; diff --git a/k9mail/src/main/java/com/fsck/k9/view/ClientCertificateSpinner.java b/k9mail/src/main/java/com/fsck/k9/view/ClientCertificateSpinner.java index 9f6a10d45..b72fb8264 100644 --- a/k9mail/src/main/java/com/fsck/k9/view/ClientCertificateSpinner.java +++ b/k9mail/src/main/java/com/fsck/k9/view/ClientCertificateSpinner.java @@ -9,7 +9,7 @@ import android.content.Context; import android.security.KeyChain; import android.security.KeyChainAliasCallback; import android.util.AttributeSet; -import android.util.Log; +import timber.log.Timber; import android.view.LayoutInflater; import android.view.View; import android.widget.Button; @@ -39,7 +39,7 @@ public class ClientCertificateSpinner extends LinearLayout { if (context instanceof Activity) { mActivity = (Activity) context; } else { - Log.e(K9.LOG_TAG, "ClientCertificateSpinner init failed! Please inflate with Activity!"); + Timber.e("ClientCertificateSpinner init failed! Please inflate with Activity!"); } setOrientation(LinearLayout.HORIZONTAL); @@ -102,8 +102,7 @@ public class ClientCertificateSpinner extends LinearLayout { KeyChain.choosePrivateKeyAlias(mActivity, new KeyChainAliasCallback() { @Override public void alias(String alias) { - if (K9.DEBUG) - Log.d(K9.LOG_TAG, "User has selected client certificate alias: " + alias); + Timber.d("User has selected client certificate alias: %s", alias); setAlias(alias); } diff --git a/k9mail/src/main/java/com/fsck/k9/view/K9WebViewClient.java b/k9mail/src/main/java/com/fsck/k9/view/K9WebViewClient.java index 930ee0b3b..a31c930e8 100644 --- a/k9mail/src/main/java/com/fsck/k9/view/K9WebViewClient.java +++ b/k9mail/src/main/java/com/fsck/k9/view/K9WebViewClient.java @@ -14,7 +14,7 @@ import android.os.Build.VERSION_CODES; import android.provider.Browser; import android.support.annotation.Nullable; import android.text.TextUtils; -import android.util.Log; +import timber.log.Timber; import android.webkit.WebResourceRequest; import android.webkit.WebResourceResponse; import android.webkit.WebView; @@ -111,7 +111,7 @@ abstract class K9WebViewClient extends WebViewClient { return new WebResourceResponse(mimeType, null, inputStream); } catch (Exception e) { - Log.e(K9.LOG_TAG, "Error while intercepting URI: " + uri, e); + Timber.e(e, "Error while intercepting URI: %s", uri); return RESULT_DUMMY_RESPONSE; } } diff --git a/k9mail/src/main/java/com/fsck/k9/view/MessageHeader.java b/k9mail/src/main/java/com/fsck/k9/view/MessageHeader.java index b2b6db860..ce008876e 100644 --- a/k9mail/src/main/java/com/fsck/k9/view/MessageHeader.java +++ b/k9mail/src/main/java/com/fsck/k9/view/MessageHeader.java @@ -17,7 +17,7 @@ import android.text.TextUtils; import android.text.format.DateUtils; import android.text.style.StyleSpan; import android.util.AttributeSet; -import android.util.Log; +import timber.log.Timber; import android.view.Gravity; import android.view.View; import android.view.View.OnClickListener; @@ -188,7 +188,7 @@ public class MessageHeader extends LinearLayout implements OnClickListener, OnLo final Address senderEmail = mMessage.getFrom()[0]; mContacts.createContact(senderEmail); } catch (Exception e) { - Log.e(K9.LOG_TAG, "Couldn't create contact", e); + Timber.e(e, "Couldn't create contact"); } } } diff --git a/k9mail/src/main/java/com/fsck/k9/view/MessageWebView.java b/k9mail/src/main/java/com/fsck/k9/view/MessageWebView.java index dc6b93995..16d451f76 100644 --- a/k9mail/src/main/java/com/fsck/k9/view/MessageWebView.java +++ b/k9mail/src/main/java/com/fsck/k9/view/MessageWebView.java @@ -6,7 +6,7 @@ import android.content.pm.PackageManager; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.AttributeSet; -import android.util.Log; +import timber.log.Timber; import android.view.KeyEvent; import android.webkit.WebSettings; import android.webkit.WebSettings.LayoutAlgorithm; @@ -146,7 +146,7 @@ public class MessageWebView extends RigidWebView { shiftPressEvent.dispatch(this, null, null); Toast.makeText(getContext() , R.string.select_text_now, Toast.LENGTH_SHORT).show(); } catch (Exception e) { - Log.e(K9.LOG_TAG, "Exception in emulateShiftHeld()", e); + Timber.e(e, "Exception in emulateShiftHeld()"); } } diff --git a/k9mail/src/main/java/com/fsck/k9/view/RecipientSelectView.java b/k9mail/src/main/java/com/fsck/k9/view/RecipientSelectView.java index 13a3edbee..a731e9032 100644 --- a/k9mail/src/main/java/com/fsck/k9/view/RecipientSelectView.java +++ b/k9mail/src/main/java/com/fsck/k9/view/RecipientSelectView.java @@ -22,7 +22,7 @@ import android.support.annotation.Nullable; import android.text.Editable; import android.text.TextUtils; import android.util.AttributeSet; -import android.util.Log; +import timber.log.Timber; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.MotionEvent; @@ -409,7 +409,7 @@ public class RecipientSelectView extends TokenCompleteTextView implem List currentRecipients = getObjects(); int indexOfRecipient = currentRecipients.indexOf(recipientToReplace); if (indexOfRecipient == -1) { - Log.e(K9.LOG_TAG, "Tried to refresh invalid view token!"); + Timber.e("Tried to refresh invalid view token!"); return; } Recipient currentRecipient = currentRecipients.get(indexOfRecipient); @@ -420,7 +420,7 @@ public class RecipientSelectView extends TokenCompleteTextView implem View recipientTokenView = getTokenViewForRecipient(currentRecipient); if (recipientTokenView == null) { - Log.e(K9.LOG_TAG, "Tried to refresh invalid view token!"); + Timber.e("Tried to refresh invalid view token!"); return; } diff --git a/k9mail/src/main/java/com/fsck/k9/view/RigidWebView.java b/k9mail/src/main/java/com/fsck/k9/view/RigidWebView.java index 43e344ba5..1ac137b05 100644 --- a/k9mail/src/main/java/com/fsck/k9/view/RigidWebView.java +++ b/k9mail/src/main/java/com/fsck/k9/view/RigidWebView.java @@ -20,7 +20,7 @@ package com.fsck.k9.view; import android.content.Context; import android.os.Build; import android.util.AttributeSet; -import android.util.Log; +import timber.log.Timber; import android.webkit.WebView; import com.fsck.k9.Clock; @@ -82,9 +82,7 @@ public class RigidWebView extends WebView { if (mIgnoreNext) { mIgnoreNext = false; if (recentlySized) { - if (K9.DEBUG) { - Log.w(K9.LOG_TAG, "Supressing size change in RigidWebView"); - } + Timber.w("Supressing size change in RigidWebView"); return; } } diff --git a/k9mail/src/test/java/com/fsck/k9/activity/ActivityListenerTest.java b/k9mail/src/test/java/com/fsck/k9/activity/ActivityListenerTest.java index 660fa1ea4..f05813fc5 100644 --- a/k9mail/src/test/java/com/fsck/k9/activity/ActivityListenerTest.java +++ b/k9mail/src/test/java/com/fsck/k9/activity/ActivityListenerTest.java @@ -75,7 +75,7 @@ public class ActivityListenerTest { String operation = activityListener.getOperation(context); - if (K9.DEBUG) { + if (K9.isDebug()) { assertEquals("Polling and pushing disabled", operation); } else { assertEquals("Syncing disabled", operation); @@ -90,7 +90,7 @@ public class ActivityListenerTest { String operation = activityListener.getOperation(context); - if (K9.DEBUG) { + if (K9.isDebug()) { assertEquals("Polling and pushing disabled", operation); } else { assertEquals("Syncing disabled", operation); @@ -104,7 +104,7 @@ public class ActivityListenerTest { String operation = activityListener.getOperation(context); - if (K9.DEBUG) { + if (K9.isDebug()) { assertEquals("Polling and pushing disabled", operation); } else { assertEquals("Syncing disabled", operation); diff --git a/k9mail/src/test/java/com/fsck/k9/controller/MessagingControllerTest.java b/k9mail/src/test/java/com/fsck/k9/controller/MessagingControllerTest.java index bfdcf8d26..9aad30463 100644 --- a/k9mail/src/test/java/com/fsck/k9/controller/MessagingControllerTest.java +++ b/k9mail/src/test/java/com/fsck/k9/controller/MessagingControllerTest.java @@ -183,7 +183,7 @@ public class MessagingControllerTest { @Test() public void clearFolderSynchronous_whenExceptionThrown_shouldAddErrorMessageInDebug() throws MessagingException { - if (K9.DEBUG) { + if (K9.isDebug()) { doThrow(new RuntimeException("Test")).when(localFolder).open(Folder.OPEN_MODE_RW); controller.clearFolderSynchronous(account, FOLDER_NAME, listener); diff --git a/k9mail/src/test/java/com/fsck/k9/mailstore/MigrationTest.java b/k9mail/src/test/java/com/fsck/k9/mailstore/MigrationTest.java index a5f74fc8f..21e589010 100644 --- a/k9mail/src/test/java/com/fsck/k9/mailstore/MigrationTest.java +++ b/k9mail/src/test/java/com/fsck/k9/mailstore/MigrationTest.java @@ -42,7 +42,7 @@ public class MigrationTest { @Before public void setUp() throws Exception { - K9.DEBUG = true; + K9.setDebug(true); ShadowLog.stream = System.out; ShadowSQLiteConnection.reset();