From e558bcdaed7c13311da57841b08025be030dcaab Mon Sep 17 00:00:00 2001 From: Sergei Dryganets Date: Mon, 20 Mar 2017 02:40:19 -0700 Subject: [PATCH] Production level logging for the plugin. (#137) We print logs through Facebook logger only. This way application could customize if logs need to be saved on disk or have some custom processing. Instead of printing stacktraces we let FLog class to figure out how to handle it. Log levels are changed in the way that important logs wouldn't be filtered out by default log policy in release. --- .../io/liteglue/SQLiteAndroidDatabase.java | 40 ++++----- .../main/java/io/liteglue/SQLitePlugin.java | 68 +++++++------- .../main/java/org/pgsqlite/SQLiteArray.java | 6 +- .../main/java/org/pgsqlite/SQLiteObject.java | 6 +- .../main/java/org/pgsqlite/SQLitePlugin.java | 89 +++++++++---------- src/ios/SQLite.m | 85 +++++++++--------- 6 files changed, 137 insertions(+), 157 deletions(-) diff --git a/src/android-native/src/main/java/io/liteglue/SQLiteAndroidDatabase.java b/src/android-native/src/main/java/io/liteglue/SQLiteAndroidDatabase.java index 41f7965a..1e3e1d9e 100644 --- a/src/android-native/src/main/java/io/liteglue/SQLiteAndroidDatabase.java +++ b/src/android-native/src/main/java/io/liteglue/SQLiteAndroidDatabase.java @@ -17,7 +17,8 @@ import android.database.sqlite.SQLiteStatement; import android.util.Base64; -import android.util.Log; + +import com.facebook.common.logging.FLog; import java.io.File; import java.lang.IllegalArgumentException; @@ -33,8 +34,7 @@ /** * Android Database helper class */ -class SQLiteAndroidDatabase -{ +class SQLiteAndroidDatabase { private static final Pattern FIRST_WORD = Pattern.compile("^\\s*(\\S+)", Pattern.CASE_INSENSITIVE); @@ -145,9 +145,8 @@ void executeSqlBatch(String[] queryarr, JSONArray[] jsonparams, needRawQuery = false; } catch (SQLiteException ex) { // Indicate problem & stop this query: - ex.printStackTrace(); errorMessage = ex.getMessage(); - Log.v("executeSqlBatch", "SQLiteStatement.executeUpdateDelete(): Error=" + errorMessage); + FLog.e(SQLitePlugin.TAG, "SQLiteStatement.executeUpdateDelete() failed", ex); needRawQuery = false; } catch (Exception ex) { // Assuming SDK_INT was lying & method not found: @@ -188,9 +187,8 @@ void executeSqlBatch(String[] queryarr, JSONArray[] jsonparams, } catch (SQLiteException ex) { // report error result with the error message // could be constraint violation or some other error - ex.printStackTrace(); errorMessage = ex.getMessage(); - Log.v("executeSqlBatch", "SQLiteDatabase.executeInsert(): Error=" + errorMessage); + FLog.e(SQLitePlugin.TAG, "SQLiteDatabase.executeInsert() failed", ex); } } @@ -202,9 +200,8 @@ void executeSqlBatch(String[] queryarr, JSONArray[] jsonparams, queryResult = new JSONObject(); queryResult.put("rowsAffected", 0); } catch (SQLiteException ex) { - ex.printStackTrace(); errorMessage = ex.getMessage(); - Log.v("executeSqlBatch", "SQLiteDatabase.beginTransaction(): Error=" + errorMessage); + FLog.e(SQLitePlugin.TAG, "SQLiteDatabase.beginTransaction() failed", ex); } } @@ -217,9 +214,8 @@ void executeSqlBatch(String[] queryarr, JSONArray[] jsonparams, queryResult = new JSONObject(); queryResult.put("rowsAffected", 0); } catch (SQLiteException ex) { - ex.printStackTrace(); errorMessage = ex.getMessage(); - Log.v("executeSqlBatch", "SQLiteDatabase.setTransactionSuccessful/endTransaction(): Error=" + errorMessage); + FLog.e(SQLitePlugin.TAG, "SQLiteDatabase.setTransactionSuccessful/endTransaction() failed", ex); } } @@ -231,9 +227,8 @@ void executeSqlBatch(String[] queryarr, JSONArray[] jsonparams, queryResult = new JSONObject(); queryResult.put("rowsAffected", 0); } catch (SQLiteException ex) { - ex.printStackTrace(); errorMessage = ex.getMessage(); - Log.v("executeSqlBatch", "SQLiteDatabase.endTransaction(): Error=" + errorMessage); + FLog.e(SQLitePlugin.TAG, "SQLiteDatabase.endTransaction() failed", ex); } } @@ -246,9 +241,8 @@ void executeSqlBatch(String[] queryarr, JSONArray[] jsonparams, } } } catch (Exception ex) { - ex.printStackTrace(); errorMessage = ex.getMessage(); - Log.v("executeSqlBatch", "SQLiteAndroidDatabase.executeSql[Batch](): Error=" + errorMessage); + FLog.e(SQLitePlugin.TAG, "SQLiteAndroidDatabase.executeSql[Batch]() failed", ex); } try { @@ -272,9 +266,7 @@ void executeSqlBatch(String[] queryarr, JSONArray[] jsonparams, batchResults.put(r); } } catch (JSONException ex) { - ex.printStackTrace(); - Log.v("executeSqlBatch", "SQLiteAndroidDatabase.executeSql[Batch](): Error=" + ex.getMessage()); - // TODO what to do? + FLog.e(SQLitePlugin.TAG, "SQLiteAndroidDatabase.executeSql[Batch]() failed", ex); } } @@ -332,7 +324,7 @@ private int countRowsAffectedCompat(QueryType queryType, String query, JSONArray return (int)statement.simpleQueryForLong(); } catch (Exception e) { // assume we couldn't count for whatever reason, keep going - Log.e(SQLiteAndroidDatabase.class.getSimpleName(), "uncaught", e); + FLog.e(SQLitePlugin.TAG, "update query failed", e); } } } else { // delete @@ -347,7 +339,7 @@ private int countRowsAffectedCompat(QueryType queryType, String query, JSONArray return (int)statement.simpleQueryForLong(); } catch (Exception e) { // assume we couldn't count for whatever reason, keep going - Log.e(SQLiteAndroidDatabase.class.getSimpleName(), "uncaught", e); + FLog.e(SQLitePlugin.TAG, "delete table query failed", e); } } @@ -395,9 +387,7 @@ private JSONObject executeSqlStatementQuery(SQLiteDatabase mydb, cur = mydb.rawQuery(query, params); } catch (Exception ex) { - ex.printStackTrace(); - String errorMessage = ex.getMessage(); - Log.v("executeSqlBatch", "SQLiteAndroidDatabase.executeSql[Batch](): Error=" + errorMessage); + FLog.e(SQLitePlugin.TAG, "SQLiteAndroidDatabase.executeSql[Batch]() failed", ex); throw ex; } @@ -430,14 +420,14 @@ private JSONObject executeSqlStatementQuery(SQLiteDatabase mydb, rowsArrayResult.put(row); } catch (JSONException e) { - e.printStackTrace(); + FLog.w(SQLitePlugin.TAG, e.getMessage(), e); } } while (cur.moveToNext()); try { rowsResult.put("rows", rowsArrayResult); } catch (JSONException e) { - e.printStackTrace(); + FLog.e(SQLitePlugin.TAG, e.getMessage(), e); } } diff --git a/src/android-native/src/main/java/io/liteglue/SQLitePlugin.java b/src/android-native/src/main/java/io/liteglue/SQLitePlugin.java index 5dcbe1dd..424d8883 100755 --- a/src/android-native/src/main/java/io/liteglue/SQLitePlugin.java +++ b/src/android-native/src/main/java/io/liteglue/SQLitePlugin.java @@ -8,8 +8,8 @@ package io.liteglue; import android.content.Context; -import android.util.Log; +import com.facebook.common.logging.FLog; import com.facebook.react.bridge.Callback; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; @@ -37,6 +37,8 @@ public class SQLitePlugin extends ReactContextBaseJavaModule { + public static final String TAG = SQLitePlugin.class.getSimpleName(); + /** * Multiple database runner map (static). * NOTE: no public static accessor to db (runner) map since it would not work with db threading. @@ -49,7 +51,6 @@ public class SQLitePlugin extends ReactContextBaseJavaModule { */ static SQLiteConnector connector = new SQLiteConnector(); - static String LOG_TAG = SQLitePlugin.class.getSimpleName(); protected ExecutorService threadPool; private Context context; @@ -174,7 +175,7 @@ protected boolean execute(String actionAsString, JSONArray args, CallbackContext action = Action.valueOf(actionAsString); } catch (IllegalArgumentException e) { // shouldn't ever happen - Log.e(LOG_TAG, "unexpected error", e); + FLog.e(TAG, "unexpected error", e); throw(e); } @@ -182,7 +183,7 @@ protected boolean execute(String actionAsString, JSONArray args, CallbackContext return executeAndPossiblyThrow(action, args, cbc); } catch (JSONException e) { // TODO: signal JSON problem to JS - Log.e(LOG_TAG, "unexpected error", e); + FLog.e(TAG, "unexpected error", e); throw(e); } } @@ -268,7 +269,7 @@ private boolean executeAndPossiblyThrow(Action action, JSONArray args, CallbackC try { r.q.put(q); } catch(Exception e) { - Log.e(LOG_TAG, "couldn't add to queue", e); + FLog.e(TAG, "couldn't add to queue", e); cbc.error("couldn't add to queue"); } } else { @@ -295,7 +296,7 @@ public void onDestroy() { // stop the db runner thread: r.q.put(new DBQuery()); } catch(Exception e) { - Log.e(LOG_TAG, "couldn't stop db thread", e); + FLog.e(TAG, "couldn't stop db thread", e); } dbrmap.remove(dbname); } @@ -335,20 +336,20 @@ private SQLiteAndroidDatabase openDatabase(String dbname, String assetFilePath, if (assetFilePath.compareTo("1") == 0) { assetFilePath = "www/" + dbname; in = this.getContext().getAssets().open(assetFilePath); - Log.v("info", "Located pre-populated DB asset in app bundle www subdirectory: " + assetFilePath); + FLog.v(TAG, "Located pre-populated DB asset in app bundle www subdirectory: " + assetFilePath); } else if (assetFilePath.charAt(0) == '~') { assetFilePath = assetFilePath.startsWith("~/") ? assetFilePath.substring(2) : assetFilePath.substring(1); in = this.getContext().getAssets().open(assetFilePath); - Log.v("info", "Located pre-populated DB asset in app bundle subdirectory: " + assetFilePath); + FLog.v(TAG, "Located pre-populated DB asset in app bundle subdirectory: " + assetFilePath); } else { File filesDir = this.getContext().getFilesDir(); assetFilePath = assetFilePath.startsWith("/") ? assetFilePath.substring(1) : assetFilePath; File assetFile = new File(filesDir, assetFilePath); in = new FileInputStream(assetFile); - Log.v("info", "Located pre-populated DB asset in Files subdirectory: " + assetFile.getCanonicalPath()); + FLog.v(TAG, "Located pre-populated DB asset in Files subdirectory: " + assetFile.getCanonicalPath()); if (openFlags == SQLiteOpenFlags.READONLY) { dbfile = assetFile; - Log.v("info", "Detected read-only mode request for external asset."); + FLog.v(TAG, "Detected read-only mode request for external asset."); } } } @@ -358,7 +359,7 @@ private SQLiteAndroidDatabase openDatabase(String dbname, String assetFilePath, dbfile = this.getContext().getDatabasePath(dbname); if (!dbfile.exists() && in != null) { - Log.v("info", "Copying pre-populated db asset to destination"); + FLog.v(TAG, "Copying pre-populated db asset to destination"); this.createFromAssets(dbname, dbfile, in); } @@ -403,7 +404,7 @@ public void closeAllOpenDatabases() { // stop the db runner thread: r.q.put(new DBQuery()); } catch(Exception ex) { - Log.e(LOG_TAG, "couldn't stop db thread for db: " + dbname,ex); + FLog.e(TAG, "couldn't stop db thread for db: " + dbname, ex); } dbrmap.remove(dbname); } @@ -434,9 +435,9 @@ private void createFromAssets(String myDBName, File dbfile, InputStream assetFil while ((len = assetFileInputStream.read(buf)) > 0) out.write(buf, 0, len); - Log.v("info", "Copied pre-populated DB content to: " + newDbFile.getAbsolutePath()); + FLog.v(TAG, "Copied pre-populated DB content to: " + newDbFile.getAbsolutePath()); } catch (IOException ex) { - Log.v("createFromAssets", "No pre-populated DB found, error=" + ex.getMessage()); + FLog.e(TAG, "No pre-populated DB found.", ex); } finally { if (out != null) { try { @@ -461,7 +462,7 @@ private void closeDatabase(String dbname, CallbackContext cbc) { if (cbc != null) { cbc.error("couldn't close database" + e); } - Log.e(LOG_TAG, "couldn't close database", e); + FLog.e(TAG, "couldn't close database", e); } } else { if (cbc != null) { @@ -521,7 +522,7 @@ private void deleteDatabase(String dbname, CallbackContext cbc) { if (cbc != null) { cbc.error("couldn't close database" + e); } - Log.e(LOG_TAG, "couldn't close database", e); + FLog.e(TAG, "couldn't close database", e); } } else { boolean deleteResult = this.deleteDatabaseNow(dbname); @@ -546,7 +547,7 @@ private boolean deleteDatabaseNow(String dbname) { try { return this.getContext().deleteDatabase(dbfile.getAbsolutePath()); } catch (Exception e) { - Log.e(LOG_TAG, "couldn't delete database", e); + FLog.e(TAG, "couldn't delete database", e); return false; } } @@ -585,7 +586,7 @@ void closeDatabaseNow() { if (mydb != null) mydb.dispose(); } catch (Exception e) { - Log.e(LOG_TAG, "couldn't close database, ignoring", e); + FLog.e(TAG, "couldn't close database, ignoring", e); } } @@ -638,9 +639,8 @@ void executeSqlBatch( String[] queryarr, JSONArray[] jsonparams, } } } catch (Exception ex) { - ex.printStackTrace(); errorMessage = ex.getMessage(); - Log.v("executeSqlBatch", "SQLitePlugin.executeSql[Batch](): Error=" + errorMessage); + FLog.e(TAG, "SQLitePlugin.executeSql[Batch]() failed", ex); } try { @@ -664,9 +664,7 @@ void executeSqlBatch( String[] queryarr, JSONArray[] jsonparams, batchResults.put(r); } } catch (JSONException ex) { - ex.printStackTrace(); - Log.v("executeSqlBatch", "SQLitePlugin.executeSql[Batch](): Error=" + ex.getMessage()); - // TODO what to do? + FLog.e(TAG, "SQLitePlugin.executeSql[Batch]() failed", ex); } } @@ -704,11 +702,7 @@ else if (p instanceof Number) hasRows = myStatement.step(); } catch (Exception ex) { - ex.printStackTrace(); - String errorMessage = ex.getMessage(); - Log.v("executeSqlBatch", "SQLitePlugin.executeSql[Batch](): Error=" + errorMessage); - - + FLog.e(TAG, "SQLitePlugin.executeSql[Batch]() failed", ex); throw ex; } @@ -749,14 +743,14 @@ else if (p instanceof Number) rowsArrayResult.put(row); } catch (JSONException e) { - e.printStackTrace(); + FLog.w(SQLitePlugin.TAG, e.getMessage(), e); } } while (myStatement.step()); try { rowsResult.put("rows", rowsArrayResult); } catch (JSONException e) { - e.printStackTrace(); + FLog.e(TAG, e.getMessage(), e); } } } finally { @@ -791,14 +785,14 @@ private class DBRunner implements Runnable { } } catch (JSONException ex){ - Log.v(LOG_TAG,"Error retrieving assetFilename from options:",ex); + FLog.e(TAG,"Error retrieving assetFilename from options.", ex); } this.openFlags = openFlags; this.oldImpl = options.has("androidOldDatabaseImplementation"); - Log.v(LOG_TAG, "Android db implementation: " + (oldImpl ? "OLD" : "sqlite4java (NDK)")); + FLog.v(TAG, "Android db implementation: " + (oldImpl ? "OLD" : "sqlite4java (NDK)")); this.bugWorkaround = this.oldImpl && options.has("androidBugWorkaround"); if (this.bugWorkaround) - Log.v(LOG_TAG, "Android db closing/locking workaround applied"); + FLog.i(TAG, "Android db closing/locking workaround applied"); this.q = new LinkedBlockingQueue<>(); this.openCbc = cbc; @@ -808,7 +802,7 @@ public void run() { try { this.mydb = openDatabase(dbname, this.assetFilename, this.openFlags, this.openCbc, this.oldImpl); } catch (Exception e) { - Log.e(LOG_TAG, "unexpected error, stopping db thread", e); + FLog.e(TAG, "unexpected error, stopping db thread", e); dbrmap.remove(dbname); return; } @@ -828,7 +822,7 @@ public void run() { dbq = q.take(); } } catch (Exception e) { - Log.e(LOG_TAG, "unexpected error", e); + FLog.e(TAG, "unexpected error", e); } if (dbq != null && dbq.close) { @@ -848,12 +842,12 @@ public void run() { dbq.cbc.error("couldn't delete database"); } } catch (Exception e) { - Log.e(LOG_TAG, "couldn't delete database", e); + FLog.e(TAG, "couldn't delete database", e); dbq.cbc.error("couldn't delete database: " + e); } } } catch (Exception e) { - Log.e(LOG_TAG, "couldn't close database", e); + FLog.e(TAG, "couldn't close database", e); if (dbq.cbc != null) { dbq.cbc.error("couldn't close database: " + e); } diff --git a/src/android/src/main/java/org/pgsqlite/SQLiteArray.java b/src/android/src/main/java/org/pgsqlite/SQLiteArray.java index 468a3057..88b34f81 100644 --- a/src/android/src/main/java/org/pgsqlite/SQLiteArray.java +++ b/src/android/src/main/java/org/pgsqlite/SQLiteArray.java @@ -1,5 +1,7 @@ package org.pgsqlite; +import com.facebook.common.logging.FLog; + import org.json.JSONArray; import java.lang.reflect.Field; @@ -22,9 +24,9 @@ public SQLiteArray(int size){ valuesField.setAccessible(true); valuesField.set(this, new ArrayList<>(size)); } catch (NoSuchFieldException e) { - e.printStackTrace(); + FLog.e(SQLitePlugin.TAG, e.getMessage(), e); } catch (IllegalAccessException e) { - e.printStackTrace(); + FLog.e(SQLitePlugin.TAG, e.getMessage(), e); } } diff --git a/src/android/src/main/java/org/pgsqlite/SQLiteObject.java b/src/android/src/main/java/org/pgsqlite/SQLiteObject.java index 5d85a041..84566dfa 100644 --- a/src/android/src/main/java/org/pgsqlite/SQLiteObject.java +++ b/src/android/src/main/java/org/pgsqlite/SQLiteObject.java @@ -1,5 +1,7 @@ package org.pgsqlite; +import com.facebook.common.logging.FLog; + import org.json.JSONObject; import java.lang.reflect.Field; @@ -22,9 +24,9 @@ public SQLiteObject(int size){ valuesField.setAccessible(true); valuesField.set(this, new LinkedHashMap(size)); } catch (NoSuchFieldException e) { - e.printStackTrace(); + FLog.e(SQLitePlugin.TAG, e.getMessage(), e); } catch (IllegalAccessException e) { - e.printStackTrace(); + FLog.e(SQLitePlugin.TAG, e.getMessage(), e); } } } diff --git a/src/android/src/main/java/org/pgsqlite/SQLitePlugin.java b/src/android/src/main/java/org/pgsqlite/SQLitePlugin.java index 3ab4c6f4..0a84afee 100755 --- a/src/android/src/main/java/org/pgsqlite/SQLitePlugin.java +++ b/src/android/src/main/java/org/pgsqlite/SQLitePlugin.java @@ -17,7 +17,6 @@ import android.content.Context; import android.os.Bundle; import android.util.Base64; -import android.util.Log; import java.io.Closeable; import java.io.File; @@ -33,6 +32,7 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; +import com.facebook.common.logging.FLog; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; @@ -51,9 +51,9 @@ public class SQLitePlugin extends ReactContextBaseJavaModule { - private static final String PLUGIN_NAME = "SQLite"; + public static final String TAG = SQLitePlugin.class.getSimpleName(); - private static final String LOG_TAG = SQLitePlugin.class.getSimpleName(); + private static final String PLUGIN_NAME = "SQLite"; private static final Pattern FIRST_WORD = Pattern.compile("^\\s*(\\S+)", Pattern.CASE_INSENSITIVE); @@ -214,7 +214,7 @@ protected boolean execute(String actionAsString, JSONArray args, CallbackContext action = Action.valueOf(actionAsString); } catch (IllegalArgumentException e) { // shouldn't ever happen - Log.e(SQLitePlugin.class.getSimpleName(), "unexpected error", e); + FLog.e(TAG, "unexpected error", e); throw(e); } @@ -222,7 +222,7 @@ protected boolean execute(String actionAsString, JSONArray args, CallbackContext return executeAndPossiblyThrow(action, args, cbc); } catch (JSONException e) { // TODO: signal JSON problem to JS - Log.e(SQLitePlugin.class.getSimpleName(), "unexpected error", e); + FLog.e(TAG, "unexpected error", e); throw(e); } } @@ -307,7 +307,7 @@ private boolean executeAndPossiblyThrow(Action action, JSONArray args, CallbackC try { r.q.put(q); } catch(Exception e) { - Log.e(SQLitePlugin.class.getSimpleName(), "couldn't add to queue", e); + FLog.e(TAG, "couldn't add to queue", e); cbc.error("couldn't add to queue"); } } else { @@ -333,7 +333,7 @@ public void closeAllOpenDatabases() { // stop the db runner thread: r.q.put(new DBQuery()); } catch(Exception ex) { - Log.e(SQLitePlugin.class.getSimpleName(), "couldn't stop db thread for db: " + dbname,ex); + FLog.e(TAG, "couldn't stop db thread for db: " + dbname,ex); } dbrmap.remove(dbname); } @@ -393,20 +393,20 @@ private SQLiteDatabase openDatabase(String dbname, String assetFilePath, int ope if (assetFilePath.compareTo("1") == 0) { assetFilePath = "www/" + dbname; in = this.getContext().getAssets().open(assetFilePath); - Log.v("info", "Located pre-populated DB asset in app bundle www subdirectory: " + assetFilePath); + FLog.v(TAG, "Located pre-populated DB asset in app bundle www subdirectory: " + assetFilePath); } else if (assetFilePath.charAt(0) == '~') { assetFilePath = assetFilePath.startsWith("~/") ? assetFilePath.substring(2) : assetFilePath.substring(1); in = this.getContext().getAssets().open(assetFilePath); - Log.v("info", "Located pre-populated DB asset in app bundle subdirectory: " + assetFilePath); + FLog.v(TAG, "Located pre-populated DB asset in app bundle subdirectory: " + assetFilePath); } else { File filesDir = this.getContext().getFilesDir(); assetFilePath = assetFilePath.startsWith("/") ? assetFilePath.substring(1) : assetFilePath; File assetFile = new File(filesDir, assetFilePath); in = new FileInputStream(assetFile); - Log.v("info", "Located pre-populated DB asset in Files subdirectory: " + assetFile.getCanonicalPath()); + FLog.v(TAG, "Located pre-populated DB asset in Files subdirectory: " + assetFile.getCanonicalPath()); if (openFlags == SQLiteDatabase.OPEN_READONLY) { dbfile = assetFile; - Log.v("info", "Detected read-only mode request for external asset."); + FLog.v(TAG, "Detected read-only mode request for external asset."); } } } @@ -416,7 +416,7 @@ private SQLiteDatabase openDatabase(String dbname, String assetFilePath, int ope dbfile = this.getContext().getDatabasePath(dbname); if (!dbfile.exists() && in != null) { - Log.v("info", "Copying pre-populated db asset to destination"); + FLog.v(TAG, "Copying pre-populated db asset to destination"); this.createFromAssets(dbname, dbfile, in); } @@ -425,7 +425,7 @@ private SQLiteDatabase openDatabase(String dbname, String assetFilePath, int ope } } - Log.v("info", "Opening sqlite db: " + dbfile.getAbsolutePath()); + FLog.v(TAG, "Opening sqlite db: " + dbfile.getAbsolutePath()); SQLiteDatabase mydb = SQLiteDatabase.openDatabase(dbfile.getAbsolutePath(), null, openFlags); @@ -454,7 +454,7 @@ private void createFromAssets(String dbName, File dbfile, InputStream assetFileI OutputStream out = null; try { - Log.v("info", "Copying pre-populated DB content"); + FLog.v(TAG, "Copying pre-populated DB content"); String dbPath = dbfile.getAbsolutePath(); dbPath = dbPath.substring(0, dbPath.lastIndexOf("/") + 1); @@ -472,9 +472,9 @@ private void createFromAssets(String dbName, File dbfile, InputStream assetFileI while ((len = assetFileInputStream.read(buf)) > 0) out.write(buf, 0, len); - Log.v("info", "Copied pre-populated DB content to: " + newDbFile.getAbsolutePath()); + FLog.v(TAG, "Copied pre-populated DB content to: " + newDbFile.getAbsolutePath()); } catch (IOException e) { - Log.v("createFromAssets", "No pre-populated DB found, error=" + e.getMessage()); + FLog.e(TAG, "No pre-populated DB found.", e); } finally { closeQuietly(out); } @@ -495,7 +495,7 @@ private void closeDatabase(String dbName, CallbackContext cbc) { if (cbc != null) { cbc.error("couldn't close database" + e); } - Log.e(SQLitePlugin.class.getSimpleName(), "couldn't close database", e); + FLog.e(TAG, "couldn't close database", e); } } else { if (cbc != null) { @@ -558,7 +558,7 @@ private void deleteDatabase(String dbname, CallbackContext cbc) { if (cbc != null) { cbc.error("couldn't close database" + e); } - Log.e(SQLitePlugin.class.getSimpleName(), "couldn't close database", e); + FLog.e(TAG, "couldn't close database", e); } } else { boolean deleteResult = this.deleteDatabaseNow(dbname); @@ -585,7 +585,7 @@ private boolean deleteDatabaseNow(String dbname) { try { return SQLiteDatabase.deleteDatabase(dbfile); } catch (Exception e) { - Log.e(SQLitePlugin.class.getSimpleName(), "couldn't delete because old SDK_INT", e); + FLog.e(TAG, "couldn't delete because old SDK_INT", e); return deleteDatabasePreHoneycomb(dbfile); } } else { @@ -598,7 +598,7 @@ private boolean deleteDatabasePreHoneycomb(File dbfile) { try { return this.getContext().deleteDatabase(dbfile.getAbsolutePath()); } catch (Exception e) { - Log.e(SQLitePlugin.class.getSimpleName(), "couldn't delete database", e); + FLog.e(TAG, "couldn't delete database", e); return false; } } @@ -672,9 +672,8 @@ private void executeSqlBatch(String dbname, String[] queryarr, JSONArray[] jsonp needRawQuery = false; } catch (SQLiteException ex) { // Indicate problem & stop this query: - ex.printStackTrace(); errorMessage = ex.getMessage(); - Log.v("executeSqlBatch", "SQLiteStatement.executeUpdateDelete(): Error=" + errorMessage); + FLog.e(TAG, "SQLiteStatement.executeUpdateDelete() failed", ex); needRawQuery = false; } catch (Exception ex) { // Assuming SDK_INT was lying & method not found: @@ -717,9 +716,8 @@ private void executeSqlBatch(String dbname, String[] queryarr, JSONArray[] jsonp } catch (SQLiteException ex) { // report error result with the error message // could be constraint violation or some other error - ex.printStackTrace(); errorMessage = ex.getMessage(); - Log.v("executeSqlBatch", "SQLiteDatabase.executeInsert(): Error=" + errorMessage); + FLog.e(TAG, "SQLiteDatabase.executeInsert() failed", ex); } finally { closeQuietly(myStatement); } @@ -733,9 +731,8 @@ private void executeSqlBatch(String dbname, String[] queryarr, JSONArray[] jsonp queryResult = new JSONObject(); queryResult.put("rowsAffected", 0); } catch (SQLiteException ex) { - ex.printStackTrace(); errorMessage = ex.getMessage(); - Log.v("executeSqlBatch", "SQLiteDatabase.beginTransaction(): Error=" + errorMessage); + FLog.e(TAG, "SQLiteDatabase.beginTransaction() failed", ex); } } @@ -748,9 +745,8 @@ private void executeSqlBatch(String dbname, String[] queryarr, JSONArray[] jsonp queryResult = new JSONObject(); queryResult.put("rowsAffected", 0); } catch (SQLiteException ex) { - ex.printStackTrace(); errorMessage = ex.getMessage(); - Log.v("executeSqlBatch", "SQLiteDatabase.setTransactionSuccessful/endTransaction(): Error=" + errorMessage); + FLog.e(TAG, "SQLiteDatabase.setTransactionSuccessful/endTransaction() failed", ex); } } @@ -762,9 +758,8 @@ private void executeSqlBatch(String dbname, String[] queryarr, JSONArray[] jsonp queryResult = new JSONObject(); queryResult.put("rowsAffected", 0); } catch (SQLiteException ex) { - ex.printStackTrace(); errorMessage = ex.getMessage(); - Log.v("executeSqlBatch", "SQLiteDatabase.endTransaction(): Error=" + errorMessage); + FLog.e(TAG, "SQLiteDatabase.endTransaction() failed", ex); } } @@ -777,9 +772,8 @@ private void executeSqlBatch(String dbname, String[] queryarr, JSONArray[] jsonp } } } catch (Exception ex) { - ex.printStackTrace(); errorMessage = ex.getMessage(); - Log.v("executeSqlBatch", "SQLitePlugin.executeSql[Batch](): Error=" + errorMessage); + FLog.e(TAG, "SQLitePlugin.executeSql[Batch](): failed", ex); } try { @@ -803,8 +797,7 @@ private void executeSqlBatch(String dbname, String[] queryarr, JSONArray[] jsonp batchResults.put(r); } } catch (JSONException ex) { - ex.printStackTrace(); - Log.v("executeSqlBatch", "SQLitePlugin.executeSql[Batch](): Error=" + ex.getMessage()); + FLog.e(TAG, "SQLitePlugin.executeSql[Batch]() failed", ex); } } @@ -863,7 +856,7 @@ private int countRowsAffectedCompat(QueryType queryType, String query, JSONArray return (int)statement.simpleQueryForLong(); } catch (Exception e) { // assume we couldn't count for whatever reason, keep going - Log.e(SQLitePlugin.class.getSimpleName(), "uncaught", e); + FLog.e(TAG, "uncaught", e); } finally { closeQuietly(statement); } @@ -881,7 +874,7 @@ private int countRowsAffectedCompat(QueryType queryType, String query, JSONArray return (int)statement.simpleQueryForLong(); } catch (Exception e) { // assume we couldn't count for whatever reason, keep going - Log.e(LOG_TAG, "uncaught", e); + FLog.e(TAG, "uncaught", e); } finally { closeQuietly(statement); } @@ -949,9 +942,7 @@ private JSONObject executeSqlStatementQuery(SQLiteDatabase mydb, cur = mydb.rawQuery(query, params); } catch (Exception ex) { - ex.printStackTrace(); - String errorMessage = ex.getMessage(); - Log.v("executeSqlBatch", "SQLitePlugin.executeSql[Batch](): Error=" + errorMessage); + FLog.e(TAG, "SQLitePlugin.executeSql[Batch]() failed", ex); throw ex; } @@ -984,14 +975,14 @@ private JSONObject executeSqlStatementQuery(SQLiteDatabase mydb, rowsArrayResult.put(row); } catch (JSONException e) { - Log.e(LOG_TAG, e.getMessage(), e); + FLog.e(TAG, e.getMessage(), e); } } while (cur.moveToNext()); try { rowsResult.put("rows", rowsArrayResult); } catch (JSONException e) { - Log.e(LOG_TAG, e.getMessage(), e); + FLog.e(TAG, e.getMessage(), e); } } } finally { @@ -1075,12 +1066,12 @@ private class DBRunner implements Runnable { openFlags = readOnly ? SQLiteDatabase.OPEN_READONLY : openFlags; } } catch (Exception ex){ - Log.v(SQLitePlugin.class.getSimpleName(),"Error retrieving assetFilename this.mode from options:",ex); + FLog.e(TAG,"Error retrieving assetFilename this.mode from options:",ex); } this.openFlags = openFlags; this.androidLockWorkaround = options.has("androidLockWorkaround"); if (this.androidLockWorkaround) - Log.v(SQLitePlugin.class.getSimpleName(), "Android db closing/locking workaround applied"); + FLog.i(TAG, "Android db closing/locking workaround applied"); this.q = new LinkedBlockingQueue(); this.openCbc = cbc; @@ -1090,7 +1081,7 @@ public void run() { try { this.mydb = openDatabase(dbname, this.assetFilename, this.openFlags, this.openCbc); } catch (Exception e) { - Log.e(SQLitePlugin.class.getSimpleName(), "unexpected error, stopping db thread", e); + FLog.e(TAG, "unexpected error, stopping db thread", e); dbrmap.remove(dbname); return; } @@ -1105,16 +1096,16 @@ public void run() { // XXX workaround for Android locking/closing issue: if (androidLockWorkaround && dbq.queries.length == 1 && dbq.queries[0].equals("COMMIT")) { - // Log.v(SQLitePlugin.class.getSimpleName(), "close and reopen db"); + // FLog.v(TAG, "close and reopen db"); closeDatabaseNow(dbname); this.mydb = openDatabase(dbname, "", this.openFlags, null); - // Log.v(SQLitePlugin.class.getSimpleName(), "close and reopen db finished"); + // FLog.v(TAG, "close and reopen db finished"); } dbq = q.take(); } } catch (Exception e) { - Log.e(SQLitePlugin.class.getSimpleName(), "unexpected error", e); + FLog.e(TAG, "unexpected error", e); } if (dbq != null && dbq.close) { @@ -1134,12 +1125,12 @@ public void run() { dbq.cbc.error("couldn't delete database"); } } catch (Exception e) { - Log.e(SQLitePlugin.class.getSimpleName(), "couldn't delete database", e); + FLog.e(TAG, "couldn't delete database", e); dbq.cbc.error("couldn't delete database: " + e); } } } catch (Exception e) { - Log.e(SQLitePlugin.class.getSimpleName(), "couldn't close database", e); + FLog.e(TAG, "couldn't close database", e); if (dbq.cbc != null) { dbq.cbc.error("couldn't close database: " + e); } diff --git a/src/ios/SQLite.m b/src/ios/SQLite.m index 418da284..450f1c07 100644 --- a/src/ios/SQLite.m +++ b/src/ios/SQLite.m @@ -75,7 +75,7 @@ @implementation SQLite - (id) init { - NSLog(@"Initializing SQLitePlugin"); + RCTLog(@"Initializing SQLitePlugin"); self = [super init]; if (self) { openDBs = [NSMutableDictionary dictionaryWithCapacity:0]; @@ -86,18 +86,18 @@ - (id) init #endif NSString *docs = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex: 0]; - NSLog(@"Detected docs path: %@", docs); + RCTLog(@"Detected docs path: %@", docs); [appDBPaths setObject: docs forKey:@"docs"]; NSString *libs = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex: 0]; - NSLog(@"Detected Library path: %@", libs); + RCTLog(@"Detected Library path: %@", libs); [appDBPaths setObject: libs forKey:@"libs"]; NSString *nosync = [libs stringByAppendingPathComponent:@"LocalDatabase"]; NSError *err; if ([[NSFileManager defaultManager] fileExistsAtPath: nosync]) { - NSLog(@"no cloud sync at path: %@", nosync); + RCTLog(@"no cloud sync at path: %@", nosync); [appDBPaths setObject: nosync forKey:@"nosync"]; } else @@ -107,15 +107,15 @@ - (id) init NSURL *nosyncURL = [ NSURL fileURLWithPath: nosync]; if (![nosyncURL setResourceValue: [NSNumber numberWithBool: YES] forKey: NSURLIsExcludedFromBackupKey error: &err]) { - NSLog(@"IGNORED: error setting nobackup flag in LocalDatabase directory: %@", err); + RCTLog(@"IGNORED: error setting nobackup flag in LocalDatabase directory: %@", err); } - NSLog(@"no cloud sync at path: %@", nosync); + RCTLog(@"no cloud sync at path: %@", nosync); [appDBPaths setObject: nosync forKey:@"nosync"]; } else { // fallback: - NSLog(@"WARNING: error adding LocalDatabase directory: %@", err); + RCTLog(@"WARNING: error adding LocalDatabase directory: %@", err); [appDBPaths setObject: libs forKey:@"nosync"]; } } @@ -141,7 +141,7 @@ -(id) getDBPath:(NSString *)dbFile at:(NSString *)atkey { RCT_EXPORT_METHOD(echoStringValue: (NSDictionary *) options success:(RCTResponseSenderBlock)success error:(RCTResponseSenderBlock)error) { NSString * string_value = options[@"value"]; - NSLog(@"echo string value: %@", string_value); + RCTLog(@"echo string value: %@", string_value); SQLiteResult* pluginResult = [SQLiteResult resultWithStatus:SQLiteStatus_OK messageAsString:string_value]; [pluginResult.status intValue] == SQLiteStatus_OK ? success(@[pluginResult.message]) : error(@[pluginResult.message]); @@ -156,12 +156,12 @@ -(id) getDBPath:(NSString *)dbFile at:(NSString *)atkey { @synchronized (self) { NSString *dbfilename = options[@"name"]; if (dbfilename == NULL) { - NSLog(@"No db name specified for open"); + RCTLog(@"No db name specified for open"); pluginResult = [SQLiteResult resultWithStatus:SQLiteStatus_OK messageAsString:@"You must specify database name"]; } else { NSDictionary *dbInfo = openDBs[dbfilename]; if (dbInfo != NULL && dbInfo[@"dbPointer"] != NULL) { - NSLog(@"Reusing existing database connection for db name %@", dbfilename); + RCTLog(@"Reusing existing database connection for db name %@", dbfilename); pluginResult = [SQLiteResult resultWithStatus:SQLiteStatus_OK messageAsString:@"Database opened"]; } else { NSString *assetFilePath = options[@"assetFilename"]; @@ -171,20 +171,20 @@ -(id) getDBPath:(NSString *)dbFile at:(NSString *)atkey { NSString *targetBundleDirPath = [[NSBundle mainBundle] resourcePath]; targetBundleDirPath = [targetBundleDirPath stringByAppendingPathComponent: @"www"]; assetFilePath = [targetBundleDirPath stringByAppendingPathComponent: dbfilename]; - NSLog(@"Built path to pre-populated DB asset from app bundle www subdirectory: %@",assetFilePath); + RCTLog(@"Built path to pre-populated DB asset from app bundle www subdirectory: %@",assetFilePath); } else if ([assetFilePath characterAtIndex:0 == '~']) { assetFilePath = [assetFilePath substringFromIndex:1]; NSString *targetBundleDirPath = [[NSBundle mainBundle] resourcePath]; assetFilePath = [targetBundleDirPath stringByAppendingPathComponent: assetFilePath]; - NSLog(@"Built path to pre-populated DB asset from app bundle subdirectory: %@",assetFilePath); + RCTLog(@"Built path to pre-populated DB asset from app bundle subdirectory: %@",assetFilePath); } else { NSURL * documentsDirUrl = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject]; assetFilePath = [documentsDirUrl.path stringByAppendingPathComponent:assetFilePath]; - NSLog(@"Built path to pre-populated DB asset from app sandbox documents directory: %@",assetFilePath); + RCTLog(@"Built path to pre-populated DB asset from app sandbox documents directory: %@",assetFilePath); } } @catch(NSException *ex){ - NSLog(@"Error building path for pre-populated DB asset %@",ex.reason); + RCTLog(@"Error building path for pre-populated DB asset %@",ex.reason); } } @@ -194,18 +194,18 @@ -(id) getDBPath:(NSString *)dbFile at:(NSString *)atkey { } else { NSString *dblocation = options[@"dblocation"]; if (dblocation == NULL) dblocation = @"nosync"; - NSLog(@"target database location: %@", dblocation); + RCTLog(@"target database location: %@", dblocation); dbname = [self getDBPath:dbfilename at:dblocation]; /* Option to create from resource (pre-populated) if db does not exist: */ if (![[NSFileManager defaultManager] fileExistsAtPath:dbname] && assetFilePath != NULL) { - NSLog(@"Copying pre-populated asset to the destination directory"); + RCTLog(@"Copying pre-populated asset to the destination directory"); [self createFromResource:assetFilePath withDbname:dbname]; } } - NSLog(@"Opening db in mode %@, full path: %@", (sqlOpenFlags == SQLITE_OPEN_READONLY) ? @"READ ONLY" : @"READ_WRITE",dbname); + RCTLog(@"Opening db in mode %@, full path: %@", (sqlOpenFlags == SQLITE_OPEN_READONLY) ? @"READ ONLY" : @"READ_WRITE",dbname); const char *name = [dbname UTF8String]; sqlite3 *db; @@ -229,7 +229,7 @@ -(id) getDBPath:(NSString *)dbFile at:(NSString *)atkey { pluginResult = [SQLiteResult resultWithStatus:SQLiteStatus_OK messageAsString:@"Database opened"]; } else { pluginResult = [SQLiteResult resultWithStatus:SQLiteStatus_ERROR messageAsString:@"Unable to open DB with key"]; - NSLog(@"Unable to open db with key"); + RCTLog(@"Unable to open db with key"); sqlite3_close (db); [openDBs removeObjectForKey:dbfilename]; } @@ -239,27 +239,28 @@ -(id) getDBPath:(NSString *)dbFile at:(NSString *)atkey { } if (sqlite3_threadsafe()) { - NSLog(@"Good news: SQLite is thread safe!"); + RCTLog(@"Good news: SQLite is thread safe!"); } else { - NSLog(@"Warning: SQLite is not thread safe."); + RCTLog(@"Warning: SQLite is not thread safe."); } [pluginResult.status intValue] == SQLiteStatus_OK ? success(@[pluginResult.message]) : error(@[pluginResult.message]); - NSLog(@"open cb finished ok"); + RCTLog(@"open cb finished ok"); } -(void)createFromResource:(NSString *)prepopulatedDb withDbname:(NSString *)dbname { - NSLog(@"Looking for prepopulated DB at: %@", prepopulatedDb); + RCTLog(@"Looking for prepopulated DB at: %@", prepopulatedDb); if ([[NSFileManager defaultManager] fileExistsAtPath:prepopulatedDb]) { - NSLog(@"Found prepopulated DB: %@", prepopulatedDb); + RCTLog(@"Found prepopulated DB: %@", prepopulatedDb); NSError *error; BOOL success = [[NSFileManager defaultManager] copyItemAtPath:prepopulatedDb toPath:dbname error:&error]; - if(success) - NSLog(@"Copied prepopulated DB content to: %@", dbname); - else - NSLog(@"Unable to copy DB file: %@", [error localizedDescription]); + if(success) { + RCTLog(@"Copied prepopulated DB content to: %@", dbname); + } else { + RCTLog(@"Unable to copy DB file: %@", [error localizedDescription]); + } } } @@ -271,36 +272,36 @@ -(void)createFromResource:(NSString *)prepopulatedDb withDbname:(NSString *)dbna NSString *dbFileName = options[@"path"]; if (dbFileName == NULL) { // Should not happen: - NSLog(@"No db name specified for close"); + RCTLog(@"No db name specified for close"); pluginResult = [SQLiteResult resultWithStatus:SQLiteStatus_ERROR messageAsString:@"You must specify database path"]; } else { NSDictionary *dbInfo = openDBs[dbFileName]; if (dbInfo == NULL || dbInfo[@"dbPointer"] == NULL) { - NSLog(@"close: db name was not found in open databases: %@", dbFileName); + RCTLog(@"close: db name was not found in open databases: %@", dbFileName); pluginResult = [SQLiteResult resultWithStatus:SQLiteStatus_ERROR messageAsString:@"Specified db was not open"]; } else { sqlite3 *db = [((NSValue *) dbInfo[@"dbPointer"]) pointerValue]; NSString *dbPath = dbInfo[@"dbPath"]; if ([[NSFileManager defaultManager] fileExistsAtPath:dbPath]) { - NSLog(@"close: database still exists at path %@, proceeding to close it.",dbPath); + RCTLog(@"close: database still exists at path %@, proceeding to close it.",dbPath); } if (db == NULL) { // Should not happen: - NSLog(@"close: db name was not open: %@", dbFileName); + RCTLog(@"close: db name was not open: %@", dbFileName); pluginResult = [SQLiteResult resultWithStatus:SQLiteStatus_ERROR messageAsString:@"Specified db was not open"]; } else { - NSLog(@"close: closing db: %@", dbFileName); + RCTLog(@"close: closing db: %@", dbFileName); sqlite3_close (db); [openDBs removeObjectForKey:dbFileName]; pluginResult = [SQLiteResult resultWithStatus:SQLiteStatus_OK messageAsString:@"DB closed"]; } if ([[NSFileManager defaultManager]fileExistsAtPath:dbPath]) { - NSLog(@"database file still exists after close"); + RCTLog(@"database file still exists after close"); } else { - NSLog(@"database file doesn't exists after close"); + RCTLog(@"database file doesn't exists after close"); } } } @@ -320,20 +321,20 @@ -(void)createFromResource:(NSString *)prepopulatedDb withDbname:(NSString *)dbna if (dbName == NULL || dbAlias == NULL) { // Should not happen: - NSLog(@"No dbName or dbAlias specified for attach"); + RCTLog(@"No dbName or dbAlias specified for attach"); pluginResult = [SQLiteResult resultWithStatus:SQLiteStatus_ERROR messageAsString:@"You must specify dbName and dbAlias"]; } else { - NSLog(@"Will attach %@ with alias %@", dbName, dbAlias); + RCTLog(@"Will attach %@ with alias %@", dbName, dbAlias); @synchronized (self) { NSDictionary *dbInfo = openDBs[dbFileName]; NSDictionary *dbInfoToAttach = openDBs[dbName]; if (dbInfo == NULL || dbInfo[@"dbPointer"] == NULL) { - NSLog(@"attach: db name was not found in open databases: %@", dbFileName); + RCTLog(@"attach: db name was not found in open databases: %@", dbFileName); pluginResult = [SQLiteResult resultWithStatus:SQLiteStatus_ERROR messageAsString:@"Specified db was not open"]; } else if (dbInfoToAttach == NULL || dbInfoToAttach[@"dbPointer"] == NULL) { - NSLog(@"attach: db name was not found in open databases: %@", dbName); + RCTLog(@"attach: db name was not found in open databases: %@", dbName); pluginResult = [SQLiteResult resultWithStatus:SQLiteStatus_ERROR messageAsString:@"Specified db for ALIAS was not open"]; } else { sqlite3 *db = [((NSValue *) dbInfo[@"dbPointer"]) pointerValue]; @@ -362,19 +363,19 @@ -(void)createFromResource:(NSString *)prepopulatedDb withDbname:(NSString *)dbna @synchronized (self) { if (dbfilename == NULL) { // Should not happen: - NSLog(@"No db name specified for delete"); + RCTLog(@"No db name specified for delete"); pluginResult = [SQLiteResult resultWithStatus:SQLiteStatus_ERROR messageAsString:@"You must specify database path"]; } else { if (dblocation == NULL) dblocation = @"nosync"; NSString *dbPath = [self getDBPath:dbfilename at:dblocation]; if ([[NSFileManager defaultManager] fileExistsAtPath:dbPath]) { - NSLog(@"delete full db path: %@", dbPath); + RCTLog(@"delete full db path: %@", dbPath); [[NSFileManager defaultManager]removeItemAtPath:dbPath error:nil]; [openDBs removeObjectForKey:dbfilename]; pluginResult = [SQLiteResult resultWithStatus:SQLiteStatus_OK messageAsString:@"DB deleted"]; } else { - NSLog(@"delete: db was not found: %@", dbPath); + RCTLog(@"delete: db was not found: %@", dbPath); pluginResult = [SQLiteResult resultWithStatus:SQLiteStatus_ERROR messageAsString:@"The database does not exist on that path"]; } } @@ -496,7 +497,7 @@ -(SQLiteResult *) executeSqlWithDict: (NSMutableDictionary*)options andArgs: (NS } } - // NSLog(@"inside executeSqlWithDict"); + // RCTLog(@"inside executeSqlWithDict"); while (keepGoing) { result = sqlite3_step (statement); switch (result) {