Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(ios): add configuration option to disable logs #1697

Merged
merged 1 commit into from
Jun 21, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion ios/Capacitor/Capacitor/CAPAssetHandler.swift
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ class CAPAssetHandler: NSObject, WKURLSchemeHandler {
}

func webView(_ webView: WKWebView, stop urlSchemeTask: WKURLSchemeTask) {
print("scheme stop")
CAPLog.print("scheme stop")
}

func mimeTypeForExtension(pathExtension: String) -> String {
Expand Down
56 changes: 28 additions & 28 deletions ios/Capacitor/Capacitor/CAPBridge.swift
Original file line number Diff line number Diff line change
Expand Up @@ -137,20 +137,20 @@ enum BridgeError: Error {
* particularly dreadful happens.
*/
static func fatalError(_ error: Error, _ originalError: Error) {
print("⚡️ ❌ Capacitor: FATAL ERROR")
print("⚡️ ❌ Error was: ", originalError.localizedDescription)
CAPLog.print("⚡️ ❌ Capacitor: FATAL ERROR")
CAPLog.print("⚡️ ❌ Error was: ", originalError.localizedDescription)
switch error {
case BridgeError.errorExportingCoreJS:
print("⚡️ ❌ Unable to export required Bridge JavaScript. Bridge will not function.")
print("⚡️ ❌ You should run \"npx capacitor copy\" to ensure the Bridge JS is added to your project.")
CAPLog.print("⚡️ ❌ Unable to export required Bridge JavaScript. Bridge will not function.")
CAPLog.print("⚡️ ❌ You should run \"npx capacitor copy\" to ensure the Bridge JS is added to your project.")
if let wke = originalError as? WKError {
print("⚡️ ❌ ", wke.userInfo)
CAPLog.print("⚡️ ❌ ", wke.userInfo)
}
default:
print("⚡️ ❌ Unknown error")
CAPLog.print("⚡️ ❌ Unknown error")
}

print("⚡️ ❌ Please verify your installation or file an issue")
CAPLog.print("⚡️ ❌ Please verify your installation or file an issue")
}

/**
Expand All @@ -160,12 +160,12 @@ enum BridgeError: Error {
let appStatePlugin = getOrLoadPlugin(pluginName: "App") as? CAPAppPlugin

NotificationCenter.default.addObserver(forName: UIApplication.didBecomeActiveNotification, object: nil, queue: OperationQueue.main) { (notification) in
print("APP ACTIVE")
CAPLog.print("APP ACTIVE")
self.isActive = true
appStatePlugin?.fireChange(isActive: self.isActive)
}
NotificationCenter.default.addObserver(forName: UIApplication.didEnterBackgroundNotification, object: nil, queue: OperationQueue.main) { (notification) in
print("APP INACTIVE")
CAPLog.print("APP INACTIVE")
self.isActive = false
appStatePlugin?.fireChange(isActive: self.isActive)
}
Expand Down Expand Up @@ -275,7 +275,7 @@ enum BridgeError: Error {

public func loadPlugin(pluginName: String) -> CAPPlugin? {
guard let pluginType = knownPlugins[pluginName] else {
print("⚡️ Unable to load plugin \(pluginName). No such module found.")
CAPLog.print("⚡️ Unable to load plugin \(pluginName). No such module found.")
return nil
}

Expand Down Expand Up @@ -347,7 +347,7 @@ enum BridgeError: Error {

public func modulePrint(_ plugin: CAPPlugin, _ items: Any...) {
let output = items.map { "\($0)" }.joined(separator: " ")
Swift.print("⚡️ ", plugin.pluginId, "-", output)
CAPLog.print("⚡️ ", plugin.pluginId, "-", output)
}

public func alert(_ title: String, _ message: String, _ buttonTitle: String = "OK") {
Expand All @@ -366,7 +366,7 @@ enum BridgeError: Error {
*/
public func handleJSCall(call: JSCall) {
guard let plugin = self.getPlugin(pluginName: call.pluginId) ?? self.loadPlugin(pluginName: call.pluginId) else {
print("⚡️ Error loading plugin \(call.pluginId) for call. Check that the pluginId is correct")
CAPLog.print("⚡️ Error loading plugin \(call.pluginId) for call. Check that the pluginId is correct")
return
}
guard let pluginType = knownPlugins[plugin.getId()] else {
Expand All @@ -379,20 +379,20 @@ enum BridgeError: Error {
} else {
let bridgeType = pluginType as! CAPBridgedPlugin.Type
guard let method = bridgeType.getMethod(call.method) else {
print("⚡️ Error calling method \(call.method) on plugin \(call.pluginId): No method found.")
print("⚡️ Ensure plugin method exists and uses @objc in its declaration, and has been defined")
CAPLog.print("⚡️ Error calling method \(call.method) on plugin \(call.pluginId): No method found.")
CAPLog.print("⚡️ Ensure plugin method exists and uses @objc in its declaration, and has been defined")
return
}

//print("\n⚡️ Calling method \"\(call.method)\" on plugin \"\(plugin.getId()!)\"")
//CAPLog.print("\n⚡️ Calling method \"\(call.method)\" on plugin \"\(plugin.getId()!)\"")

selector = method.selector
}

if !plugin.responds(to: selector) {
print("⚡️ Error: Plugin \(plugin.getId()!) does not respond to method call \"\(call.method)\" using selector \"\(selector!)\".")
print("⚡️ Ensure plugin method exists, uses @objc in its declaration, and arguments match selector without callbacks in CAP_PLUGIN_METHOD.")
print("⚡️ Learn more: \(docLink(DocLinks.CAPPluginMethodSelector.rawValue))")
CAPLog.print("⚡️ Error: Plugin \(plugin.getId()!) does not respond to method call \"\(call.method)\" using selector \"\(selector!)\".")
CAPLog.print("⚡️ Ensure plugin method exists, uses @objc in its declaration, and arguments match selector without callbacks in CAP_PLUGIN_METHOD.")
CAPLog.print("⚡️ Learn more: \(docLink(DocLinks.CAPPluginMethodSelector.rawValue))")
return
}

Expand All @@ -418,7 +418,7 @@ enum BridgeError: Error {
}

//let timeElapsed = CFAbsoluteTimeGetCurrent() - startTime
//print("Native call took", timeElapsed)
//CAPLog.print("Native call took", timeElapsed)
}
}

Expand All @@ -432,8 +432,8 @@ enum BridgeError: Error {
if let plugin = self.cordovaPluginManager?.getCommandInstance(call.pluginId.lowercased()) {
let selector = NSSelectorFromString("\(call.method):")
if !plugin.responds(to: selector) {
print("Error: Plugin \(plugin.className!) does not respond to method call \(selector).")
print("Ensure plugin method exists and uses @objc in its declaration")
CAPLog.print("Error: Plugin \(plugin.className!) does not respond to method call \(selector).")
CAPLog.print("Ensure plugin method exists and uses @objc in its declaration")
return
}

Expand All @@ -443,7 +443,7 @@ enum BridgeError: Error {
plugin.perform(selector, with: pluginCall)
}
} else {
print("Error: Cordova Plugin mapping not found")
CAPLog.print("Error: Cordova Plugin mapping not found")
return
}
}
Expand All @@ -454,7 +454,7 @@ enum BridgeError: Error {
public func toJs(result: JSResult, save: Bool) {
do {
let resultJson = try result.toJson()
print("⚡️ TO JS", resultJson.prefix(256))
CAPLog.print("⚡️ TO JS", resultJson.prefix(256))

DispatchQueue.main.async {
self.getWebView()?.evaluateJavaScript("""
Expand All @@ -468,7 +468,7 @@ enum BridgeError: Error {
})
""") { (result, error) in
if error != nil && result != nil {
print(result!)
CAPLog.print(result!)
}
}
}
Expand All @@ -489,7 +489,7 @@ enum BridgeError: Error {
DispatchQueue.main.async {
self.getWebView()?.evaluateJavaScript("window.Capacitor.fromNative({ callbackId: '\(error.call.callbackId)', pluginId: '\(error.call.pluginId)', methodName: '\(error.call.method)', success: false, error: \(error.toJson())})") { (result, error) in
if error != nil && result != nil {
print(result!)
CAPLog.print(result!)
}
}
}
Expand All @@ -509,7 +509,7 @@ enum BridgeError: Error {
DispatchQueue.main.async {
self.getWebView()?.evaluateJavaScript(wrappedJs, completionHandler: { (result, error) in
if error != nil {
print("⚡️ JS Eval error", error!.localizedDescription)
CAPLog.print("⚡️ JS Eval error", error!.localizedDescription)
}
})
}
Expand All @@ -522,7 +522,7 @@ enum BridgeError: Error {
DispatchQueue.main.async {
self.getWebView()?.evaluateJavaScript(js, completionHandler: { (result, error) in
if error != nil {
print("⚡️ JS Eval error", error!.localizedDescription)
CAPLog.print("⚡️ JS Eval error", error!.localizedDescription)
}
})
}
Expand Down Expand Up @@ -556,7 +556,7 @@ enum BridgeError: Error {
DispatchQueue.main.async {
self.getWebView()?.evaluateJavaScript("window.Capacitor.logJs('\(message)', '\(level)')") { (result, error) in
if error != nil && result != nil {
print(result!)
CAPLog.print(result!)
}
}
}
Expand Down
14 changes: 7 additions & 7 deletions ios/Capacitor/Capacitor/CAPBridgeDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ extension CAPBridgeDelegate {
let options = dict["options"] as? [String:Any] ?? [:]

if pluginId != "Console" {
print("⚡️ To Native -> ", pluginId, method, callbackId)
CAPLog.print("⚡️ To Native -> ", pluginId, method, callbackId)
}

bridge.handleJSCall(call: JSCall(options: options, pluginId: pluginId, method: method, callbackId: callbackId))
Expand All @@ -35,7 +35,7 @@ extension CAPBridgeDelegate {
let args = dict["actionArgs"] as? Array ?? []
let options = ["options":args]

print("To Native Cordova -> ", pluginId, method, callbackId, options)
CAPLog.print("To Native Cordova -> ", pluginId, method, callbackId, options)

bridge.handleCordovaJSCall(call: JSCall(options: options, pluginId: pluginId, method: method, callbackId: callbackId))
}
Expand All @@ -53,10 +53,10 @@ extension CAPBridgeDelegate {
filename = String(url[index...])
}

print("\n⚡️ ------ STARTUP JS ERROR ------\n")
print("⚡️ \(message)")
print("⚡️ URL: \(url)")
print("⚡️ \(filename):\(line):\(col)")
print("\n⚡️ See above for help with debugging blank-screen issues")
CAPLog.print("\n⚡️ ------ STARTUP JS ERROR ------\n")
CAPLog.print("⚡️ \(message)")
CAPLog.print("⚡️ URL: \(url)")
CAPLog.print("⚡️ \(filename):\(line):\(col)")
CAPLog.print("\n⚡️ See above for help with debugging blank-screen issues")
}
}
30 changes: 15 additions & 15 deletions ios/Capacitor/Capacitor/CAPBridgeViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -105,10 +105,10 @@ public class CAPBridgeViewController: UIViewController, CAPBridgeDelegate, WKScr
func printLoadError() {
let fullStartPath = URL(fileURLWithPath: "public").appendingPathComponent(startDir)

print("⚡️ ERROR: Unable to load \(fullStartPath.relativePath)/index.html")
print("⚡️ This file is the root of your web app and must exist before")
print("⚡️ Capacitor can run. Ensure you've run capacitor copy at least")
print("⚡️ or, if embedding, that this directory exists as a resource directory.")
CAPLog.print("⚡️ ERROR: Unable to load \(fullStartPath.relativePath)/index.html")
CAPLog.print("⚡️ This file is the root of your web app and must exist before")
CAPLog.print("⚡️ Capacitor can run. Ensure you've run capacitor copy at least")
CAPLog.print("⚡️ or, if embedding, that this directory exists as a resource directory.")
}

func fatalLoadError() -> Never {
Expand All @@ -126,7 +126,7 @@ public class CAPBridgeViewController: UIViewController, CAPBridgeDelegate, WKScr
allowNavigationConfig = bridge!.config.getValue("server.allowNavigation") as? Array<String>


print("⚡️ Loading app at \(hostname!)...")
CAPLog.print("⚡️ Loading app at \(hostname!)...")
let request = URLRequest(url: URL(string: hostname!)!)
_ = webView?.load(request)
}
Expand Down Expand Up @@ -212,17 +212,17 @@ public class CAPBridgeViewController: UIViewController, CAPBridgeDelegate, WKScr
}

public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
print("⚡️ WebView loaded")
CAPLog.print("⚡️ WebView loaded")
}

public func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
print("⚡️ WebView failed to load")
print("⚡️ Error: " + error.localizedDescription)
CAPLog.print("⚡️ WebView failed to load")
CAPLog.print("⚡️ Error: " + error.localizedDescription)
}

public func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
print("⚡️ WebView failed provisional navigation")
print("⚡️ Error: " + error.localizedDescription)
CAPLog.print("⚡️ WebView failed provisional navigation")
CAPLog.print("⚡️ Error: " + error.localizedDescription)
}

public func webViewWebContentProcessDidTerminate(_ webView: WKWebView) {
Expand Down Expand Up @@ -293,11 +293,11 @@ public class CAPBridgeViewController: UIViewController, CAPBridgeDelegate, WKScr
filename = String(url[index...])
}

print("\n⚡️ ------ STARTUP JS ERROR ------\n")
print("⚡️ \(message)")
print("⚡️ URL: \(url)")
print("⚡️ \(filename):\(line):\(col)")
print("\n⚡️ See above for help with debugging blank-screen issues")
CAPLog.print("\n⚡️ ------ STARTUP JS ERROR ------\n")
CAPLog.print("⚡️ \(message)")
CAPLog.print("⚡️ URL: \(url)")
CAPLog.print("⚡️ \(filename):\(line):\(col)")
CAPLog.print("\n⚡️ See above for help with debugging blank-screen issues")
}

func matchHost(host: String, pattern: String) -> Bool {
Expand Down
10 changes: 5 additions & 5 deletions ios/Capacitor/Capacitor/CAPConfig.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
super.init()
if let contents = configText {
guard let configData = contents.data(using: .utf8) else {
print("Unable to process config JSON string as UTF8")
CAPLog.print("Unable to process config JSON string as UTF8")
return
}

Expand All @@ -20,14 +20,14 @@

private func loadGlobalConfig() {
guard let configUrl = Bundle.main.url(forResource: "capacitor.config", withExtension: "json") else {
print("Unable to find capacitor.config.json, make sure it exists and run npx cap copy")
CAPLog.print("Unable to find capacitor.config.json, make sure it exists and run npx cap copy")
return
}
do {
let contents = try Data(contentsOf: configUrl)
parseAndSetConfig(contents)
} catch {
print("Unable to parse capacitor.config.json. Make sure it's valid JSON")
CAPLog.print("Unable to parse capacitor.config.json. Make sure it's valid JSON")
}
}

Expand All @@ -36,8 +36,8 @@
let json = try JSONSerialization.jsonObject(with: data) as? [String: Any]
self.config = json
} catch {
print("Unable to parse config JSON")
print(error.localizedDescription)
CAPLog.print("Unable to parse config JSON")
CAPLog.print(error.localizedDescription)
}
}

Expand Down
19 changes: 19 additions & 0 deletions ios/Capacitor/Capacitor/CAPLog.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
public class CAPLog {

public static let config = CAPConfig()

public static func print(_ items: Any..., separator: String = " ", terminator: String = "") {
if !self.hideLogs() {
for item in items {
Swift.print(item, separator, terminator)
}
}
}

public static func hideLogs() -> Bool {
if let hideLogs = config.getValue("ios.hideLogs") as? Bool {
return hideLogs
}
return false
}
}
6 changes: 3 additions & 3 deletions ios/Capacitor/Capacitor/JS.swift
Original file line number Diff line number Diff line change
Expand Up @@ -60,14 +60,14 @@ public class JSResult {
return String(data: theJSONData,
encoding: .utf8)!
} else {
print("[Capacitor Plugin Error] - \(call.pluginId) - \(call.method) - Unable to serialize plugin response as JSON." +
CAPLog.print("[Capacitor Plugin Error] - \(call.pluginId) - \(call.method) - Unable to serialize plugin response as JSON." +
"Ensure that all data passed to success callback from module method is JSON serializable!")
throw JSProcessingError.jsonSerializeError(call: call)
}
} catch let error as JSProcessingError {
throw error
} catch {
print("Unable to serialize plugin response as JSON: \(error.localizedDescription)")
CAPLog.print("Unable to serialize plugin response as JSON: \(error.localizedDescription)")
}

return "{}"
Expand Down Expand Up @@ -109,7 +109,7 @@ public class JSResultError {
if let theJSONData = try? JSONSerialization.data(withJSONObject: error, options: []) {
jsonResponse = String(data: theJSONData,
encoding: .utf8)!
print("ERROR MESSAGE: ", jsonResponse.prefix(512))
CAPLog.print("ERROR MESSAGE: ", jsonResponse.prefix(512))
}

return jsonResponse
Expand Down
Loading