GithubHelp home page GithubHelp logo

logdna / logdna-browser Goto Github PK

View Code? Open in Web Editor NEW
19.0 19.0 14.0 2.6 MB

A frontend browser logging and exception capturing library for LogDNA

License: MIT License

JavaScript 0.48% TypeScript 99.52%
lib

logdna-browser's People

Contributors

bkniffler avatar logdnabot avatar michaelshi-logdna avatar terrymooreii avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

logdna-browser's Issues

"env" configuration option for init() does not seem to do anything

Here is the config I am using:

logdna.init(LOGDNA_INGESTION_KEY, {
  app: "front-end",
  env: "staging", // this line doesn't seem to do anything
  console: false,
  globalErrorHandlers: false,
  sampleRate: 100,
});

For some reason in the logdna UI none of my logs for this app have an env field. It could be a misconfiguration on my end. As a workaround I've been adding an env field to the meta object of every log (using lineContext) which allows me to filter in the logdna UI by meta.env.

CommonJS imports don't work

This package cannot be used in the CommonJS environment (import via require())

Steps to reproduce

Init empty Node project, install @logdna/browser and try to import it with require

// package.json
{
  "name": "logdna",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@logdna/browser": "^1.1.2"
  }
}
// index.js
const logdna = require("@logdna/browser")

console.log(logdna)
~/D/P/logdna ❯❯❯ node index.js
node:internal/modules/cjs/loader:927
  throw err;
  ^

Error: Cannot find module '@logdna/browser'
Require stack:
- /Users/mxseev/Documents/Projects/logdna/index.js
    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:924:15)
    at Function.Module._load (node:internal/modules/cjs/loader:769:27)
    at Module.require (node:internal/modules/cjs/loader:996:19)
    at require (node:internal/modules/cjs/helpers:92:18)
    at Object.<anonymous> (/Users/mxseev/Documents/Projects/logdna/index.js:1:16)
    at Module._compile (node:internal/modules/cjs/loader:1092:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1121:10)
    at Module.load (node:internal/modules/cjs/loader:972:32)
    at Function.Module._load (node:internal/modules/cjs/loader:813:14)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:76:12) {
  code: 'MODULE_NOT_FOUND',
  requireStack: [ '/Users/mxseev/Documents/Projects/logdna/index.js' ]
}

CORS is Not Recognizing URL after Whitelist is Updated

Hello,

When I pass in the url parameter in the options object in the init function and then use the logger with logdna.debug('hello'), I get a CORS error to a mezmo url that I did not use. I get an error saying that I have not whitelisted the URL even though I already have (yesterday) in the Manage Organizations > CORS Origins page.

Edit: Regarding the mezmo URL, never mind. It seems, after waiting till the next day, it's now taking the URL I give it in the options object when I use the init function.

I'm currently using a logdna-based URL (I'm assuming it's the old way?). Exactly this: https://logs.us-south.logging.cloud.ibm.com/logs/ingest.

But, in the error, I keep seeing it's trying to hit this URL:

This is the URL that's trying to be hit with a POST call:
https://logs.us-south.logging.cloud.ibm.com/logs/ingest?hostname=logdna-browser-logger&now=1671551408621&tags=LogDNA-Browser

This is how I use the init function:

logdna.init(ingestionKey, {
  url: 'https://logs.us-south.logging.cloud.ibm.com/logs/ingest'
});

logdna.debug('hello world');

Here are the errors I see in the console:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://logs.us-south.logging.cloud.ibm.com/logs/ingest?hostname=logdna-browser-logger&now=1671551408621&tags=LogDNA-Browser. (Reason: CORS request did not succeed). Status code: (null).

and

