6.2.24 • Published 2 years ago

@saeon/logger v6.2.24

Weekly downloads
48
License
MIT
Repository
github
Last release
2 years ago

@saeon/logger

A tiny package that adds timestamps to the info, log, warn, and error functions on globalThis.console, and allows for extending console with bespoke functions. Functions for logging to a service via HTTP or GraphQL are included in the package with examples below. The signature of the original object is preserved (unless extended obviously).

Installation

npm install -s @saeon/logger date-fns @babel/runtime

Basic usage

import '@saeon/logger'

// All console logging functions now have a timestamp
console.log(msg)
console.info(msg)
console.warn(msg)
console.error(msg)

Extend / configure the console object

To unhelpfully print 'hello world' every time console.log() is called:

import { configure } from '@saeon/logger'

/**
 * Call the configure function with a callback that exposes the
 * global.console object and the current date-fns formatter
 *
 * Your callback needs to return an object with this signature
 * {
 *   overwrites: {
 *     ... the console.* properties/fns you would like to overwrite
 *   },
 *   timestampFormat: ... date-fns format string (or null)
 * }
 */
configure(({ console, timestampFormat }) => {
  return {
    overwrites: {
      // But note that console.log then won't have a timestamp, since you are overwriting the overwritten console.log function
      log: () => console.log('hello world'),
    },
    formatter: timestampFormat,
  }
})

Log to a webserver

Another potential use of this library is to extend the console object to log to a URL endpoint - there is built-in support for logging to HTTP endpoints as well as GraphQL endpoints (using the @apollo/client library)

Configure HTTP logging

npm install node-fetch # // If NOT a browser environment
import fetch from 'node-fetch' // If NOT a browser environment
import { logToHttp } from '@saeon/logger/log-to-http'
const httpUri = 'https://your API address here.co.za/log'
const batchingInterval = 2000

configure(() => ({
  overwrites: {
    http: logToHttp(httpUri, batchingInterval),
  },
}))

Configure GraphQL logging

First install @apollo/client

npm install @apollo/client

Then configure a link object (Refer to the ApolloClient documentation on how to configure a GraphQL link)

import { logToGql } from '@saeon/logger/log-to-graphql'
import gql from 'graphql-tag'

const link = new HttpLink({ uri: 'your graphql endpoint' })
const batchingInterval = 1800 // 1800 ms = 1.8 secs batching interval

configure(() => ({
  overwrites: {
    gql: logToGql({
      link,
      query: gql`
        mutation logBrowserEvents($input: [BrowserEventInput]!) {
          logBrowserEvents(input: $input)
        }
      `,
    }, batchingInterval),
  },
}))

Or both HTTP, GraphQL, with formatter specified and overwriting the console.error function

configure(({ console }) => {
  return {
    overwrites: {
      error: () => console.log('hello world'),
      gql: logToGql({ link, query }, 2500), // see above
      http: logToHttp(httpUri, 1500), // see above
    },
    formatter: 'yyyy-MM-dd', // https://date-fns.org
  }
})

And now you have the following console.* methods available in your browser or in your webserver

console.log(msg)
console.info(msg)
console.error() // always prints 'hello world'
console.http(msg)
console.gql(msg)

Batching network requests

Both the console.http and console.gql functions batch requests - the maximum rate at which servers are sent information is once per 5 second interval. This makes these functions suitable for logging even very many requests to the server.

This is an example of logging batches of mousemove events every 2 seconds (the default batching interval). Debouncing events that are fired often is good practice:

const debounce = (cb, duration = 0) => {
  var timer
  return (...args) => {
    clearTimeout(timer)
    timer = setTimeout(() => cb(...args), duration)
  }
}

