Noodlog: A Golang JSON Parametrized, Highly Configurable Log Library

Noodlog

Summary

Noodlog is a Golang JSON parametrized and highly configurable logging library.

It allows you to:

  • print go structs as JSON messages;
  • print JSON strings and raw strings messages as pure JSONs;
  • obscure some sensitive params from your logging;
  • chain objects or strings in your logs;
  • apply string templates to your logs;
  • choose to trace the caller file and function and fine tune the settings;
  • apply pretty printing or not;
  • apply colors to your logging;
  • customize colors per log level.

Import

go get github.com/gyozatech/noodlog

Usage

Let's assume you have Go 1.16+ istalled on your computer. Execute the following:

$ mkdir example && cd example
$ go mod init example
$ go get github.com/gyozatech/noodlog
$ touch main.go

Open main.go and paste the following code:

package main

import (
    "github.com/gyozatech/noodlog"
)

var log *noodlog.Logger

func init() {
   log = noodlog.NewLogger().SetConfigs(
      noodlog.Configs{
         LogLevel: noodlog.LevelTrace,
         JSONPrettyPrint: noodlog.Enable,
         TraceCaller: noodlog.Enable,
         Colors: noodlog.Enable,
         CustomColors: &noodlog.CustomColors{ Trace: noodlog.Cyan },
         ObscureSensitiveData: noodlog.Enable,
         SensitiveParams: []string{"password"},
      },
    )
}

func main() {
    // simple string message (with custom color)
    log.Trace("Hello world!")
    
    // chaining elements
    log.Info("You've reached", 3, "login attemps")
    
    // using string formatting
    log.Warn("You have %d attempts left", 2)
    
    // logging a struct with a JSON
    log.Error(struct{Code int; Error string}{500, "Generic Error"})
    
    // logging a raw JSON string with a JSON (with obscuring "password")
    log.Info(`{"username": "gyozatech", "password": "Gy0zApAssw0rd"}`)
    
    // logging a JSON string with a JSON (with obscuring "password")
    log.Info("{\"username\": \"nooduser\", \"password\": \"N0oDPasSw0rD\"}")
}

Running this example with:

$ go run main.go

You'll get the following output:

alt text

Settings

Noodlog allows you to customize the logs through various settings. You can use various facility functions or the SetConfigs function which wraps all the configs together.


LogLevel

To set the logging level, after importing the library with:

import (
    "github.com/gyozatech/noodlog"
)

var log *noodlog.Logger

func init() {
   log = noodlog.NewLogger()
}

you can use the facility method:

log.LogLevel("warn")

or the SetConfigs function:

log.SetConfigs(
    noodlog.Configs{
        LogLevel: noodlog.LevelWarn,
    },
)

log.LevelWarn is a pre-built pointer to the string "warn".

The default log level is info.


JSON Pretty Printing

After importing the library with:

import (
    "github.com/gyozatech/noodlog"
)

var log *noodlog.Logger

func init() {
   log = noodlog.NewLogger()
}

To enable pretty printing of the JSON logs you can use:

log.EnableJSONPrettyPrint()

or

log.SetConfigs(
    noodlog.Configs{
       JSONPrettyPrint: noodlog.Enable,
    },
)

noodlog.Enable is a pre-built pointer to the bool true.

to disable pretty printing you can use:

log.DisableJSONPrettyPrint()

or

log.SetConfigs(
    noodlog.Configs{
       JSONPrettyPrint: noodlog.Disable,
    },
)

noodlog.Disable is a pre-built pointer to the bool false.

The default value is false.


Colors

After importing the library with:

import (
    "github.com/gyozatech/noodlog"
)

var log *noodlog.Logger

func init() {
   log = noodlog.NewLogger()
}

to enable colors in JSON logs you can use:

log.EnableColors()

or

log.SetConfigs(
    noodlog.Configs{
        Colors: noodlog.Enable,
    },
)

noodlog.Enable is a pre-built pointer to the bool true.

To disable colors you can use:

log.DisableColors()

or

log.SetConfigs(
    noodlog.Configs{
        Colors: noodlog.Disable,
    },
)

noodlog.Disable is a pre-built pointer to the bool false.

The default value is false.

Color

The basic way to use a custom color is declaring using a pointer of a string representing the color. 
log.Cyan, log.Green, log.Default, log.Yellow, log.Purple, log.Red, log.Blue are pre-build pointers to the strings "cyan", "green", "default", "yellow", "purple", "red", "blue".

For instance, you can customize trace color by:

log.SetTraceColor(noodlog.Cyan)

A more detailed explanation of each log level is available later into this section.

Composition of a color

Color can be composed with text color and background color. For each level it can be composed using a string or a true color notation.

Trivial usage is creating a new color like:

log.NewColor(noodlog.Red)

It results a red text on default background

Adding a background color can be done through:

log.NewColor(noodlog.Red).Background(noodlog.Cyan)

In this scenario it prints red text on cyan background

A third option is to edit just background color using default text color:

log.Background(noodlog.Cyan)

