How to use @optimizely/js-sdk-logging - 10 common examples

To help you get started, we’ve selected a few @optimizely/js-sdk-logging examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github optimizely / javascript-sdk / packages / optimizely-sdk / lib / index.node.js View on Github external
var hasLogger = false;
      config = config || {};

      // TODO warn about setting per instance errorHandler / logger / logLevel
      if (config.errorHandler) {
        logging.setErrorHandler(config.errorHandler);
      }
      if (config.logger) {
        // only set a logger in node if one is provided, by not setting we are noop-ing
        hasLogger = true;
        logging.setLogHandler(config.logger);
        // respect the logger's shouldLog functionality
        logging.setLogLevel(logging.LogLevel.NOTSET);
      }
      if (config.logLevel !== undefined) {
        logging.setLogLevel(config.logLevel);
      }

      try {
        configValidator.validate(config);
        config.isValidInstance = true;
      } catch (ex) {
        if (hasLogger) {
          logger.error(ex);
        } else {
          console.error(ex.message);
        }
        config.isValidInstance = false;
      }

      config = fns.assign(
        {
github optimizely / javascript-sdk / packages / optimizely-sdk / lib / index.node.js View on Github external
createInstance: function(config) {
    try {
      var hasLogger = false;
      config = config || {};

      // TODO warn about setting per instance errorHandler / logger / logLevel
      if (config.errorHandler) {
        logging.setErrorHandler(config.errorHandler);
      }
      if (config.logger) {
        // only set a logger in node if one is provided, by not setting we are noop-ing
        hasLogger = true;
        logging.setLogHandler(config.logger);
        // respect the logger's shouldLog functionality
        logging.setLogLevel(logging.LogLevel.NOTSET);
      }
      if (config.logLevel !== undefined) {
        logging.setLogLevel(config.logLevel);
      }

      try {
        configValidator.validate(config);
        config.isValidInstance = true;
      } catch (ex) {
        if (hasLogger) {
          logger.error(ex);
        } else {
          console.error(ex.message);
        }
        config.isValidInstance = false;
      }
github optimizely / javascript-sdk / packages / optimizely-sdk / lib / index.node.js View on Github external
createInstance: function(config) {
    try {
      var hasLogger = false;
      config = config || {};

      // TODO warn about setting per instance errorHandler / logger / logLevel
      if (config.errorHandler) {
        logging.setErrorHandler(config.errorHandler);
      }
      if (config.logger) {
        // only set a logger in node if one is provided, by not setting we are noop-ing
        hasLogger = true;
        logging.setLogHandler(config.logger);
        // respect the logger's shouldLog functionality
        logging.setLogLevel(logging.LogLevel.NOTSET);
      }
      if (config.logLevel !== undefined) {
        logging.setLogLevel(config.logLevel);
      }

      try {
        configValidator.validate(config);
        config.isValidInstance = true;
      } catch (ex) {
        if (hasLogger) {
          logger.error(ex);
        } else {
          console.error(ex.message);
        }
github optimizely / javascript-sdk / packages / datafile-manager / src / browserCachingDatafileManager.ts View on Github external
* See the License for the specific language governing permissions and
 * limitations under the License.
 */

// TODO: localForage/IndexedDB can store full objects.
// We can store the actual configObj, not the datafile, for fast initialization

import { makeGetRequest } from './browserRequest'
import HttpPollingDatafileManager from './httpPollingDatafileManager'
import { Headers, AbortableRequest, Response } from './http'
import { DatafileManagerConfig } from './datafileManager'
import { LocalForageShim, serialize, deserialize } from './localForageDatafileCache'
import DatafileCache from './datafileCache'
import { getLogger } from '@optimizely/js-sdk-logging'

const logger = getLogger('CachingDatafileManager')

export enum CacheRefreshDirective {
  ONLY_IF_CACHE_MISS = 'ONLY_IF_CACHE_MISS',
  YES_DONT_AWAIT = 'YES_DONT_AWAIT',
  // TODO: The YES_WAIT option is equivalent to not using the cache, so it should be removed.
  // Maybe this whole thing should be replaced with a boolean instead since there are only two valid options.
  YES_AWAIT = 'YES_AWAIT',
}

// TODO: Add maxCacheAge
export interface BrowserCachingDatafileManagerConfig extends DatafileManagerConfig {
  refreshDirective?: CacheRefreshDirective
}

export default class BrowserCachingDatafileManager extends HttpPollingDatafileManager {
  private static localForageShim: LocalForageShim = new LocalForageShim()
github optimizely / javascript-sdk / packages / datafile-manager / src / datafileStorage.ts View on Github external
* You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { getLogger } from '@optimizely/js-sdk-logging'
import { AsyncStorage } from './storage'
import { DatafileCacheEntry, DatafileCacheEntrySerializer } from './datafileCacheEntry';

const logger = getLogger('DatafileManager')

// K is the type used in the storage interface
export default class DatafileStorage implements AsyncStorage {
  private storage: AsyncStorage

  private serializer: DatafileCacheEntrySerializer

  constructor(storage: AsyncStorage, serializer: DatafileCacheEntrySerializer) {
    this.storage = storage
    this.serializer = serializer
  }

  async getItem(key: string): Promise {
    const serializedEntry = await this.storage.getItem(key)
    if (serializedEntry === null) {
      return null
github optimizely / javascript-sdk / packages / datafile-manager / src / datafileCache.ts View on Github external
* distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

// TODO: Log messages should be debug level instead of error?
// TODO: Should it be a write-through cache (memory, then storage, etc.). Maybe this is overcomplicating things.
// TODO: Accepting serialize/deserialize FNs, maybe not the best. could try refactor.
// TODO: maxCacheAge parameter handling

import { getLogger } from '@optimizely/js-sdk-logging'
import { LOCAL_STORAGE_KEY_PREFIX } from './config'
import { DatafileCacheEntry, DeserializationResult } from './datafileCacheEntry'

const logger = getLogger('DatafileManager')

// K is the type returned by getItem and accepted by setItem
export interface AsyncStorage {
  getItem(key: string): Promise
  setItem(key: string, value: K): Promise
  removeItem(key: string): Promise
}

// TODO: Refactor & share this logic for logging a maybe-error with same thing in httpPollingDatafileManager
function logError(maybeErr: any, messageTemplate: string): void {
  if (maybeErr instanceof Error) {
    logger.error(messageTemplate, maybeErr.message, maybeErr)
  } else {
    logger.error(messageTemplate, String(maybeErr))
  }
}
github optimizely / javascript-sdk / packages / event-processor / src / eventDispatcher.browser.ts View on Github external
* Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
// TODO change this to use Managed from js-sdk-models when available
import { objectValues } from '@optimizely/js-sdk-utils'
import {
  BufferedEventDispatcher,
  DispatchEntry,
  EntryStatus,
} from './eventDispatcher'
import { getLogger } from '@optimizely/js-sdk-logging'

const logger = getLogger('EventProcessor')

const LS_KEY = 'optly_fs_event_queue'

export class BrowserEventDispatcher extends BufferedEventDispatcher {
  start(): void {
    super.start()
    const data = window.localStorage.getItem(LS_KEY)
    try {
      if (data) {
        const parsed = JSON.parse(data) as DispatchEntry[]
        logger.info('flushing queue from previous session, num events = %s', parsed.length)
        parsed.forEach((item: DispatchEntry) => {
          this.enqueueAndDispatch(item, () => {})
        })
      }
    } catch (e) {
github optimizely / javascript-sdk / packages / optimizely-sdk / lib / index.browser.js View on Github external
* See the License for the specific language governing permissions and
 * limitations under the License.
 */
require('promise-polyfill/dist/polyfill');
var logging = require('@optimizely/js-sdk-logging');
var fns = require('./utils/fns');
var configValidator = require('./utils/config_validator');
var defaultErrorHandler = require('./plugins/error_handler');
var defaultEventDispatcher = require('./plugins/event_dispatcher/index.browser');
var enums = require('./utils/enums');
var eventProcessor = require('@optimizely/js-sdk-event-processor');
var loggerPlugin = require('./plugins/logger');
var Optimizely = require('./optimizely');
var eventProcessorConfigValidator = require('./utils/event_processor_config_validator');

var logger = logging.getLogger();
logging.setLogHandler(loggerPlugin.createLogger());
logging.setLogLevel(logging.LogLevel.INFO);

var MODULE_NAME = 'INDEX_BROWSER';

var DEFAULT_EVENT_BATCH_SIZE = 10;
var DEFAULT_EVENT_FLUSH_INTERVAL = 1000; // Unit is ms, default is 1s

var hasRetriedEvents = false;
/**
 * Entry point into the Optimizely Browser SDK
 */
module.exports = {
  logging: loggerPlugin,
  errorHandler: defaultErrorHandler,
  eventDispatcher: defaultEventDispatcher,
github optimizely / javascript-sdk / packages / event-processor / src / eventQueue.ts View on Github external
* You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { getLogger } from '@optimizely/js-sdk-logging'
// TODO change this to use Managed from js-sdk-models when available
import { Managed } from './managed'

const logger = getLogger('EventProcessor')

export type EventQueueSink = (buffer: K[]) => Promise

export interface EventQueue extends Managed {
  enqueue(event: K): void
}

export interface EventQueueFactory {
  createEventQueue(config: {
    sink: EventQueueSink
    flushInterval: number
    maxQueueSize: number
  }): EventQueue
}

class Timer {
github optimizely / javascript-sdk / packages / optimizely-sdk / lib / index.react_native.js View on Github external
* See the License for the specific language governing permissions and
 * limitations under the License.
 */
var logging = require('@optimizely/js-sdk-logging');
var fns = require('./utils/fns');
var configValidator = require('./utils/config_validator');
var defaultErrorHandler = require('./plugins/error_handler');
var defaultEventDispatcher = require('./plugins/event_dispatcher/index.browser');
var enums = require('./utils/enums');
var loggerPlugin = require('./plugins/logger/index.react_native');
var Optimizely = require('./optimizely');
var eventProcessorConfigValidator = require('./utils/event_processor_config_validator');

var logger = logging.getLogger();
logging.setLogHandler(loggerPlugin.createLogger());
logging.setLogLevel(logging.LogLevel.INFO);

var DEFAULT_EVENT_BATCH_SIZE = 10;
var DEFAULT_EVENT_FLUSH_INTERVAL = 1000; // Unit is ms, default is 1s

/**
 * Entry point into the Optimizely Javascript SDK for React Native
 */
module.exports = {
  logging: loggerPlugin,
  errorHandler: defaultErrorHandler,
  eventDispatcher: defaultEventDispatcher,
  enums: enums,

  setLogger: logging.setLogHandler,
  setLogLevel: logging.setLogLevel,