Skip to content

Commit

Permalink
feat: support full console API
Browse files Browse the repository at this point in the history
  • Loading branch information
aparajita committed Apr 8, 2021
1 parent 34de180 commit ee311a1
Show file tree
Hide file tree
Showing 7 changed files with 261 additions and 159 deletions.
3 changes: 1 addition & 2 deletions android/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="app.willsub.capacitor">
package="com.aparajita.capacitor">
</manifest>

Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package app.willsub.capacitor.logger;
package com.aparajita.capacitor.logger;

import android.webkit.ConsoleMessage;
import com.getcapacitor.Bridge;
Expand All @@ -9,7 +9,7 @@
*/
public class MyBridgeWebChromeClient extends BridgeWebChromeClient {

private WSLogger logger;
private final WSLogger logger;

public MyBridgeWebChromeClient(Bridge bridge, WSLogger logger) {
super(bridge);
Expand All @@ -35,6 +35,9 @@ public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
case "warning":
level = "warn";
break;
case "tip": // debug
level = "debug";
break;
}

logger.print(msg, level);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,7 @@
package app.willsub.capacitor.logger;
package com.aparajita.capacitor.logger;

import android.util.Log;
import com.getcapacitor.CapConfig;
import com.getcapacitor.NativePlugin;
import com.getcapacitor.Plugin;
import com.getcapacitor.PluginCall;
import com.getcapacitor.PluginMethod;
import com.getcapacitor.*;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONObject;
Expand All @@ -14,9 +10,12 @@
public class WSLogger extends Plugin {

public enum LogLevel {
info,
off,
error,
warn,
error
info,
debug,
trace
}

private Map<LogLevel, String> levelPrefixes;
Expand All @@ -37,7 +36,7 @@ public void load() {
private void setHideFlag() {
CapConfig config = bridge.getConfig();
hideLogs = config != null && config.getBoolean("android.hideLogs", config.getBoolean("hideLogs", false));
Object value = getConfigValue("hide");
Object value = getConfigValue("hideLogs");

if (value instanceof Boolean) {
hideLogs = (Boolean) value;
Expand All @@ -49,9 +48,11 @@ private void setHideFlag() {
*/
private void loadCustomPrefixes() {
levelPrefixes = new HashMap<>();
levelPrefixes.put(LogLevel.info, "🟢");
levelPrefixes.put(LogLevel.warn, "🟠");
levelPrefixes.put(LogLevel.error, "🔴");
levelPrefixes.put(LogLevel.warn, "🟠");
levelPrefixes.put(LogLevel.info, "🟢");
levelPrefixes.put(LogLevel.debug, "👉");
levelPrefixes.put(LogLevel.trace, "🔎");

JSONObject prefixes = (JSONObject) getConfigValue("prefixes");

Expand Down Expand Up @@ -127,14 +128,20 @@ public void print(String message, LogLevel level, String module) {
String msg = String.format("%s [%s] %s", symbol, module, message);

switch (level) {
case info:
Log.i(tag, msg);
case error:
Log.e(tag, msg);
break;
case warn:
Log.w(tag, msg);
break;
case error:
Log.e(tag, msg);
case info:
Log.i(tag, msg);
break;
case debug:
Log.d(tag, msg);
break;
case trace:
Log.v(tag, msg);
break;
}
}
Expand Down Expand Up @@ -193,7 +200,7 @@ private void handleCall(PluginCall call, LogLevel level) {
* @param call Plugin call options
*/
@PluginMethod
public void handleConsole(PluginCall call) {
public void handleNativeConsole(PluginCall call) {
final WSLogger logger = this;

class HandleConsoleRunner implements Runnable {
Expand All @@ -204,46 +211,7 @@ public void run() {
}

bridge.executeOnMainThread(new HandleConsoleRunner());
Log.i(tag, "[WSLogger] Now handling the console");
call.success();
}

/**
* Handle calls to console.log().
*
* @param call Plugin call options
*/
@PluginMethod
public void log(PluginCall call) {
handleCall(call);
}

/**
* Handle calls to console.info().
*
* @param call Plugin call options
*/
@PluginMethod
public void info(PluginCall call) {
handleCall(call, LogLevel.info);
}

/**
* Handle calls to console.warn().
*
* @param call Plugin call options
*/
@PluginMethod
public void warn(PluginCall call) {
handleCall(call, LogLevel.warn);
}

/**
* Handle calls to console.error().
*
* @param call Plugin call options
*/
@PluginMethod
public void error(PluginCall call) {
handleCall(call, LogLevel.error);
}
}
6 changes: 2 additions & 4 deletions ios/Plugin/Plugin.m
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
#import <Foundation/Foundation.h>
#import <Capacitor/Capacitor.h>

CAP_PLUGIN(WSLogger, "WSLogger",
CAP_PLUGIN_METHOD(handleConsole, CAPPluginReturnPromise);
CAP_PLUGIN_METHOD(handleNativeConsole, CAPPluginReturnPromise);
CAP_PLUGIN_METHOD(log, CAPPluginReturnPromise);
CAP_PLUGIN_METHOD(info, CAPPluginReturnPromise);
CAP_PLUGIN_METHOD(warn, CAPPluginReturnPromise);
CAP_PLUGIN_METHOD(error, CAPPluginReturnPromise);
)
109 changes: 60 additions & 49 deletions ios/Plugin/Plugin.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,36 @@ import Capacitor

@objc(WSLogger)
public class WSLogger: CAPPlugin {
public enum LogLevel: String {
case info
case warn
public enum LogLevel: Int {
case off = 0
case error
case warn
case info
case debug
case trace
}

let levelNames = [
LogLevel.trace: "trace",
LogLevel.debug: "debug",
LogLevel.info: "info",
LogLevel.warn: "warn",
LogLevel.error: "error",
LogLevel.off: "off"
]

let levelValues = [
"trace": LogLevel.trace,
"debug": LogLevel.debug,
"info": LogLevel.info,
"warn": LogLevel.warn,
"error": LogLevel.error,
"off": LogLevel.off
]

var levelPrefixes = [
LogLevel.trace: "🔎",
LogLevel.debug: "👉",
LogLevel.info: "🟢",
LogLevel.warn: "🟠",
LogLevel.error: "🔴"
Expand All @@ -22,48 +45,49 @@ public class WSLogger: CAPPlugin {
setHideFlag()
}

/**
* Determine if we should hide logs. By default, use the ios.hideLogs or hideLogs capacitor setting.
* If there is a plugins.WSLogger.hide setting, use that. This allows us to hide Capacitor logs but keep user logs.
/*
* Determine if we should hide logs. By default, use global the ios.hideLogs or hideLogs capacitor setting.
* If there is a plugins.WSLogger.hideLogs setting, use that. This allows us to hide Capacitor logs
* but keep user logs.
*/
func setHideFlag() {
private func setHideFlag() {
if let hide = (bridge.config.getValue("ios.hideLogs") as? Bool) ?? (bridge.config.getValue("hideLogs") as? Bool) {
hideConsole = hide
hideLogs = hideConsole
}

if let hide = getConfigValue("hide") as? Bool ?? hideConsole {
if let hide = getConfigValue("hideLogs") as? Bool? ?? hideConsole {
hideLogs = hide
}
}

/**
/*
* Load custom level prefixes from plugins.WSLogger.prefixes.
*/
func loadCustomPrefixes() {
private func loadCustomPrefixes() {
guard let prefixes = getConfigValue("prefixes") as? [String: Any] else {
return
}

for level in prefixes.keys {
if let symbol = prefixes[level] as? String {
if let logLevel = LogLevel(rawValue: level) {
if let symbol = prefixes[level] as? String,
let value = levelValues[level]?.rawValue,
let logLevel = LogLevel(rawValue: value) {
levelPrefixes[logLevel] = symbol
}
}
}
}

/**
/*
* Print a message to the log at the given log level, optionally specifying
* the free-form module scope. If the module is nil, it defaults to "app".
* the free-form module scope.
*/
public func print(_ message: String, level: LogLevel, module: String?) {
public func print(_ message: String, level: LogLevel, module: String = "app") {
let symbol = getLevelPrefix(level)
Swift.print("\(symbol) [\(module ?? "app")] \(message)")
Swift.print("\(symbol) [\(module)] \(message)")
}

/**
/*
* Get the level prefix for the given level. If the level is invalid,
* return the prefix for LogLevel.info.
*/
Expand All @@ -75,32 +99,39 @@ public class WSLogger: CAPPlugin {
return levelPrefixes[LogLevel.info] ?? ""
}

/**
/*
* Extract the "message" call option and print it at the given log level.
* If there is a "module" call option, it is used.
* If there is a "module" call option, it is used, otherwise it defaults to "app".
*/
private func handleCall(_ call: CAPPluginCall, _ level: LogLevel) {
if !self.hideLogs {
let message = call.getString("message") ?? ""
let module = call.getString("module")
self.print(message, level: level, module: module)

if let module = call.getString("module") {
self.print(message, level: level, module: module)
} else {
self.print(message, level: level)
}
}

call.success()
}

/**
* Route calls to console.level() to this plugin by replacing the built in
/*
* Route calls to console.<level>() to this plugin by replacing the built in
* Console plugin with this plugin.
*/
@objc func handleConsole(_ call: CAPPluginCall) {
@objc func handleNativeConsole(_ call: CAPPluginCall) {
// Replace the built in Console plugin with this plugin
if bridge.getPlugin(pluginName: "Console") != nil {
if bridge?.getPlugin(pluginName: "Console") != nil {
bridge.plugins["Console"] = self
Swift.print("[WSLogger] Now handling the console")
}

call.success()
}

/**
/*
* Handle calls to console.log(). A "level" call option may be specified.
*/
@objc func log(_ call: CAPPluginCall) {
Expand All @@ -113,31 +144,11 @@ public class WSLogger: CAPPlugin {

var logLevel = LogLevel.info

if let convertedLevel = LogLevel(rawValue: level) {
if let value = levelValues[level],
let convertedLevel = LogLevel(rawValue: value.rawValue) {
logLevel = convertedLevel
}

self.handleCall(call, logLevel)
}

/**
* Handle calls to console.info().
*/
@objc func info(_ call: CAPPluginCall) {
self.handleCall(call, .info)
}

/**
* Handle calls to console.warn().
*/
@objc func warn(_ call: CAPPluginCall) {
self.handleCall(call, .warn)
}

/**
* Handle calls to console.error().
*/
@objc func error(_ call: CAPPluginCall) {
self.handleCall(call, .error)
}
}
20 changes: 11 additions & 9 deletions src/definitions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,18 @@ declare module '@capacitor/core' {
}
}

export interface WSLoggerOptions {
message: string;
context?: string;
export enum LogLevel {
off,
error,
warn,
info,
debug,
trace,
}

export type WSLoggerFunction = (options: WSLoggerOptions) => Promise<void>;

export interface WSLoggerPlugin {
log: WSLoggerFunction;
info: WSLoggerFunction;
warn: WSLoggerFunction;
error: WSLoggerFunction;
setLevel(level: LogLevel | string): void;
getLevel(): LogLevel;
getLevelName(): string;
handleNativeConsole(): Promise<void>;
}
Loading

0 comments on commit ee311a1

Please sign in to comment.