A list of pre-built pointer of a string is [here](#Composition of a color).

Library provides also more customization through the usage of true color notation (RGB value). Before the usage of this notation, please consider if your terminal supports truecolor. For instance if you execute (printf required):

printf '\033[38;2;255;0;0mHello World\033[0m'

a red text "Hello World" should be displayed on the screen

In this way a wider set of color is available for logging, besides of the previous way it can be created a color as:

log.NewColorRGB(255,0,0).BackgroundRGB(0,0,255)

Where a red text (255 for red, 0 the others) is showed on blue background (255 for blue, 0 for others).

As in the previous scenario, NewColorRGB and BackgroundRGB hasn't to be executed combined.

Color can be used to set color of Trace log, by typing:

log.SetTraceColor(noodlog.NewColorRGB(255,0,0).BackgroundRGB(0,0,255))

You can customize the single colors (for log level) by using:

log.SetTraceColor(noodlog.Cyan)
log.SetDebugColor(noodlog.NewColorRGB(255,255,0))
log.SetInfoColor(noodlog.NewColor(noodlog.Red).Background(noodlog.Cyan))
log.SetWarnColor(noodlog.NewColor(noodlog.Green).BackgroundRGB(0,255,255))
log.SetErrorColor(noodlog.NewColorRGB(128,255,0).Background(noodlog.Purple))

or

log.SetConfigs(
    noodlog.Configs{
        Colors: noodlog.Enable,
        CustomColors: &noodlog.CustomColors{ 
            Trace: noodlog.Cyan, 
            Debug: noodlog.NewColorRGB(255,255,0),
            Info:  noodlog.NewColor(noodlog.Red).Background(noodlog.Cyan),
            Warn:  noodlog.NewColor(noodlog.Green).BackgroundRGB(0,255,255),
            Error: noodlog.NewColorRGB(128,255,0).Background(noodlog.Purple),    
        },
    },
)

Here we highlight all the different combination available to customize colors.

When enabled, the default colors are:

  • trace: "default"
  • info: "default"
  • debug: "green"
  • warn: "yellow"
  • error: "red"

Trace the caller

Noodles allows you to print the file and the function which are calling the log functions.

After importing the library with:

import (
    "github.com/gyozatech/noodlog"
)

var log *noodlog.Logger

func init() {
   log = noodlog.NewLogger()
}

to enable the trace caller you can use:

log.EnableTraceCaller()

or

log.SetConfigs(
    noodlog.Configs{
        TraceCaller: noodlog.Enable,
    },
)

noodlog.Enable is a pre-built pointer to the bool true.

To disable it:

log.DisableTraceCaller()

or

log.SetConfigs(
    noodlog.Configs{
        TraceCaller: noodlog.Disable,
    },
)

noodlog.Disable is a pre-built pointer to the bool false.

The default value is false.

Important: if you want to import noodlog only in one package of your project (in order to configure it once) and wraps the logging functions you can use the EnableSinglePointTracing to trace file and function the real caller and not of your logging package.

For example:

main.go

package main

import (
   log "example/logging"
)

func main() {
   // main.main real caller we want to track 
   log.Info("Hello folks!")
}

logging/logger.go

package logging

import (
    "github.com/gyozatech/noodlog"
)

var l *noodlog.Logger

func init() {
    l = noodlog.NewLogger()
    // configure logger once
    l.SetConfig(
        noodlog.Configs{
         TraceCaller: noodlog.Enable,
         SinglePointTracing: noodlog.Enable,
      },
    )
}

// wrapper function
func Info(message ...interface{}) {
    // if we wouldn't enable SinglePointTracing
    // logger.Info would have been considered the caller to be tracked
    l.Info(message...)
}

Sensitive params

Noodlog gives you the possibility to enable the obscuration of sensitive params when recognized in the JSON structures (not in the simple strings that you compose).

After importing the library with:

import (
    "github.com/gyozatech/noodlog"
)

var log *noodlog.Logger

func init() {
   log = noodlog.NewLogger()
}

You can enable the sensitive params obscuration with the facility methods:

log.EnableObscureSensitiveData([]string{"param1", "param2", "param3"})

or with the SetConfig function:

log.SetConfigs(
    noodlog.Configs{
        ObscureSensitiveData: noodlog.Enable,
        SensitiveParams: []string{"param1", "param2", "param3"},
    },
)

Where noodlog.Enable is a pre-built pointer to the bool true.

To disable the sensitive params obscuration you can set:

log.DisableObscureSensitiveData()

or

log.SetConfigs(
    noodlog.Configs{
        ObscureSensitiveData: noodlog.Disable,
    },
)

Where noodlog.Disable is a pre-built pointer to the bool false.

The default value for the obscuration is false.


Contribute to the project

If you want to contribute to the project follow the following guidelines. Any form of contribution is encouraged!

Author: Gyozatech
Source Code: https://github.com/gyozatech/noodlog 
License: Apache-2.0 License

#json #go #golang #logger #logging 

What is GEEK

Buddha Community

Noodlog: A Golang JSON Parametrized, Highly Configurable Log Library

Noodlog: A Golang JSON Parametrized, Highly Configurable Log Library

Noodlog

Summary

Noodlog is a Golang JSON parametrized and highly configurable logging library.

It allows you to:

  • print go structs as JSON messages;
  • print JSON strings and raw strings messages as pure JSONs;
  • obscure some sensitive params from your logging;
  • chain objects or strings in your logs;
  • apply string templates to your logs;
  • choose to trace the caller file and function and fine tune the settings;
  • apply pretty printing or not;
  • apply colors to your logging;
  • customize colors per log level.

Import

go get github.com/gyozatech/noodlog

Usage

Let's assume you have Go 1.16+ istalled on your computer. Execute the following:

$ mkdir example && cd example
$ go mod init example
$ go get github.com/gyozatech/noodlog
$ touch main.go

Open main.go and paste the following code:

package main

import (
    "github.com/gyozatech/noodlog"
)

var log *noodlog.Logger

func init() {
   log = noodlog.NewLogger().SetConfigs(
      noodlog.Configs{
         LogLevel: noodlog.LevelTrace,
         JSONPrettyPrint: noodlog.Enable,
         TraceCaller: noodlog.Enable,
         Colors: noodlog.Enable,
         CustomColors: &noodlog.CustomColors{ Trace: noodlog.Cyan },
         ObscureSensitiveData: noodlog.Enable,
         SensitiveParams: []string{"password"},
      },
    )
}

func main() {
    // simple string message (with custom color)
    log.Trace("Hello world!")
    
    // chaining elements
    log.Info("You've reached", 3, "login attemps")
    
    // using string formatting
    log.Warn("You have %d attempts left", 2)
    
    // logging a struct with a JSON
    log.Error(struct{Code int; Error string}{500, "Generic Error"})
    
    // logging a raw JSON string with a JSON (with obscuring "password")
    log.Info(`{"username": "gyozatech", "password": "Gy0zApAssw0rd"}`)
    
    // logging a JSON string with a JSON (with obscuring "password")
    log.Info("{\"username\": \"nooduser\", \"password\": \"N0oDPasSw0rD\"}")
}

Running this example with:

$ go run main.go

You'll get the following output:

alt text

Settings

Noodlog allows you to customize the logs through various settings. You can use various facility functions or the SetConfigs function which wraps all the configs together.


LogLevel

To set the logging level, after importing the library with:

import (
    "github.com/gyozatech/noodlog"
)

var log *noodlog.Logger

func init() {
   log = noodlog.NewLogger()
}

you can use the facility method:

log.LogLevel("warn")

or the SetConfigs function:

log.SetConfigs(
    noodlog.Configs{
        LogLevel: noodlog.LevelWarn,
    },
)

log.LevelWarn is a pre-built pointer to the string "warn".

The default log level is info.


JSON Pretty Printing

After importing the library with:

import (
    "github.com/gyozatech/noodlog"
)

var log *noodlog.Logger

func init() {
   log = noodlog.NewLogger()
}

To enable pretty printing of the JSON logs you can use:

log.EnableJSONPrettyPrint()

or

log.SetConfigs(
    noodlog.Configs{
       JSONPrettyPrint: noodlog.Enable,
    },
)

noodlog.Enable is a pre-built pointer to the bool true.

to disable pretty printing you can use:

log.DisableJSONPrettyPrint()

or

log.SetConfigs(
    noodlog.Configs{
       JSONPrettyPrint: noodlog.Disable,
    },
)

noodlog.Disable is a pre-built pointer to the bool false.

The default value is false.


Colors

After importing the library with:

import (
    "github.com/gyozatech/noodlog"
)

var log *noodlog.Logger

func init() {
   log = noodlog.NewLogger()
}

to enable colors in JSON logs you can use:

log.EnableColors()

or

log.SetConfigs(
    noodlog.Configs{
        Colors: noodlog.Enable,
    },
)

noodlog.Enable is a pre-built pointer to the bool true.

To disable colors you can use:

log.DisableColors()

or

log.SetConfigs(
    noodlog.Configs{
        Colors: noodlog.Disable,
    },
)

noodlog.Disable is a pre-built pointer to the bool false.

The default value is false.

Color

The basic way to use a custom color is declaring using a pointer of a string representing the color. 
log.Cyan, log.Green, log.Default, log.Yellow, log.Purple, log.Red, log.Blue are pre-build pointers to the strings "cyan", "green", "default", "yellow", "purple", "red", "blue".

For instance, you can customize trace color by:

log.SetTraceColor(noodlog.Cyan)

A more detailed explanation of each log level is available later into this section.

Composition of a color

Color can be composed with text color and background color. For each level it can be composed using a string or a true color notation.

Trivial usage is creating a new color like:

log.NewColor(noodlog.Red)

It results a red text on default background

Adding a background color can be done through:

log.NewColor(noodlog.Red).Background(noodlog.Cyan)

In this scenario it prints red text on cyan background

A third option is to edit just background color using default text color:

log.Background(noodlog.Cyan)

A list of pre-built pointer of a string is [here](#Composition of a color).

Library provides also more customization through the usage of true color notation (RGB value). Before the usage of this notation, please consider if your terminal supports truecolor. For instance if you execute (printf required):

printf '\033[38;2;255;0;0mHello World\033[0m'

a red text "Hello World" should be displayed on the screen

In this way a wider set of color is available for logging, besides of the previous way it can be created a color as:

log.NewColorRGB(255,0,0).BackgroundRGB(0,0,255)

Where a red text (255 for red, 0 the others) is showed on blue background (255 for blue, 0 for others).

As in the previous scenario, NewColorRGB and BackgroundRGB hasn't to be executed combined.

Color can be used to set color of Trace log, by typing:

log.SetTraceColor(noodlog.NewColorRGB(255,0,0).BackgroundRGB(0,0,255))

You can customize the single colors (for log level) by using:

log.SetTraceColor(noodlog.Cyan)
log.SetDebugColor(noodlog.NewColorRGB(255,255,0))
log.SetInfoColor(noodlog.NewColor(noodlog.Red).Background(noodlog.Cyan))
log.SetWarnColor(noodlog.NewColor(noodlog.Green).BackgroundRGB(0,255,255))
log.SetErrorColor(noodlog.NewColorRGB(128,255,0).Background(noodlog.Purple))

or

log.SetConfigs(
    noodlog.Configs{
        Colors: noodlog.Enable,
        CustomColors: &noodlog.CustomColors{ 
            Trace: noodlog.Cyan, 
            Debug: noodlog.NewColorRGB(255,255,0),
            Info:  noodlog.NewColor(noodlog.Red).Background(noodlog.Cyan),
            Warn:  noodlog.NewColor(noodlog.Green).BackgroundRGB(0,255,255),
            Error: noodlog.NewColorRGB(128,255,0).Background(noodlog.Purple),    
        },
    },
)

Here we highlight all the different combination available to customize colors.

When enabled, the default colors are:

  • trace: "default"
  • info: "default"
  • debug: "green"
  • warn: "yellow"
  • error: "red"

Trace the caller

Noodles allows you to print the file and the function which are calling the log functions.

After importing the library with:

import (
    "github.com/gyozatech/noodlog"
)

var log *noodlog.Logger

func init() {
   log = noodlog.NewLogger()
}

to enable the trace caller you can use:

log.EnableTraceCaller()

or

log.SetConfigs(
    noodlog.Configs{
        TraceCaller: noodlog.Enable,
    },
)

noodlog.Enable is a pre-built pointer to the bool true.

To disable it:

log.DisableTraceCaller()

or

log.SetConfigs(
    noodlog.Configs{
        TraceCaller: noodlog.Disable,
    },
)

noodlog.Disable is a pre-built pointer to the bool false.

The default value is false.

Important: if you want to import noodlog only in one package of your project (in order to configure it once) and wraps the logging functions you can use the EnableSinglePointTracing to trace file and function the real caller and not of your logging package.

For example:

main.go

package main

import (
   log "example/logging"
)

func main() {
   // main.main real caller we want to track 
   log.Info("Hello folks!")
}

logging/logger.go

package logging

import (
    "github.com/gyozatech/noodlog"
)

var l *noodlog.Logger

func init() {
    l = noodlog.NewLogger()
    // configure logger once
    l.SetConfig(
        noodlog.Configs{
         TraceCaller: noodlog.Enable,
         SinglePointTracing: noodlog.Enable,
      },
    )
}

// wrapper function
func Info(message ...interface{}) {
    // if we wouldn't enable SinglePointTracing
    // logger.Info would have been considered the caller to be tracked
    l.Info(message...)
}

Sensitive params

Noodlog gives you the possibility to enable the obscuration of sensitive params when recognized in the JSON structures (not in the simple strings that you compose).

After importing the library with:

import (
    "github.com/gyozatech/noodlog"
)

var log *noodlog.Logger

func init() {
   log = noodlog.NewLogger()
}

You can enable the sensitive params obscuration with the facility methods:

log.EnableObscureSensitiveData([]string{"param1", "param2", "param3"})

or with the SetConfig function:

log.SetConfigs(
    noodlog.Configs{
        ObscureSensitiveData: noodlog.Enable,
        SensitiveParams: []string{"param1", "param2", "param3"},
    },
)

Where noodlog.Enable is a pre-built pointer to the bool true.

To disable the sensitive params obscuration you can set:

log.DisableObscureSensitiveData()

or

log.SetConfigs(
    noodlog.Configs{
        ObscureSensitiveData: noodlog.Disable,
    },
)

Where noodlog.Disable is a pre-built pointer to the bool false.

The default value for the obscuration is false.


Contribute to the project

If you want to contribute to the project follow the following guidelines. Any form of contribution is encouraged!

Author: Gyozatech
Source Code: https://github.com/gyozatech/noodlog 
License: Apache-2.0 License

#json #go #golang #logger #logging 

Background Fetch for React Native Apps

react-native-background-fetch

Background Fetch is a very simple plugin which attempts to awaken an app in the background about every 15 minutes, providing a short period of background running-time. This plugin will execute your provided callbackFn whenever a background-fetch event occurs.

There is no way to increase the rate which a fetch-event occurs and this plugin sets the rate to the most frequent possible — you will never receive an event faster than 15 minutes. The operating-system will automatically throttle the rate the background-fetch events occur based upon usage patterns. Eg: if user hasn't turned on their phone for a long period of time, fetch events will occur less frequently or if an iOS user disables background refresh they may not happen at all.

:new: Background Fetch now provides a scheduleTask method for scheduling arbitrary "one-shot" or periodic tasks.

iOS

  • There is no way to increase the rate which a fetch-event occurs and this plugin sets the rate to the most frequent possible — you will never receive an event faster than 15 minutes. The operating-system will automatically throttle the rate the background-fetch events occur based upon usage patterns. Eg: if user hasn't turned on their phone for a long period of time, fetch events will occur less frequently.
  • scheduleTask seems only to fire when the device is plugged into power.
  • ⚠️ When your app is terminated, iOS no longer fires events — There is no such thing as stopOnTerminate: false for iOS.
  • iOS can take days before Apple's machine-learning algorithm settles in and begins regularly firing events. Do not sit staring at your logs waiting for an event to fire. If your simulated events work, that's all you need to know that everything is correctly configured.
  • If the user doesn't open your iOS app for long periods of time, iOS will stop firing events.

Android

Installing the plugin

⚠️ If you have a previous version of react-native-background-fetch < 2.7.0 installed into react-native >= 0.60, you should first unlink your previous version as react-native link is no longer required.

$ react-native unlink react-native-background-fetch

With yarn

$ yarn add react-native-background-fetch

With npm

$ npm install --save react-native-background-fetch

Setup Guides

iOS Setup

react-native >= 0.60

Android Setup

react-native >= 0.60

Example

ℹ️ This repo contains its own Example App. See /example

import React from 'react';
import {
  SafeAreaView,
  StyleSheet,
  ScrollView,
  View,
  Text,
  FlatList,
  StatusBar,
} from 'react-native';

import {
  Header,
  Colors
} from 'react-native/Libraries/NewAppScreen';

import BackgroundFetch from "react-native-background-fetch";

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      events: []
    };
  }

  componentDidMount() {
    // Initialize BackgroundFetch ONLY ONCE when component mounts.
    this.initBackgroundFetch();
  }

  async initBackgroundFetch() {
    // BackgroundFetch event handler.
    const onEvent = async (taskId) => {
      console.log('[BackgroundFetch] task: ', taskId);
      // Do your background work...
      await this.addEvent(taskId);
      // IMPORTANT:  You must signal to the OS that your task is complete.
      BackgroundFetch.finish(taskId);
    }

    // Timeout callback is executed when your Task has exceeded its allowed running-time.
    // You must stop what you're doing immediately BackgroundFetch.finish(taskId)
    const onTimeout = async (taskId) => {
      console.warn('[BackgroundFetch] TIMEOUT task: ', taskId);
      BackgroundFetch.finish(taskId);
    }

    // Initialize BackgroundFetch only once when component mounts.
    let status = await BackgroundFetch.configure({minimumFetchInterval: 15}, onEvent, onTimeout);

    console.log('[BackgroundFetch] configure status: ', status);
  }

  // Add a BackgroundFetch event to <FlatList>
  addEvent(taskId) {
    // Simulate a possibly long-running asynchronous task with a Promise.
    return new Promise((resolve, reject) => {
      this.setState(state => ({
        events: [...state.events, {
          taskId: taskId,
          timestamp: (new Date()).toString()
        }]
      }));
      resolve();
    });
  }

  render() {
    return (
      <>
        <StatusBar barStyle="dark-content" />
        <SafeAreaView>
          <ScrollView
            contentInsetAdjustmentBehavior="automatic"
            style={styles.scrollView}>
            <Header />

            <View style={styles.body}>
              <View style={styles.sectionContainer}>
                <Text style={styles.sectionTitle}>BackgroundFetch Demo</Text>
              </View>
            </View>
          </ScrollView>
          <View style={styles.sectionContainer}>
            <FlatList
              data={this.state.events}
              renderItem={({item}) => (<Text>[{item.taskId}]: {item.timestamp}</Text>)}
              keyExtractor={item => item.timestamp}
            />
          </View>
        </SafeAreaView>
      </>
    );
  }
}

