From 69981855f79bf547daa4f13c81f11183c28e7d35 Mon Sep 17 00:00:00 2001
From: Thibault Wittemberg <thibault.wittemberg@savoirfairelinux.com>
Date: Thu, 6 Jul 2017 12:12:35 -0400
Subject: [PATCH] project: add SwiftyBeaver for log

SwiftyBeaver improves log readability and allows
to use different logging levels and different kinds of
outputs. Way better than simples "print()"

Change-Id: Iaa3087952095d4344b3cd85314892c4fcd25251c
---
 Ring/Cartfile                                 |  1 +
 Ring/Cartfile.resolved                        |  1 +
 Ring/Ring.xcodeproj/project.pbxproj           |  5 +++++
 Ring/Ring/Account/AccountConfigModel.swift    |  8 +++++++-
 Ring/Ring/Account/AccountModelHelper.swift    | 11 ++++++++--
 Ring/Ring/AppDelegate.swift                   | 20 +++++++++++++------
 Ring/Ring/Contacts/ContactViewModel.swift     |  8 +++++++-
 .../Conversations/ConversationViewModel.swift | 16 ++++++++++-----
 Ring/Ring/Services/AccountsService.swift      | 19 ++++++++++++------
 Ring/Ring/Services/ConversationsService.swift | 13 ++++++++----
 Ring/Ring/Services/DaemonService.swift        | 17 +++++++++++-----
 Ring/Ring/Services/NameService.swift          | 11 +++++++---
 .../CreateRingAccountViewController.swift     |  9 +++++++--
 13 files changed, 104 insertions(+), 35 deletions(-)

diff --git a/Ring/Cartfile b/Ring/Cartfile
index 6d7f438ad..2c88dc47e 100644
--- a/Ring/Cartfile
+++ b/Ring/Cartfile
@@ -2,3 +2,4 @@ github "RxSwiftCommunity/RxRealm"
 github "RxSwiftCommunity/RxDataSources" == 1.0.3
 github "pkluz/PKHUD"
 github "AliSoftware/Reusable" ~> 4.0
+github "SwiftyBeaver/SwiftyBeaver"
diff --git a/Ring/Cartfile.resolved b/Ring/Cartfile.resolved
index e2c6be117..d31aa67fc 100644
--- a/Ring/Cartfile.resolved
+++ b/Ring/Cartfile.resolved
@@ -2,5 +2,6 @@ github "AliSoftware/Reusable" "4.0.1"
 github "ReactiveX/RxSwift" "3.5.0"
 github "RxSwiftCommunity/RxDataSources" "1.0.4"
 github "RxSwiftCommunity/RxRealm" "0.6.0"
+github "SwiftyBeaver/SwiftyBeaver" "1.3.0"
 github "pkluz/PKHUD" "4.2.3"
 github "realm/realm-cocoa" "v2.8.3"
diff --git a/Ring/Ring.xcodeproj/project.pbxproj b/Ring/Ring.xcodeproj/project.pbxproj
index 4cd68298e..48fd34789 100644
--- a/Ring/Ring.xcodeproj/project.pbxproj
+++ b/Ring/Ring.xcodeproj/project.pbxproj
@@ -93,6 +93,7 @@
 		04399B141D1C341A00E99CD9 /* libx264.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 04399AE21D1C341A00E99CD9 /* libx264.a */; };
 		04399B151D1C341A00E99CD9 /* libyaml-cpp.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 04399AE31D1C341A00E99CD9 /* libyaml-cpp.a */; };
 		1A1E476D1F0E808500EA9A36 /* Reusable.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 1A1E476C1F0E808500EA9A36 /* Reusable.framework */; };