document.getElementsByTagName('body')[0].onmousemove = debounce(({ x, y }) =>
  console.http({ x, y, etc })
)
abbrevaggregate-erroragentkeepaliveansi-alignagent-baseansi-regexansi-stylesaprobaare-we-there-yetargparsebabel-plugin-polyfill-corejs2babel-plugin-polyfill-corejs3array-unionbabel-plugin-polyfill-regeneratorbalanced-matchboxenbrace-expansionbracesbrowserslistbuffer-frombuiltinsbuiltin-modulescacachecacheable-lookupcamelcasecacheable-requestcaniuse-litechalkchownrclean-stackci-infocli-boxescli-tablecolor-convertcolor-namecolor-supportcolorscommandercommondirconcat-mapconfig-chainconvert-source-mapcore-js-compatconfigstorecross-spawncrypto-random-stringdebugconsole-control-stringsdecompress-responsedeep-extenddefer-to-connectdelegatesdepddeepmergedot-propdir-globelectron-to-chromiumeastasianwidtherr-codeemoji-regexencodingescape-goatescaladeenv-pathsescape-string-regexpesutilsfast-globestree-walkerfast-memoizefastqfill-rangefind-upform-data-encoderfs-minipassfp-and-orfunction-bindfs.realpathgaugegensyncget-stdinglobget-streamglob-parentglobal-dirsglobalsglobbygraceful-fsgothashas-flaghas-unicodehas-yarnhoist-non-react-staticshosted-git-infohttp-cache-semanticshttp-proxy-agenthttp2-wrapperhttps-proxy-agenthumanize-msiconv-liteignoreignore-walkinfer-ownerinflightimport-lazyinheritsiniipis-builtin-moduleis-ciis-core-moduleis-fullwidth-code-pointis-extglobis-installed-globallyis-globimurmurhashis-lambdais-npmis-numberis-moduleis-objis-path-insideis-referenceis-typedarrayis-yarn-globaljjuisexejsescjs-tokensjs-yamljson-bufferjson-parse-even-better-errorsjson-parse-helpfulerrorjson5jsonparsekeyvjsonlineskleurlatest-versionlodashlocate-pathlodash.debounceloose-envifylowercase-keysmagic-stringmake-fetch-happenlru-cachemerge2micromatchmimic-responseminimatchminipassminimistminipass-flushminipass-fetchminipass-pipelineminipass-collectminipass-json-streamminipass-sizedminizlibmkdirpmsnegotiatornode-releasesnoptnormalize-package-datanode-gypnpm-bundlednormalize-urlnpm-install-checksnpm-normalize-package-binnpm-packlistnpm-package-argnpm-registry-fetchnpm-pick-manifestnpmlogobject-assignonceoptimismp-cancelablep-limitp-locatep-mappackage-jsonpacoteparse-github-urlpath-existspath-keypath-is-absolutepath-parsepicocolorspath-typepicomatchprogressproc-logpromise-inflightpromise-retryindent-stringproto-listpupaqueue-microtaskquick-lruprop-typesrcrc-config-loaderreact-isread-package-jsonread-package-json-fastreadable-streamregenerateregenerate-unicode-propertiesregenerator-transformregenerator-runtimeregexpu-coreregistry-auth-tokenregjsgenregistry-urlregjsparserrequire-from-stringremote-git-tagsresolveresolve-alpnresponselikeresponse-iteratorreusifyretryrun-parallelsafe-buffersafer-bufferprompts-ncusemversemver-diffset-blockingsemver-utilsshebang-commandshebang-regexsignal-exitslashsisteransismart-buffersocks-proxy-agentsockssource-mapsource-map-supportspawn-pleasespdx-correctspdx-expression-parsespdx-exceptionsspdx-license-idsssristring-widthstrip-ansistrip-json-commentssupports-colorstring_decodersymbol-observablesupports-preserve-symlinks-flagto-fast-propertiesto-regex-rangetartslibts-invarianttype-festtypedarray-to-bufferunicode-match-property-ecmascriptgraphqlgraphql-tagunicode-canonical-property-names-ecmascriptunicode-property-aliases-ecmascriptunique-filenameunique-slugunique-stringuntildifyunicode-match-property-value-ecmascriptupdate-browserslist-dbutil-deprecateupdate-notifiervalidate-npm-package-namevalidate-npm-package-licensewhichwide-alignwidest-linewrap-ansiwrappywrite-file-atomicxdg-basediryocto-queueyallistyamlzen-observablezen-observable-ts
6.2.24

2 years ago

6.2.20

3 years ago

6.2.21

3 years ago

6.2.22

3 years ago

6.2.17

3 years ago

6.2.18

3 years ago

6.2.16

3 years ago

6.2.19

3 years ago

6.2.15

4 years ago

6.2.14

4 years ago

6.2.13

4 years ago

6.2.11

4 years ago

6.2.12

4 years ago

6.2.10

4 years ago

6.2.9

4 years ago

6.2.8

4 years ago

6.2.7

4 years ago

6.2.5

4 years ago

6.2.4

4 years ago

6.2.6

4 years ago

6.2.3

4 years ago

6.2.2

4 years ago

6.2.1

4 years ago

6.2.0

4 years ago

6.1.3

4 years ago

6.1.2

5 years ago

6.1.1

5 years ago

6.1.0

5 years ago

6.0.6

5 years ago

6.0.1

5 years ago

6.0.0

5 years ago

6.0.3

5 years ago

6.0.2

5 years ago

6.0.5

5 years ago

6.0.4

5 years ago

5.0.4

5 years ago

5.0.3

5 years ago

5.0.2

5 years ago

3.1.16

5 years ago

3.1.14

5 years ago

3.1.12

5 years ago

3.1.11

5 years ago

3.1.10

5 years ago

3.1.9

5 years ago

3.1.8

5 years ago

3.1.7

5 years ago

3.1.6

5 years ago

3.1.5

5 years ago

3.1.4

5 years ago

3.1.3

5 years ago

3.1.2

5 years ago

3.1.1

5 years ago

3.1.0

5 years ago

3.0.1

5 years ago

3.0.0

5 years ago

2.0.3

5 years ago

2.0.2

5 years ago

2.0.1

5 years ago

2.0.0

5 years ago

1.0.5

5 years ago

1.0.4

5 years ago

1.0.3

5 years ago

1.0.2

5 years ago

1.0.1

5 years ago

1.0.0

5 years ago