const styles = StyleSheet.create({
  scrollView: {
    backgroundColor: Colors.lighter,
  },
  body: {
    backgroundColor: Colors.white,
  },
  sectionContainer: {
    marginTop: 32,
    paddingHorizontal: 24,
  },
  sectionTitle: {
    fontSize: 24,
    fontWeight: '600',
    color: Colors.black,
  },
  sectionDescription: {
    marginTop: 8,
    fontSize: 18,
    fontWeight: '400',
    color: Colors.dark,
  },
});

export default App;

Executing Custom Tasks

In addition to the default background-fetch task defined by BackgroundFetch.configure, you may also execute your own arbitrary "oneshot" or periodic tasks (iOS requires additional Setup Instructions). However, all events will be fired into the Callback provided to BackgroundFetch#configure:

⚠️ iOS:

  • scheduleTask on iOS seems only to run when the device is plugged into power.
  • scheduleTask on iOS are designed for low-priority tasks, such as purging cache files — they tend to be unreliable for mission-critical tasks. scheduleTask will never run as frequently as you want.
  • The default fetch event is much more reliable and fires far more often.
  • scheduleTask on iOS stop when the user terminates the app. There is no such thing as stopOnTerminate: false for iOS.
// Step 1:  Configure BackgroundFetch as usual.
let status = await BackgroundFetch.configure({
  minimumFetchInterval: 15
}, async (taskId) => {  // <-- Event callback
  // This is the fetch-event callback.
  console.log("[BackgroundFetch] taskId: ", taskId);

  // Use a switch statement to route task-handling.
  switch (taskId) {
    case 'com.foo.customtask':
      print("Received custom task");
      break;
    default:
      print("Default fetch task");
  }
  // Finish, providing received taskId.
  BackgroundFetch.finish(taskId);
}, async (taskId) => {  // <-- Task timeout callback
  // This task has exceeded its allowed running-time.
  // You must stop what you're doing and immediately .finish(taskId)
  BackgroundFetch.finish(taskId);
});

