logdna / logdna-browser Goto Github PK
View Code? Open in Web Editor NEWA frontend browser logging and exception capturing library for LogDNA
License: MIT License
A frontend browser logging and exception capturing library for LogDNA
License: MIT License
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
.
This package cannot be used in the CommonJS environment (import via require()
)
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' ]
}
Just trying out the new v2.0.1
and noticed that despite enabling
const options = {
console: true
}
the logger is no longer sending lines to console output.
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 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.mezmo
url that I did not use.
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!
logdna-browser/src/logdna.d.ts
Line 88 in f8e09e7
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.
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?
Hello there.
I noticed that the package deployed to the npm repo has version 1.4.1 meanwhile here at the github repository it is 2.0.10.
So, my question is this package maintaned or abandoned? How can I install 2.0.10 if there is no such package anywhere?
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):
(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.
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:
Framework:
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
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',
};
`
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.
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?
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?
Cannot get visibility on exported types.
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;
TS2614: Module '"../../node_modules/@logdna/browser/dist/types"' has no exported member 'LogDNABrowserOptionsT'.
In src/utils.ts
, the console methods are cached. However, in a JS worker, window
is undefined, and, so, this code fails with "ReferenceError: window is not defined".
It appears these cached methods are only used in two places: src/plugins/logger.ts and src/capture.ts.
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.
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.
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
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;
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)
}
Usually, the javascript error object already have the message
property, so this code is overriding the original message that is being lost:
logdna-browser/src/plugins/global-handler.ts
Lines 26 to 48 in 7f7d727
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.