+		1A1E476F1F0E894600EA9A36 /* SwiftyBeaver.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 1A1E476E1F0E894600EA9A36 /* SwiftyBeaver.framework */; };
 		1ABE07BA1F0C16F100D36361 /* ContactViewModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1ABE07B91F0C16F100D36361 /* ContactViewModel.swift */; };
 		1ABE07BC1F0C22CC00D36361 /* WalkthroughStoryboard.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 1ABE07BB1F0C22CC00D36361 /* WalkthroughStoryboard.storyboard */; };
 		1ABE07D21F0D8FE800D36361 /* Images.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1ABE07D01F0D8FE800D36361 /* Images.swift */; };
@@ -272,6 +273,7 @@
 		04399AE21D1C341A00E99CD9 /* libx264.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; name = libx264.a; path = ../fat/lib/libx264.a; sourceTree = "<group>"; };
 		04399AE31D1C341A00E99CD9 /* libyaml-cpp.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; name = "libyaml-cpp.a"; path = "../fat/lib/libyaml-cpp.a"; sourceTree = "<group>"; };
 		1A1E476C1F0E808500EA9A36 /* Reusable.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Reusable.framework; path = Carthage/Build/iOS/Reusable.framework; sourceTree = "<group>"; };
+		1A1E476E1F0E894600EA9A36 /* SwiftyBeaver.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = SwiftyBeaver.framework; path = Carthage/Build/iOS/SwiftyBeaver.framework; sourceTree = "<group>"; };
 		1ABE07B91F0C16F100D36361 /* ContactViewModel.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ContactViewModel.swift; sourceTree = "<group>"; };
 		1ABE07BB1F0C22CC00D36361 /* WalkthroughStoryboard.storyboard */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.storyboard; path = WalkthroughStoryboard.storyboard; sourceTree = "<group>"; };
 		1ABE07D01F0D8FE800D36361 /* Images.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Images.swift; sourceTree = "<group>"; };
@@ -344,6 +346,7 @@
 			isa = PBXFrameworksBuildPhase;
 			buildActionMask = 2147483647;
 			files = (
+				1A1E476F1F0E894600EA9A36 /* SwiftyBeaver.framework in Frameworks */,
 				1A1E476D1F0E808500EA9A36 /* Reusable.framework in Frameworks */,
 				56559B0E1EE8777600BF20E1 /* RxRealm.framework in Frameworks */,
 				564775831EE5CFC500A0C855 /* Realm.framework in Frameworks */,