// Step 2:  Schedule a custom "oneshot" task "com.foo.customtask" to execute 5000ms from now.
BackgroundFetch.scheduleTask({
  taskId: "com.foo.customtask",
  forceAlarmManager: true,
  delay: 5000  // <-- milliseconds
});

API Documentation

Config

Common Options

@param {Integer} minimumFetchInterval [15]

The minimum interval in minutes to execute background fetch events. Defaults to 15 minutes. Note: Background-fetch events will never occur at a frequency higher than every 15 minutes. Apple uses a secret algorithm to adjust the frequency of fetch events, presumably based upon usage patterns of the app. Fetch events can occur less often than your configured minimumFetchInterval.

@param {Integer} delay (milliseconds)

ℹ️ Valid only for BackgroundFetch.scheduleTask. The minimum number of milliseconds in future that task should execute.

@param {Boolean} periodic [false]

ℹ️ Valid only for BackgroundFetch.scheduleTask. Defaults to false. Set true to execute the task repeatedly. When false, the task will execute just once.

Android Options

@config {Boolean} stopOnTerminate [true]

Set false to continue background-fetch events after user terminates the app. Default to true.

@config {Boolean} startOnBoot [false]

Set true to initiate background-fetch events when the device is rebooted. Defaults to false.

NOTE: startOnBoot requires stopOnTerminate: false.

