Skip to content

Logging client #1

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Jan 13, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions .github/workflows/action.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
name: "fmt-check"
on:
pull_request:
push:
branches:
- master

jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- uses: actions/setup-node@v1
with:
node-version: 12
- run: yarn install --frozen-lockfile
- run: yarn run fmt-check
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,4 @@
.idea/
node_modules

dist/
yarn-error.log
1 change: 1 addition & 0 deletions .prettierignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
dist/
5 changes: 5 additions & 0 deletions .prettierrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"printWidth": 120,
"trailingComma": "es5",
"singleQuote": false
}
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2020 Counting Limited

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
46 changes: 46 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
# browser-logging-client

Sends browser logs to [browser-logging-server](https://www.npmjs.com/package/browser-logging-server).

This is useful for retrieving Cypress UI test browser logs.

Any message sent to `console.log`, `console.warn` and `console.error` will be sent to and logged by the logging server.

### Usage

Add the dependency to your project with:

```
yarn add browser-logging-client
```

or

```
npm install browser-logging-client
```

Then import & initialise at the root of your application.

```js
import browserLoggingClient from "browser-logging-client";
browserLoggingClient.initialise();
```

Note calling `initialise` more than once has no effect.

Ensure the [server](https://www.npmjs.com/package/browser-logging-server) is running before starting your application.

## Publishing

Install `np` - https://github.com/sindresorhus/np:

```
yarn global add np
```

Run `np` and follow instructions.

## License

[MIT](https://opensource.org/licenses/MIT) License.
38 changes: 36 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,41 @@
"name": "browser-logging-client",
"version": "0.0.1",
"description": "Send logs from browser to node server",
"main": "index.js",
"license": "MIT",
"private": false
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
"repository": {
"type": "git",
"url": "[email protected]:Countingup/browser-logging-client.git"
},
"scripts": {
"version": "npm run build",
"postversion": "git push",
"test": "echo No tests.",
"build": "tsc",
"fmt": "prettier --write \"./**/*.{md,js,ts,tsx,json}\"",
"fmt-check": "prettier --list-different \"./**/*.{md,js,ts,tsx,json}\""
},
"files": [
"src",
"dist"
],
"devDependencies": {
"husky": "^3.1.0",
"lint-staged": "^9.4.3",
"prettier": "^1.19.1",
"typescript": "^3.7.2"
},
"dependencies": {},
"lint-staged": {
"*.{md,js,ts,tsx,json}": [
"yarn run prettier --write",
"git add"
]
},
"husky": {
"hooks": {
"pre-commit": "lint-staged"
}
}
}
61 changes: 61 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
let connected = false;
let socket: WebSocket;
let initialised = false;

const defaultLog = console.log;
const defaultWarn = console.warn;
const defaultError = console.error;

/**
* Overrides console.log, warn & error to also send to logging server.
* Allows retrieving logs when running Cypress tests.
* Logging server must be running for this to work. See https://www.npmjs.com/package/browser-logging-server.
*/
export const initialise = (host: string = "localhost", port: number = 8888) => {
if (initialised) return;
initialised = true;

socket = new WebSocket(`ws://${host}:${port}`);
socket.onopen = () => (connected = true);

console.log(`Piping browser logs to logging server at ws://${host}:${port}`);

console.log = pipeToLoggingServer(defaultLog, "INFO");
console.warn = pipeToLoggingServer(defaultWarn, "WARN");
console.error = pipeToLoggingServer(defaultError, "ERROR");
};

const pipeToLoggingServer = (logger: (...args: any[]) => void, logLevel: string) => (...args: any[]) => {
logger(...args);

sendToLoggingServer(Date.now(), logLevel, args, 0);
};

const sendToLoggingServer = (timestamp: number, logLevel: string, message: any[], retryCount: number) => {
if (!connected && retryCount < 10) {
// websocket not connected - retry a bit later
setTimeout(() => sendToLoggingServer(timestamp, logLevel, message, retryCount++), 200);
return;
}
try {
socket.send(JSON.stringify({ timestamp, logLevel, message }, replaceErrors));
} catch (e) {
defaultError("Error sending to logging server:", e);
}
};

// override error stringification (otherwise they display as "{}")
const replaceErrors = (key: string, value: any) => {
if (value instanceof Error) {
const error: { [key: string]: any } = {};

Object.getOwnPropertyNames(value).forEach(key => {
// @ts-ignore
error[key] = value[key];
});

return error;
}

return value;
};
9 changes: 9 additions & 0 deletions tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"declaration": true,
"outDir": "./dist",
"strict": true
}
}
Loading