Custom Logger for React native app with WatermelonDB

September 19, 2023

Custom Logger for React native app with WatermelonDB

Custom Logger for React native app with WatermelonDB

Certainly! Below is a step-by-step guide and documentation for creating a Logger.js file, a database.js file, and implementing the functionality to store and retrieve logs using WatermelonDB in a React Native application.

Logger.js

Logger.js is a module responsible for logging messages and storing them in memory for later retrieval.

// Logger.js

class Logger {
  static logs = [];

  static logWithTimestamp(message, isError = false) {
    const timestamp = new Date().toLocaleString();
    const logMessage = `${timestamp}: ${message}`;

    if (isError) {
      // Log the error message
      console.error(logMessage);
    } else {
      // Log regular messages
      console.log(logMessage);
    }

    this.logs.push(logMessage);
  }

  static getLogs() {
    return this.logs;
  }

  static clearLogs() {
    this.logs = [];
  }
}

export default Logger;

In Logger.js, we define a Logger class with methods to log messages with timestamps, retrieve logs, and clear logs. The logs are stored in memory in the logs array.

database.js

database.js is a module responsible for configuring and interacting with WatermelonDB.

// database.js

import { Database } from '@nozbe/watermelondb';
import SQLiteAdapter from '@nozbe/watermelondb/adapters/sqlite';
import { mySchema } from './schema'; // Import your schema

// Create the adapter
const adapter = new SQLiteAdapter({
  dbName: 'myAppDatabase',
  schema: mySchema,
});

// Create the database instance
const database = new Database({
  adapter,
  modelClasses: [],
  actionsEnabled: true,
});

export default database;

In database.js, we set up WatermelonDB by configuring the adapter and creating the database instance. You should replace mySchema with your actual schema.

Storing and Retrieving Logs

Now, you can use these modules to store and retrieve logs as shown below:

// Import Logger.js and database.js
import Logger from './Logger';
import database from './database';

// Function to store logs in the database
const storeLogs = async () => {
  try {
    const logs = Logger.getLogs();
    const logsJSON = JSON.stringify(logs);

    await database.write(async () => {
      const logEntry = await database.create('logs', (log) => {
        log.logData = logsJSON;
        log.timestamp = new Date().toLocaleString();
      });

      console.info('Stored logs:', logEntry);
    });

    Logger.clearLogs();
    return true;
  } catch (error) {
    throw error;
  }
};

// Function to retrieve logs from the database
const retrieveLogs = async () => {
  try {
    const logs = await database.query((q) =>
      q.collection('logs').fetch()
    );

    return logs;
  } catch (error) {
    throw error;
  }
};

In this code, we have two functions: storeLogs to store logs in the database and retrieveLogs to retrieve logs from the database. These functions use the Logger and database modules we defined earlier.

You can now call these functions as needed in your React Native application to store and retrieve logs using WatermelonDB.


Written by Manoj Bhardwaj who lives and works in Dharamshala Himachal Pradesh (India). My stackoverflow