@config {Boolean} forceAlarmManager [false]

By default, the plugin will use Android's JobScheduler when possible. The JobScheduler API prioritizes for battery-life, throttling task-execution based upon device usage and battery level.

Configuring forceAlarmManager: true will bypass JobScheduler to use Android's older AlarmManager API, resulting in more accurate task-execution at the cost of higher battery usage.

let status = await BackgroundFetch.configure({
  minimumFetchInterval: 15,
  forceAlarmManager: true
}, async (taskId) => {  // <-- Event callback
  console.log("[BackgroundFetch] taskId: ", taskId);
  BackgroundFetch.finish(taskId);
}, async (taskId) => {  // <-- Task timeout callback
  // This task has exceeded its allowed running-time.
  // You must stop what you're doing and immediately .finish(taskId)
  BackgroundFetch.finish(taskId);
});
.
.
.
// And with with #scheduleTask
BackgroundFetch.scheduleTask({
  taskId: 'com.foo.customtask',
  delay: 5000,       // milliseconds
  forceAlarmManager: true,
  periodic: false
});

@config {Boolean} enableHeadless [false]

Set true to enable React Native's Headless JS mechanism, for handling fetch events after app termination.

  • 📂 index.js (MUST BE IN index.js):
import BackgroundFetch from "react-native-background-fetch";