@@ -464,6 +467,7 @@
 		02AED8171DD4C4B000F740BA /* Frameworks */ = {
 			isa = PBXGroup;
 			children = (
+				1A1E476E1F0E894600EA9A36 /* SwiftyBeaver.framework */,
 				1A1E476C1F0E808500EA9A36 /* Reusable.framework */,
 				56559B0D1EE8777600BF20E1 /* RxRealm.framework */,
 				564775811EE5CFC500A0C855 /* Realm.framework */,
@@ -987,6 +991,7 @@
 				"$(SRCROOT)/Carthage/Build/iOS/RealmSwift.framework",
 				"$(SRCROOT)/Carthage/Build/iOS/RxRealm.framework",
 				"$(SRCROOT)/Carthage/Build/iOS/Reusable.framework",
+				"$(SRCROOT)/Carthage/Build/iOS/SwiftyBeaver.framework",
 			);
 			name = "⚙️ Copy Frameworks";
 			outputPaths = (
diff --git a/Ring/Ring/Account/AccountConfigModel.swift b/Ring/Ring/Account/AccountConfigModel.swift
index ff9bbb1b9..82450d3c5 100644
--- a/Ring/Ring/Account/AccountConfigModel.swift
+++ b/Ring/Ring/Account/AccountConfigModel.swift
@@ -19,6 +19,7 @@
  */
 
 import RealmSwift
+import SwiftyBeaver
 
 /**
  The different states that an account can have during time.
@@ -69,6 +70,11 @@ class AccountConfigModel: Object {
      */
     fileprivate var configValues = [ConfigKeyModel: String]()
 
+    /**
+     logguer
+    */
+    private let log = SwiftyBeaver.self
+
     /**
      Constructor.
 
@@ -85,7 +91,7 @@ class AccountConfigModel: Object {
                     configValues.updateValue(value, forKey: configKeyModel)
                 } else {
                     //~ The key given in parameter is not known from Ring.
-                    print("Can't find key", key)
+                    log.warning("Can't find key: \(key)")
                 }
             }
         }
diff --git a/Ring/Ring/Account/AccountModelHelper.swift b/Ring/Ring/Account/AccountModelHelper.swift
index 6b9dadc9a..f39a3aa4c 100644
--- a/Ring/Ring/Account/AccountModelHelper.swift
+++ b/Ring/Ring/Account/AccountModelHelper.swift
@@ -18,12 +18,19 @@
  *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA.
  */
 
+import SwiftyBeaver
+
 /**
  A structure exposing the fields and methods for an Account
  */
 struct AccountModelHelper {
     fileprivate var account: AccountModel
 
+    /**
+     logguer
+     */
+    private let log = SwiftyBeaver.self
+
     /**
      Constructor
 
@@ -110,9 +117,9 @@ struct AccountModelHelper {
                     let accountCredentialModel = try AccountCredentialsModel(withRawaData: credential)
                     self.account.credentialDetails.append(accountCredentialModel)
                 } catch CredentialsError.notEnoughData {
-                    print("Not enough data to create a credential")
+                    log.error("Not enough data to create a credential")
                 } catch {
-                    print("Unexpected error")
+                    log.error("Unexpected error")
                 }
             }
         }
diff --git a/Ring/Ring/AppDelegate.swift b/Ring/Ring/AppDelegate.swift
index 7c1705edf..03026bc52 100644
--- a/Ring/Ring/AppDelegate.swift
+++ b/Ring/Ring/AppDelegate.swift
@@ -21,6 +21,7 @@
 
 import UIKit
 import RealmSwift
+import SwiftyBeaver
 
 @UIApplicationMain
 class AppDelegate: UIResponder, UIApplicationDelegate {
@@ -30,8 +31,15 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
     static let accountService = AccountsService(withAccountAdapter: AccountAdapter())
     static let nameService = NameService(withNameRegistrationAdapter: NameRegistrationAdapter())
     static let conversationsService = ConversationsService(withMessageAdapter: MessagesAdapter())
+    private let log = SwiftyBeaver.self
 
     func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
+
+        // initialize log format
+        let console = ConsoleDestination()
+        console.format = "$Dyyyy-MM-dd HH:mm:ss.SSS$d $C$L$c: $M"
+        log.addDestination(console)
+
         SystemAdapter().registerConfigurationHandler()
         self.startDaemon()
         return true
@@ -60,13 +68,13 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
             try AppDelegate.daemonService.startDaemon()
             AppDelegate.accountService.loadAccounts()
         } catch StartDaemonError.initializationFailure {
-            print("Daemon failed to initialize.")
+            log.error("Daemon failed to initialize.")
         } catch StartDaemonError.startFailure {
-            print("Daemon failed to start.")
+            log.error("Daemon failed to start.")
         } catch StartDaemonError.daemonAlreadyRunning {
-            print("Daemon already running.")
+            log.error("Daemon already running.")
         } catch {
-            print("Unknown error in Daemon start.")
+            log.error("Unknown error in Daemon start.")
         }
     }
 
@@ -74,9 +82,9 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
         do {
             try AppDelegate.daemonService.stopDaemon()
         } catch StopDaemonError.daemonNotRunning {
-            print("Daemon failed to stop because it was not already running.")
+            log.error("Daemon failed to stop because it was not already running.")
         } catch {
-            print("Unknown error in Daemon stop.")
+            log.error("Unknown error in Daemon stop.")
         }
     }
 }
diff --git a/Ring/Ring/Contacts/ContactViewModel.swift b/Ring/Ring/Contacts/ContactViewModel.swift
index 9cb498fb9..15ef8b4f3 100644
--- a/Ring/Ring/Contacts/ContactViewModel.swift
+++ b/Ring/Ring/Contacts/ContactViewModel.swift
@@ -20,9 +20,15 @@
 
 import RxSwift
 import RealmSwift
+import SwiftyBeaver
 
 class ContactViewModel {
 
+    /**
+     logguer
+     */
+    private let log = SwiftyBeaver.self
+
     private let nameService = AppDelegate.nameService
     private let disposeBag = DisposeBag()
     private let contact: ContactModel
@@ -60,7 +66,7 @@ class ContactViewModel {
                             self.contact.userName = lookupNameResponse.name
                         }
                     } catch let error {
-                        print ("Realm persistence with error: \(error)")
+                        self.log.error("Realm persistence with error: \(error)")
                     }
 
                     self.userName.value = lookupNameResponse.name
diff --git a/Ring/Ring/Conversations/ConversationViewModel.swift b/Ring/Ring/Conversations/ConversationViewModel.swift
index d11cc973f..2cd71b896 100644
--- a/Ring/Ring/Conversations/ConversationViewModel.swift
+++ b/Ring/Ring/Conversations/ConversationViewModel.swift
@@ -21,9 +21,15 @@
 import UIKit
 import RxSwift
 import RealmSwift
+import SwiftyBeaver
 
 class ConversationViewModel {
 
+    /**
+     logguer
+     */
+    private let log = SwiftyBeaver.self
+
     let conversation: ConversationModel
     private lazy var realm: Realm = {
         guard let realm = try? Realm() else {
@@ -80,7 +86,7 @@ class ConversationViewModel {
                         self.conversation.recipient?.userName = userNameFound
                     }
                 } catch let error {
-                    print ("Realm persistence with error: \(error)")
+                    self.log.error("Realm persistence with error: \(error)")
                 }
 
             }).addDisposableTo(self.disposeBag)
@@ -158,8 +164,8 @@ class ConversationViewModel {
     fileprivate func saveMessage(withContent content: String, byAuthor author: String, toConversationWith account: String) {
         self.conversationsService
             .saveMessage(withContent: content, byAuthor: author, toConversationWith: account, currentAccountId: (accountService.currentAccount?.id)!)
-            .subscribe(onCompleted: {
-                print("Message saved")
+            .subscribe(onCompleted: { [unowned self] in
+                self.log.debug("Message saved")
             })
             .addDisposableTo(disposeBag)
     }
@@ -167,8 +173,8 @@ class ConversationViewModel {
     func setMessagesAsRead() {
         self.conversationsService
             .setMessagesAsRead(forConversation: self.conversation)
-            .subscribe(onCompleted: {
-                print("Message set as read")
+            .subscribe(onCompleted: { [unowned self] in
+                self.log.debug("Message set as read")
             }).addDisposableTo(disposeBag)
     }
 
diff --git a/Ring/Ring/Services/AccountsService.swift b/Ring/Ring/Services/AccountsService.swift
index 0345c04cd..e18d32eb1 100644
--- a/Ring/Ring/Services/AccountsService.swift
+++ b/Ring/Ring/Services/AccountsService.swift
@@ -22,6 +22,7 @@
 import RxCocoa
 import RxSwift
 import RealmSwift
+import SwiftyBeaver
 
 enum AddAccountError: Error {
     case templateNotConform
@@ -30,6 +31,12 @@ enum AddAccountError: Error {
 
 class AccountsService: AccountAdapterDelegate {
     // MARK: Private members
+
+    /**
+     logguer
+     */
+    private let log = SwiftyBeaver.self
+
     /**
      Used to register the service to daemon events, injected by constructor.
      */
@@ -150,7 +157,7 @@ class AccountsService: AccountAdapterDelegate {
                 account.credentialDetails.removeAll()
                 account.credentialDetails.append(objectsIn: credentialDetails)
             } catch {
-                print(error)
+                log.error("\(error)")
             }
         }
     }
@@ -208,7 +215,7 @@ class AccountsService: AccountAdapterDelegate {
      Not supported yet.
      */
     fileprivate func addSipAccount() {
-        print("Not supported yet")
+        log.info("Not supported yet")
     }
 
     /**
@@ -273,10 +280,10 @@ class AccountsService: AccountAdapterDelegate {
                     let credentials = try AccountCredentialsModel(withRawaData: rawCredentials)
                     credentialsList.append(credentials)
                 } catch CredentialsError.notEnoughData {
-                    print("Not enough data to build a credential object.")
+                    log.error("Not enough data to build a credential object.")
                     throw CredentialsError.notEnoughData
                 } catch {
-                    print("Unexpected error.")
+                    log.error("Unexpected error.")
                     throw AccountModelError.unexpectedError
                 }
             }
@@ -348,7 +355,7 @@ class AccountsService: AccountAdapterDelegate {
 
     // MARK: - AccountAdapterDelegate
     func accountsChanged() {
-        print("Accounts changed.")
+        log.debug("Accounts changed.")
         reloadAccounts()
 
         let event = ServiceEvent(withEventType: .accountsChanged)
@@ -356,7 +363,7 @@ class AccountsService: AccountAdapterDelegate {
     }
 
     func registrationStateChanged(with response: RegistrationResponse) {
-        print("RegistrationStateChanged.")
+        log.debug("RegistrationStateChanged.")
         reloadAccounts()
 
         var event = ServiceEvent(withEventType: .registrationStateChanged)
diff --git a/Ring/Ring/Services/ConversationsService.swift b/Ring/Ring/Services/ConversationsService.swift
index 28a9df641..f69d02280 100644
--- a/Ring/Ring/Services/ConversationsService.swift
+++ b/Ring/Ring/Services/ConversationsService.swift
@@ -21,9 +21,15 @@
 import UIKit
 import RxSwift
 import RealmSwift
+import SwiftyBeaver
 
 class ConversationsService: MessagesAdapterDelegate {
 
+    /**
+     logguer
+     */
+    private let log = SwiftyBeaver.self
+
     fileprivate let messageAdapter: MessagesAdapter
     fileprivate let disposeBag = DisposeBag()
     fileprivate let textPlainMIMEType = "text/plain"
@@ -171,8 +177,8 @@ class ConversationsService: MessagesAdapterDelegate {
 
         if let content = message[textPlainMIMEType] {
             self.saveMessage(withContent: content, byAuthor: senderAccount, toConversationWith: senderAccount, currentAccountId: receiverAccountId)
-                .subscribe(onCompleted: {
-                    print("Message saved")
+                .subscribe(onCompleted: { [unowned self] in
+                    self.log.info("Message saved")
                 })
                 .addDisposableTo(disposeBag)
         }
@@ -180,7 +186,6 @@ class ConversationsService: MessagesAdapterDelegate {
 
     func messageStatusChanged(_ status: MessageStatus, for messageId: UInt64,
                               from senderAccountId: String, to receiverAccount: String) {
-
-        print("messageStatusChanged: \(status.rawValue) for: \(messageId) from: \(senderAccountId) to: \(receiverAccount)")
+        log.debug("messageStatusChanged: \(status.rawValue) for: \(messageId) from: \(senderAccountId) to: \(receiverAccount)")
     }
 }
diff --git a/Ring/Ring/Services/DaemonService.swift b/Ring/Ring/Services/DaemonService.swift
index ff91fe4bd..a36bb8eda 100644
--- a/Ring/Ring/Services/DaemonService.swift
+++ b/Ring/Ring/Services/DaemonService.swift
@@ -19,6 +19,7 @@
  */
 
 import Foundation
+import SwiftyBeaver
 
 /**
  Errors that can be thrown when trying to start the daemon:
@@ -53,6 +54,12 @@ enum StopDaemonError: Error {
  */
 class DaemonService {
     // MARK: Private members
+
+    /**
+     logguer
+     */
+    private let log = SwiftyBeaver.self
+
     /// Indicates whether the daemon is started or not.
     fileprivate(set) internal var daemonStarted = false
 
@@ -81,13 +88,13 @@ class DaemonService {
             throw StartDaemonError.daemonAlreadyRunning
         }
 
-        print("Starting daemon...")
+        log.debug("Starting daemon...")
         if self.dRingAdaptor.initDaemon() {
-            print("Daemon initialized.")
+            log.debug("Daemon initialized.")
             if self.dRingAdaptor.startDaemon() {
                 self.startRingServicePolling()
                 self.daemonStarted = true
-                print("Daemon started.")
+                log.debug("Daemon started.")
             } else {
                 throw StartDaemonError.startFailure
             }
@@ -106,11 +113,11 @@ class DaemonService {
             throw StopDaemonError.daemonNotRunning
         }
 
-        print("Stopping daemon...")
+        log.debug("Stopping daemon...")
         self.pollingTimer?.invalidate()
         self.dRingAdaptor.fini()
         self.daemonStarted = false
-        print("Daemon stopped.")
+        log.debug("Daemon stopped.")
     }
 
     // MARK: Private Core
diff --git a/Ring/Ring/Services/NameService.swift b/Ring/Ring/Services/NameService.swift
index 0c8365759..2b8df9e4d 100644
--- a/Ring/Ring/Services/NameService.swift
+++ b/Ring/Ring/Services/NameService.swift
@@ -20,6 +20,7 @@
 
 import UIKit
 import RxSwift
+import SwiftyBeaver
 
 /**
  Represents the status of a username validation request when the user is typing his username
@@ -33,6 +34,10 @@ enum UsernameValidationStatus {
 }
 
 class NameService: NameRegistrationAdapterDelegate {
+    /**
+     logguer
+     */
+    private let log = SwiftyBeaver.self
 
     /**
      Used to make lookup name request to the daemon
@@ -105,7 +110,7 @@ class NameService: NameRegistrationAdapterDelegate {
         } else if response.state == .invalidName {
             usernameValidationStatus.onNext(.invalid)
         } else {
-            print("Lookup name error")
+            log.error("Lookup name error")
         }
 
         usernameLookupStatus.onNext(response)
@@ -113,9 +118,9 @@ class NameService: NameRegistrationAdapterDelegate {
 
     internal func nameRegistrationEnded(with response: NameRegistrationResponse) {
         if response.state == .success {
-            print("Registred name : \(response.name)")
+            log.debug("Registred name : \(response.name)")
         } else {
-            print("Name Registration failed. State = \(response.state.rawValue)")
+            log.debug("Name Registration failed. State = \(response.state.rawValue)")
         }
     }
 }
diff --git a/Ring/Ring/Walkthrough/CreateRingAccountViewController.swift b/Ring/Ring/Walkthrough/CreateRingAccountViewController.swift
index 00bd418ae..47584db7f 100644
--- a/Ring/Ring/Walkthrough/CreateRingAccountViewController.swift
+++ b/Ring/Ring/Walkthrough/CreateRingAccountViewController.swift
@@ -19,10 +19,10 @@
  */
 
 import UIKit
-
 import RxCocoa
 import RxSwift
 import PKHUD
+import SwiftyBeaver
 
 fileprivate enum CreateRingAccountCellType {
     case registerPublicUsername
@@ -34,6 +34,11 @@ fileprivate enum CreateRingAccountCellType {
 
 class CreateRingAccountViewController: UITableViewController {
 
+    /**
+     logguer
+     */
+    private let log = SwiftyBeaver.self
+
     var mAccountViewModel = CreateRingAccountViewModel(withAccountService: AppDelegate.accountService,
                                                        nameService: AppDelegate.nameService)
 
@@ -135,7 +140,7 @@ class CreateRingAccountViewController: UITableViewController {
     }
 
     fileprivate func setCreateAccountAsLoading() {
-        print("Creating account...")
+        log.debug("Creating account...")
         self.mCreateAccountButton.setTitle("Loading...", for: .normal)
         self.mCreateAccountButton.isUserInteractionEnabled = false
 
-- 
GitLab