Giter Club home page Giter Club logo

cloudwatch-front-logger's Introduction

CloudWatch Front Logger npm version Build Status Coverage Status npm

Save your browser console logs to AWS CloudWatch (Inspired by agea/console-cloud-watch)

Installing

npm i cloudwatch-front-logger

Preparation

1. Create Public Log Group

Go to CloudWatch console and create Log Group for this purpose.

2. Create Policy

Go to IAM Console and create restricted policy for CloudWatch Logs.

  • logs:CreateLogStream
  • logs:PutLogEvents
{
    "Version": "2019-12-08",
    "Statement": [
        {
            "Sid": "CloudWatchFrontLoggerSid",
            "Effect": "Allow",
            "Action": [
                "logs:CreateLogStream",
                "logs:PutLogEvents"
            ],
            "Resource": [
                "arn:aws:logs:*:*:log-group:<LOG_GROUP_NAME>:*:*",
                "arn:aws:logs:*:*:log-group:<LOG_GROUP_NAME>"
            ]
        }
    ]
}

3. Create IAM user

Go to IAM Console and create user with the restricted policy.

Basic Usage

import { Logger } from 'cloudwatch-front-logger'

const accessKeyId = 'XXXXXXXXXXXXXXXXXXXX'
const secretAccessKey = 'YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY'
const region = 'ap-northeast-1'
const logGroupName = '<LOG_GROUP_NAME>'

const logger = new Logger(accessKeyId, secretAccessKey, region, logGroupName)
logger.install()

Logs are collected from the following sources.

  • Uncaught Error
  • console.error() call
  • Manual logger.onError() call
    (See integration examples)

Advanced Usage

Personalize LogStream

By default, "anonymous" is used for logStreamName value. If you wish allocating a unique stream for each user, you can use a method such as Canvas Fingerprint. Pass a resolver function as logStreamNameResolver option value on install() call.

import FingerprintJS from 'fingerprintjs'

logger.install({
  async logStreamNameResolver() {
    const fp = await FingerprintJS.load()
    const { visitorId } = await fp.get()
    return visitorId
  },
})

Customize Formatted Message
Filter Errors

By default, messages are formatted into JSON string which has message and type.

{
  "message": "Err: Something went wrong",
  "type": "uncaught"
}
{
  "message": "Something went wrong",
  "type": "console",
  "level": "error"
}

If you wish formatting them by yourself, pass a formatter function as messageFormatter option value on install() call. Note that you can cancel by returning null from the fuunction.

import StackTrace from 'stacktrace-js'

logger.install({
  async messageFormatter(e, info = { type: 'unknown' }) {
    if (!e.message) {
      return null
    }
    
    let stack = null
    if (e.stack) {
      stack = e.stack
      try {
        stack = await StackTrace.fromError(e, { offline: true })
      } catch (_) {
      }
    }

    return JSON.stringify({
      message: e.message,
      timestamp: new Date().getTime(),
      userAgent: window.navigator.userAgent,
      stack,
      ...info,
    })
  },
})

Use Asynchronous Storage instead of localStorage

By default, localStorage is used for caching logStreamName and nextSequenceToken. Still localStorage has only synchronous API, asynchronous interfaces are also supported. If you need to change storage implementation from localStorage, pass an instance as storage option value on install() call.

import { AsyncStorage } from 'react-native'

logger.install({
  storage: AsyncStorage,
})

Integration Examples

React (Component)

class LoggerComponent extends React.component {

  componentDidCatch(e, info) {
    this.props.logger.onError(e, {
      ...info,
      type: 'react',
    })
  }

  render() {
    return this.props.children
  }
}
<LoggerComponent logger={logger}>
  <App />
</LoggerComponent>

Redux (Middleware)

const createLoggerMiddleware = (logger) => (store) => (next) => (action) => {
  try {
    return next(action)
  } catch (e) {
    logger.onError(e, {
      action,
      type: 'redux',
    })
  }
}
const store = createStore(
  combineReducers(reducers),
  applyMiddleware(createLoggerMiddleware(logger))
)

cloudwatch-front-logger's People

Contributors

brightsider avatar mpyw avatar princed avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.