let MyHeadlessTask = async (event) => {
  // Get task id from event {}:
  let taskId = event.taskId;
  let isTimeout = event.timeout;  // <-- true when your background-time has expired.
  if (isTimeout) {
    // This task has exceeded its allowed running-time.
    // You must stop what you're doing immediately finish(taskId)
    console.log('[BackgroundFetch] Headless TIMEOUT:', taskId);
    BackgroundFetch.finish(taskId);
    return;
  }
  console.log('[BackgroundFetch HeadlessTask] start: ', taskId);

  // Perform an example HTTP request.
  // Important:  await asychronous tasks when using HeadlessJS.
  let response = await fetch('https://reactnative.dev/movies.json');
  let responseJson = await response.json();
  console.log('[BackgroundFetch HeadlessTask] response: ', responseJson);

  // Required:  Signal to native code that your task is complete.
  // If you don't do this, your app could be terminated and/or assigned
  // battery-blame for consuming too much time in background.
  BackgroundFetch.finish(taskId);
}

// Register your BackgroundFetch HeadlessTask
BackgroundFetch.registerHeadlessTask(MyHeadlessTask);

@config {integer} requiredNetworkType [BackgroundFetch.NETWORK_TYPE_NONE]

Set basic description of the kind of network your job requires.

If your job doesn't need a network connection, you don't need to use this option as the default value is BackgroundFetch.NETWORK_TYPE_NONE.

NetworkTypeDescription
BackgroundFetch.NETWORK_TYPE_NONEThis job doesn't care about network constraints, either any or none.
BackgroundFetch.NETWORK_TYPE_ANYThis job requires network connectivity.
BackgroundFetch.NETWORK_TYPE_CELLULARThis job requires network connectivity that is a cellular network.
BackgroundFetch.NETWORK_TYPE_UNMETEREDThis job requires network connectivity that is unmetered. Most WiFi networks are unmetered, as in "you can upload as much as you like".
BackgroundFetch.NETWORK_TYPE_NOT_ROAMINGThis job requires network connectivity that is not roaming (being outside the country of origin)

@config {Boolean} requiresBatteryNotLow [false]

Specify that to run this job, the device's battery level must not be low.

This defaults to false. If true, the job will only run when the battery level is not low, which is generally the point where the user is given a "low battery" warning.

@config {Boolean} requiresStorageNotLow [false]

Specify that to run this job, the device's available storage must not be low.

This defaults to false. If true, the job will only run when the device is not in a low storage state, which is generally the point where the user is given a "low storage" warning.

@config {Boolean} requiresCharging [false]

Specify that to run this job, the device must be charging (or be a non-battery-powered device connected to permanent power, such as Android TV devices). This defaults to false.

@config {Boolean} requiresDeviceIdle [false]

When set true, ensure that this job will not run if the device is in active use.

The default state is false: that is, the for the job to be runnable even when someone is interacting with the device.

This state is a loose definition provided by the system. In general, it means that the device is not currently being used interactively, and has not been in use for some time. As such, it is a good time to perform resource heavy jobs. Bear in mind that battery usage will still be attributed to your application, and shown to the user in battery stats.


Methods