LogDNA Browser Logger is unable to send logs to LogDNA.
Possible issues:
- Your web apps url (https://localhost:4000/) is not listed in your LogDNA account's CORS whitelist domains
- Ingestion key is incorrect
- The configured LogDNA ingestion url is incorrect
- LogDNA ingestion endpoint is down. https://status.mezmo.com/
Error: NetworkError when attempting to fetch resource.

I'm not sure if it's slow to update the CORS whitelist on IBM Cloud's side?

I would love some help on this!

Thank you!

[v2.0.1] Hooks signature has no typings

type BeforeSendHook = Function;

Would be great to see this typed as:

export type Serializable = string | number | boolean | bigint | object | Error

export interface HookArgs {
  message: Serializable
  level: LogLevel
  lineContext: object
}

export type BeforeSendHook = (args: HookArgs) => HookArgs

and exported for use.

ContextT TS type does not allow README example

The README has the following example for setContext:

logdna.addContext({
  // Add any custom metadata such as:
  version: 'v1.0.2',
  sessionReplay: 'http://mySessionReplayTool/',
  user: {
    email: '[email protected]',
  },
});

user throws an error as the ContextT object is typed as { [key: string]: string }. Should it be { [key: string]: string | { [key: string]: string } or does it not allow some amount of recursion here on objects?

Browser hang when logging console message

After putting my create-react-app into production using logdna-browser, I received two reports from end users of the browser hanging completely. My suspicion is that it is the same problem as this issue: pinojs/pino#990

On reverting the update that added logdna-browser, the same users reported the hanging problem was gone. I asked one of the users to send their browser console output to see what was there that might have been triggering the problem. I think it's likely to be the non-fatal error shown below (from somewhere deep in threejs):

ExpandedConsole

(FWIW, this looks like it contains an instance of https://github.com/mrdoob/three.js/blob/master/src/math/Box3.js)

Additionally, I confirmed that logdna-browser is the only package in my project that uses fast-safe-stringify:

 npm ls fast-safe-stringify
[email protected] 
└─┬ @logdna/[email protected]
  └── [email protected] 

I've not been able to reproduce the browser hang so far, but I suspect outputting an object that contains circular references may trigger it.

Unable to use in React Native

I installed the package via:

yarn add @logdna/browser

However, metro complains at runtime while using it

error: Error: While trying to resolve module `@logdna/browser` from file `/Users/user/Developer/app/index.js`, the package `/Users/user/Developer/app/node_modules/@logdna/browser/package.json` was successfully found. However, this package itself specifies a `main` module field that could not be resolved (`/Users/user/Developer/app/node_modules/@logdna/browser/index`. Indeed, none of these files exist:

The plugin ConsolePlugin is already registered with LogDNA Browser

Framework:

  • React with webpack

Created a brand new LogDNA key in the portal and am using that in the UI to connect to LogDNA.

Implementation:
typescript const [legger] = useState( logdna.init((process.env.config as unknown as Config).logDnaApiKey, { hostname: 'al-ui-2', app: 'al-ui-3', console: true, }) );

package json dependencies

image

Webpack common

`javascript
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
entry: path.resolve(__dirname, '..', './src/index.tsx'),
resolve: {
extensions: ['.tsx', '.ts', '.js'],
},
module: {
rules: [
{
test: /.(ts|js)x?$/,
exclude: /node_modules/,
use: [
{
loader: 'babel-loader',
},
],
},
{
test: /.css$/,
use: ['style-loader', 'css-loader'],
},
{
test: /.(?:ico|gif|png|jpg|jpeg)$/i,
type: 'asset/resource',
},
{
test: /.(woff(2)?|eot|ttf|otf|svg|)$/,
type: 'asset/inline',
},
],
},
output: {
path: path.resolve(__dirname, '..', './build'),
filename: 'bundle.js',
},
plugins: [
new HtmlWebpackPlugin({
template: path.resolve(__dirname, '..', './src/index.html'),
}),
],
stats: 'errors-only',
};
`

env specific Webpack:
image

Error in UI(Firefox):
image

Firefox Console:
image

Feature request: allow custom JSON replacer function

Allow custom JSON replacer function to be passed in via options, which will allow us to sanitize sensitive data from the logs (passwords, cc info, etc), helpful if objects passed into meta. Pull request incoming.

Missing main entrypoint can confuse linting

The package.json is missing a main entrypoint that points to dist/index.js. Doesn't seem to affect general ESM imports but custom eslint configs can't parse the modules correctly without it. Any particular reason for it's omission?

[2.0.3] `LogMessage` interface using `Boolean` vs `boolean`

Noticed this then when casting my own copy of the LogMessage and HooksOption type until exported.

https://github.com/logdna/logdna-browser/blob/v2.0.3/src/logdna.d.ts#L65

When using @typescript-eslint/ban-types linting rule, the linter autofixes Boolean to boolean.

Because Boolean !== boolean, it causes:

TS2322: Type 'LogHooksOption' is not assignable to type 'HooksOption'.   
Types of property 'beforeSend' are incompatible. 
...        
Types of property 'disableStacktrace' are incompatible.               
Type 'Boolean | undefined' is not assignable to type 'boolean | undefined'.                 
Type 'Boolean' is not assignable to type 'boolean | undefined'.

Normally I would assume this is developer preference, but I note that all the historic types are cast as primitives eg https://github.com/logdna/logdna-browser/blob/v2.0.3/src/logdna.d.ts#L37 so I imagine this inconsistency was possibly due to linting not running in CI etc?

💥 Type exports for ContextT, LogDNABrowserOptionsT, ILogDNABrowserLogger (and others) broken

Problem

Cannot get visibility on exported types.

Cause

I believe something is getting mangled during Rollup.

This is your dist/types/index.d.ts file, which appears to circularly reference itself on line 1, and does not export the types it is looking for.

However, those types are exported from src/index.d.ts (as seen in the screenshot), thus my inference that something must be occurring during Rollup.

import { ContextT, LogDNABrowserOptionsT, ILogDNABrowserLogger } from './index.d';
declare class LogDNABrowserLogger implements ILogDNABrowserLogger {
    Plugins: {
        PerformanceMeasurePlugin: typeof import("./plugins/performance-measure").default;
    };
    private context;
    private logger?;
    private sessionManager;
    private sampleRateScore;
    private staticContext;
    private plugins;
    private options;
    init(ingestionKey: string, options?: LogDNABrowserOptionsT): LogDNABrowserLogger;
    addContext(context: ContextT): LogDNABrowserLogger;
    setSessionId(sessionId: string): LogDNABrowserLogger;
    clearContext(): void;
    error(message: any, lineContext?: object): void;
    warn(message: any, lineContext?: object): void;
    debug(message: any, lineContext?: object): void;
    info(message: any, lineContext?: object): void;
    log(message: any, lineContext?: object): void;
    captureError(error: Error | ErrorEvent, lineContext?: object): void;
    registerMethod(name: string, fn: Function): void;
    private formatMessageForDebug;
    private registerDefaultPlugins;
    private registerPlugin;
    private registerPlugins;
    private logLines;
    private getStackTrace;
    /**
     * Fetches information about the context that is unlikely to change during the session (ex. browser)
     */
    private getStaticContext;
    /**
     * Fetches information about the context that is likely to change during the session (ex. window location)
     */
    private getDynamicContext;
}
declare const _default: LogDNABrowserLogger;
export default _default;

Error

TS2614: Module '"../../node_modules/@logdna/browser/dist/types"' has no exported member 'LogDNABrowserOptionsT'.

Screenshot

image

Auto clear the offline cache if it exceeds a certain treshold

I ran into an issue where local storage was ... filled. And when I inspected, I saw that logdna was taking most of it. It happened when I was doing a massive refactoring and there were tons of warnings along the way.

image

I deleted it manually and I'm good to go now since that only happened in my local environment and also disabled logdna in local.

But I'm worried this can happen overtime in production if there is a surge of errors or warnings for any reason.

Log Stacktrace not from the original error

Logdna sometimes don't preserve the original stacktrace. I'm loading logdna on an separated file called logs.js at the opening of the <head> file. this file is compiled and minified. the stacktrace shown on most logs are from the own logs.js file, instead of the original error.

errorMessage: Script error.
stacktrace:
@https://myproject.com/js/logs.js:1:21125
@https://myproject.com/js/logs.js:1:18593
@https://myproject.com/js/logs.js:1:19243
@https://myproject.com/js/logs.js:1:14898

[2.0.3] Export `captureError` from root.

In v1.x.x I was able to (albeit indirectly) access captureError which was really useful when I just needed to pipe an error directly from a catch without a lot dealing with the full logger.

I previously was destructuring this from the instantiated root logger (https://github.com/logdna/logdna-browser/blob/v1.1.4/src/index.ts#L165) but as far as I can tell there is no direct access anymore via the root methods export (https://github.com/logdna/logdna-browser/blob/v2.0.3/src/LogDNAMethods.ts)

It would be awesome to get access to https://github.com/logdna/logdna-browser/blob/v2.0.3/src/capture.ts#L34 from the root index exports.

// index.ts

import { LogDNAMethods } from './LogDNAMethods';

import { init, config, methods } from './init';
import plugins from './plugins';
import { addContext } from './context-manager';
import { setSessionId } from './session-manager';
import { captureError } from './capture';

// ...

export { captureError }
export default methods;

Example use case

import { captureError, debug } from "./logger"

const fooAsync = async () => {
  try {
    // ...
  } catch (error) {
    captureError(error)
  } finally {
    debug(`Completed foo.`)
  }
}

const barSync = (url: string) => {
  fetch(url).then(() => {
    // ...
  }).catch(captureError)
}

Losing the original error message

Usually, the javascript error object already have the message property, so this code is overriding the original message that is being lost:

/* istanbul ignore next */
const onUnhandledRejection = (e: any) => {
let error = e;
let reason;
if ('reason' in e) {
reason = e.reason;
} else if (e && e.detail && e.detail.reason) {
reason = e.detail.reason;
}
if (reason instanceof Error) {
error = reason;
} else if (typeof reason === 'string') {
error.message = reason;
} else {
error.message = '<unknown>';
}
error.message = `Uncaught (in promise) ${error.message}`;
captureError(error);
};

image

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.