Method NameArgumentsReturnsNotes
configure{FetchConfig}, callbackFn, timeoutFnPromise<BackgroundFetchStatus>Configures the plugin's callbackFn and timeoutFn. This callback will fire each time a background-fetch event occurs in addition to events from #scheduleTask. The timeoutFn will be called when the OS reports your task is nearing the end of its allowed background-time.
scheduleTask{TaskConfig}Promise<boolean>Executes a custom task. The task will be executed in the same Callback function provided to #configure.
statuscallbackFnPromise<BackgroundFetchStatus>Your callback will be executed with the current status (Integer) 0: Restricted, 1: Denied, 2: Available. These constants are defined as BackgroundFetch.STATUS_RESTRICTED, BackgroundFetch.STATUS_DENIED, BackgroundFetch.STATUS_AVAILABLE (NOTE: Android will always return STATUS_AVAILABLE)
finishString taskIdVoidYou MUST call this method in your callbackFn provided to #configure in order to signal to the OS that your task is complete. iOS provides only 30s of background-time for a fetch-event -- if you exceed this 30s, iOS will kill your app.
startnonePromise<BackgroundFetchStatus>Start the background-fetch API. Your callbackFn provided to #configure will be executed each time a background-fetch event occurs. NOTE the #configure method automatically calls #start. You do not have to call this method after you #configure the plugin
stop[taskId:String]Promise<boolean>Stop the background-fetch API and all #scheduleTask from firing events. Your callbackFn provided to #configure will no longer be executed. If you provide an optional taskId, only that #scheduleTask will be stopped.

Debugging

iOS

🆕 BGTaskScheduler API for iOS 13+

  • ⚠️ At the time of writing, the new task simulator does not yet work in Simulator; Only real devices.
  • See Apple docs Starting and Terminating Tasks During Development
  • After running your app in XCode, Click the [||] button to initiate a Breakpoint.
  • In the console (lldb), paste the following command (Note: use cursor up/down keys to cycle through previously run commands):
e -l objc -- (void)[[BGTaskScheduler sharedScheduler] _simulateLaunchForTaskWithIdentifier:@"com.transistorsoft.fetch"]
  • Click the [ > ] button to continue. The task will execute and the Callback function provided to BackgroundFetch.configure will receive the event.

Simulating task-timeout events

  • Only the new BGTaskScheduler api supports simulated task-timeout events. To simulate a task-timeout, your fetchCallback must not call BackgroundFetch.finish(taskId):
let status = await BackgroundFetch.configure({
  minimumFetchInterval: 15
}, async (taskId) => {  // <-- Event callback.
  // This is the task callback.
  console.log("[BackgroundFetch] taskId", taskId);
  //BackgroundFetch.finish(taskId); // <-- Disable .finish(taskId) when simulating an iOS task timeout
}, async (taskId) => {  // <-- Event timeout callback
  // This task has exceeded its allowed running-time.
  // You must stop what you're doing and immediately .finish(taskId)
  print("[BackgroundFetch] TIMEOUT taskId:", taskId);
  BackgroundFetch.finish(taskId);
});
  • Now simulate an iOS task timeout as follows, in the same manner as simulating an event above:
e -l objc -- (void)[[BGTaskScheduler sharedScheduler] _simulateExpirationForTaskWithIdentifier:@"com.transistorsoft.fetch"]

Old BackgroundFetch API

  • Simulate background fetch events in XCode using Debug->Simulate Background Fetch
  • iOS can take some hours or even days to start a consistently scheduling background-fetch events since iOS schedules fetch events based upon the user's patterns of activity. If Simulate Background Fetch works, your can be sure that everything is working fine. You just need to wait.

Android

  • Observe plugin logs in $ adb logcat:
$ adb logcat *:S ReactNative:V ReactNativeJS:V TSBackgroundFetch:V
  • Simulate a background-fetch event on a device (insert <your.application.id>) (only works for sdk 21+:
$ adb shell cmd jobscheduler run -f <your.application.id> 999
  • For devices with sdk <21, simulate a "Headless JS" event with (insert <your.application.id>)
$ adb shell am broadcast -a <your.application.id>.event.BACKGROUND_FETCH

Download Details:
Author: transistorsoft
Source Code: https://github.com/transistorsoft/react-native-background-fetch
License: MIT license

#react  #reactnative  #mobileapp  #javascript 

Brandon  Adams

Brandon Adams

1625637060

What is JSON? | JSON Objects and JSON Arrays | Working with JSONs Tutorial

In this video, we work with JSONs, which are a common data format for most web services (i.e. APIs). Thank you for watching and happy coding!

Need some new tech gadgets or a new charger? Buy from my Amazon Storefront https://www.amazon.com/shop/blondiebytes

What is an API?
https://youtu.be/T74OdSCBJfw

JSON Google Extension
https://chrome.google.com/webstore/detail/json-formatter/bcjindcccaagfpapjjmafapmmgkkhgoa?hl=en

Endpoint Example
http://maps.googleapis.com/maps/api/geocode/json?address=13+East+60th+Street+New+York,+NY

Check out my courses on LinkedIn Learning!
REFERRAL CODE: https://linkedin-learning.pxf.io/blondiebytes
https://www.linkedin.com/learning/instructors/kathryn-hodge

Support me on Patreon!
https://www.patreon.com/blondiebytes

Check out my Python Basics course on Highbrow!
https://gohighbrow.com/portfolio/python-basics/

Check out behind-the-scenes and more tech tips on my Instagram!
https://instagram.com/blondiebytes/

Free HACKATHON MODE playlist:
https://open.spotify.com/user/12124758083/playlist/6cuse5033woPHT2wf9NdDa?si=VFe9mYuGSP6SUoj8JBYuwg

MY FAVORITE THINGS:
Stitch Fix Invite Code: https://www.stitchfix.com/referral/10013108?sod=w&som=c
FabFitFun Invite Code: http://xo.fff.me/h9-GH
Uber Invite Code: kathrynh1277ue
Postmates Invite Code: 7373F
SoulCycle Invite Code: https://www.soul-cycle.com/r/WY3DlxF0/
Rent The Runway: https://rtr.app.link/e/rfHlXRUZuO

Want to BINGE?? Check out these playlists…

Quick Code Tutorials: https://www.youtube.com/watch?v=4K4QhIAfGKY&index=1&list=PLcLMSci1ZoPu9ryGJvDDuunVMjwKhDpkB

Command Line: https://www.youtube.com/watch?v=Jm8-UFf8IMg&index=1&list=PLcLMSci1ZoPvbvAIn_tuSzMgF1c7VVJ6e

30 Days of Code: https://www.youtube.com/watch?v=K5WxmFfIWbo&index=2&list=PLcLMSci1ZoPs6jV0O3LBJwChjRon3lE1F

Intermediate Web Dev Tutorials: https://www.youtube.com/watch?v=LFa9fnQGb3g&index=1&list=PLcLMSci1ZoPubx8doMzttR2ROIl4uzQbK

GitHub | https://github.com/blondiebytes

Twitter | https://twitter.com/blondiebytes

LinkedIn | https://www.linkedin.com/in/blondiebytes

#jsons #json arrays #json objects #what is json #jsons tutorial #blondiebytes

Gone/log: Golang Logging Library

gone/log

Golang logging library 

Package gone/log is a drop-in replacement for the standard Go logging library "log" which is fully source code compatible support all the standard library API while at the same time offering advanced logging features through an extended API.

The design goals of gone/log was:

  • Standard library source level compatibility with mostly preserved behavior.
  • Leveled logging with syslog levels.
  • Structured key/value logging
  • Hierarchical context-able logging to have k/v data in context logged automatically.
  • Low resource usage to allow more (debug) log-statements even if they don't result in output.
  • Light syntax to encourage logging on INFO/DEBUG level. (and low cost of doing so)
  • Flexibility in how log events are output.
  • A fast simple lightweight default in systemd new-daemon style only outputting message to standard output.

See the examples in api_test.go

Logging Overview

Logging is done through *log.Logger objects. They implement all the logging API.

A log event is created by calling one of the logging methods on a *log.Logger object - like ERROR(). Loggers are arranged in a hierarchy. Traversing it will find a Handler chain. The event is then sent through the Handler chain until it ends at a formatting Handler. Potentially the formatted event is then sent through a chain of Writers to finally reach it's *os.File destination.

diagram

Every Logger has its own config, which determines the max log level for which it will generate log events. Whether an event will be generated is determined by the exact Logger on which a log method was called.

A Logger can have associated a Handler - but need not to.

Logger objects can be named, in which case they are participate in a global hierarchy. This hierarchy is traversed for a log event until a Logger with a Handler is found. The event is then passed to that Handler.

The event is then passed along a chain of Handler objects which determines whether and how the event will be logged. Handlers can be any object implementing the Handler interface.

Normally the Handler chain ends i a "Formatting" Handler - a Handler which converts the log event to a log-line. The log line can then be passed to a chain of Writers, which again can do filtering and other decisions. In the end a Writer can Write() the log line to an *os.File.

Handler chains need not end in Formatters and Writers. A Handler could easily be written which just (say) was a statsd network client.

On every Logger (named or not) you can call With() to get a "child" Logger which stores key/value context data to be logged with every log event. Such Loggers always have the same name as their parent. They are just a shorthand to not write all key/value context with every log statement.

Example

The library is 100% source code compatible with the standard library logger

    import "github.com/One-com/gonelog/log"

    log.Println("Hello log")

    mylog := log.New(os.Stdout,"PFX:",log.LstdFlags)
    mylog.Fatal("Arggh")

 

... at the same time as providing several extra features:

h := log.NewStdFormatter(os.Stdout,"",log.LstdFlags|log.Llevel|log.Lpid|log.Lshortfile)
l := log.NewLogger(syslog.LOG_WARN,h)

err := DangerousOperation()
if err != nil {
	l.ERROR("An error happened", "err", err)
}

context_logger := l.With("session", session-id)

context_logger.WARN("Session will expire soon")

Plese see the GoDoc documentation

Author: One-com
Source Code: https://github.com/One-com/gone/tree/master/log 
License: View license

#go #golang #logger #logging 

Dynamic JSON in Golang | Golang Tutorial JSON | Golang Tutorial

A Simple Example to show How to Unmarshall A Dynamic JSON in GoLang.
Dynamic JSON Example in Golang
Install Package :go get github.com/Jeffail/gabs
Gabs is a small utility for dealing with dynamic or unknown JSON structures in Go. It’s pretty much just a helpful wrapper for navigating hierarchies of map[string]interface{} objects provided by the encoding/json package. It does nothing spectacular apart from being fabulous.

#golang #golangTutorial #GolangJSON #dynamicJsonGolang #GOJSON #golangSimpleExample

#golang #golangjson #go #json