Skip to content
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

feat: Move all logs everything over to logger #830

Merged
merged 6 commits into from
Oct 11, 2023
Merged
Show file tree
Hide file tree
Changes from 2 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
3 changes: 2 additions & 1 deletion .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ const rules = {
'@typescript-eslint/no-unused-vars': ['error'],
'no-prototype-builtins': 'off',
'no-empty': 'off',
'no-console': 'error',
}

const extend = [
Expand Down Expand Up @@ -51,7 +52,7 @@ module.exports = {
// but excluding the 'plugin:compat/recommended' rule
// we don't mind using the latest features in our tests
extends: extend.filter((s) => s !== 'plugin:compat/recommended'),
rules,
rules: rules.filter((s) => s !== 'no-console'),
},
],
root: true,
Expand Down
5 changes: 3 additions & 2 deletions react/src/context/PostHogProvider.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/* eslint-disable no-console */
import posthogJs, { PostHogConfig } from 'posthog-js'

import React, { useMemo } from 'react'
Expand All @@ -17,13 +18,13 @@ export function PostHogProvider({
const posthog = useMemo(() => {
if (client && apiKey) {
console.warn(
'You have provided both a client and an apiKey to PostHogProvider. The apiKey will be ignored in favour of the client.'
'[PostHog] You have provided both a client and an apiKey to PostHogProvider. The apiKey will be ignored in favour of the client.'
)
}

if (client && options) {
console.warn(
'You have provided both a client and options to PostHogProvider. The options will be ignored in favour of the client.'
'[PostHog] You have provided both a client and options to PostHogProvider. The options will be ignored in favour of the client.'
)
}

Expand Down
4 changes: 2 additions & 2 deletions src/autocapture-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
* @returns {string} the element's class
*/
import { AutocaptureConfig } from 'types'
import { _each, _includes, _isUndefined, _trim } from './utils'
import { _each, _includes, _isUndefined, _trim, logger } from './utils'

export function getClassName(el: Element): string {
switch (typeof el.className) {
Expand Down Expand Up @@ -335,7 +335,7 @@ export function getNestedSpanText(target: Element): string {
text = `${text} ${getNestedSpanText(child)}`.trim()
}
} catch (e) {
console.error(e)
logger.error(e)
}
}
})
Expand Down
2 changes: 1 addition & 1 deletion src/autocapture.ts
Original file line number Diff line number Diff line change
Expand Up @@ -311,7 +311,7 @@ const autocapture = {
afterDecideResponse: function (response: DecideResponse, instance: PostHog): void {
const token = instance.config.token
if (this._initializedTokens.indexOf(token) > -1) {
logger.log('autocapture already initialized for token "' + token + '"')
logger.info('autocapture already initialized for token "' + token + '"')
return
}

Expand Down
12 changes: 6 additions & 6 deletions src/decide.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { autocapture } from './autocapture'
import { _base64Encode, loadScript } from './utils'
import { _base64Encode, loadScript, logger } from './utils'
import { PostHog } from './posthog-core'
import { Compression, DecideResponse } from './types'
import { STORED_GROUP_PROPERTIES_KEY, STORED_PERSON_PROPERTIES_KEY } from './constants'
Expand Down Expand Up @@ -44,11 +44,11 @@ export class Decide {
this.instance.featureFlags._startReloadTimer()

if (response?.status === 0) {
console.error('Failed to fetch feature flags from PostHog.')
logger.error('Failed to fetch feature flags from PostHog.')
return
}
if (!(document && document.body)) {
console.log('document not ready yet, trying again in 500 milliseconds...')
logger.info('document not ready yet, trying again in 500 milliseconds...')
setTimeout(() => {
this.parseDecideResponse(response)
}, 500)
Expand Down Expand Up @@ -82,7 +82,7 @@ export class Decide {
if (response['surveys'] && !surveysGenerator) {
loadScript(this.instance.config.api_host + `/static/surveys.js`, (err) => {
if (err) {
return console.error(`Could not load surveys script`, err)
return logger.error(`Could not load surveys script`, err)
}

// eslint-disable-next-line @typescript-eslint/ban-ts-comment
Expand All @@ -104,12 +104,12 @@ export class Decide {

loadScript(scriptUrl, (err) => {
if (err) {
console.error(`Error while initializing PostHog app with config id ${id}`, err)
logger.error(`Error while initializing PostHog app with config id ${id}`, err)
}
})
}
} else if (response['siteApps'].length > 0) {
console.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')
logger.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')
}
}
}
Expand Down
8 changes: 3 additions & 5 deletions src/extensions/exceptions/exception-autocapture.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { window } from '../../utils'
import { logger, window } from '../../utils'
import { PostHog } from '../../posthog-core'
import { DecideResponse, Properties } from '../../types'
import { ErrorEventArgs, ErrorProperties, errorToProperties, unhandledRejectionToProperties } from './error-conversion'
Expand All @@ -19,9 +19,7 @@ export class ExceptionObserver {
}

private debugLog(...args: any[]) {
if (this.instance.config.debug) {
console.log('PostHog.js [PostHog.ExceptionObserver]', ...args)
}
logger.info('[ExceptionObserver]', ...args)
}

startCapturing() {
Expand Down Expand Up @@ -62,7 +60,7 @@ export class ExceptionObserver {
}.bind(this)
;(window.onunhandledrejection as any).__POSTHOG_INSTRUMENTED__ = true
} catch (e) {
console.error('PostHog failed to start exception autocapture', e)
logger.error('PostHog failed to start exception autocapture', e)
this.stopCapturing()
}
}
Expand Down
3 changes: 2 additions & 1 deletion src/extensions/segment-integration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
* })
* ```
*/
import { logger } from '../utils'
import { PostHog } from '../posthog-core'

// Loosely based on https://github.com/segmentio/analytics-next/blob/master/packages/core/src/plugins/index.ts
Expand Down Expand Up @@ -46,7 +47,7 @@ interface SegmentPlugin {

export const createSegmentIntegration = (posthog: PostHog): SegmentPlugin => {
if (!Promise || !Promise.resolve) {
console.warn('This browser does not have Promise support, and can not use the segment integration')
logger.warn('This browser does not have Promise support, and can not use the segment integration')
}

const enrichEvent = (ctx: SegmentPluginContext, eventName: string) => {
Expand Down
2 changes: 1 addition & 1 deletion src/extensions/sessionrecording.ts
Original file line number Diff line number Diff line change
Expand Up @@ -348,7 +348,7 @@ export class SessionRecording {
new MutationRateLimiter(this.rrwebRecord, {
onBlockedNode: (id, node) => {
const message = `Too many mutations on node '${id}'. Rate limiting. This could be due to SVG animations or something similar`
logger.log(message, {
logger.info(message, {
node: node,
})

Expand Down
8 changes: 4 additions & 4 deletions src/extensions/web-performance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,14 +102,14 @@ export class WebPerformanceObserver {
}

if (window?.PerformanceObserver?.supportedEntryTypes === undefined) {
logger.log(
'PostHog Performance observer not started because PerformanceObserver is not supported by this browser.'
logger.info(
'[PerformanceObserver] not started because PerformanceObserver is not supported by this browser.'
)
return
}

if (isLocalhost() && !this._forceAllowLocalhost) {
logger.log('PostHog Peformance observer not started because we are on localhost.')
logger.info('[PerformanceObserver] not started because we are on localhost.')
return
}

Expand All @@ -130,7 +130,7 @@ export class WebPerformanceObserver {
this.observer?.observe({ type: entryType, buffered: true })
})
} catch (e) {
console.error('PostHog failed to start performance observer', e)
logger.error('PostHog failed to start performance observer', e)
this.stopObserving()
}
}
Expand Down
42 changes: 4 additions & 38 deletions src/gdpr-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
* These functions are used internally by the SDK and are not intended to be publicly exposed.
*/

import { _each, _includes, _isNumber, _isString, window } from './utils'
import { _each, _includes, _isNumber, _isString, logger, window } from './utils'
import { cookieStore, localStore, localPlusCookieStore } from './storage'
import { GDPROptions, PersistentStore } from './types'
import { PostHog } from './posthog-core'
Expand Down Expand Up @@ -188,7 +188,7 @@ function _hasDoNotTrackFlagOn(options: GDPROptions) {
*/
function _optInOut(optValue: boolean, token: string, options: GDPROptions) {
if (!_isString(token) || !token.length) {
console.error('gdpr.' + (optValue ? 'optIn' : 'optOut') + ' called with an invalid token')
logger.error('gdpr.' + (optValue ? 'optIn' : 'optOut') + ' called with an invalid token')
return
}

Expand All @@ -210,7 +210,7 @@ function _optInOut(optValue: boolean, token: string, options: GDPROptions) {
}
}

export function userOptedOut(posthog: PostHog, silenceErrors: boolean | undefined) {
export function userOptedOut(posthog: PostHog) {
let optedOut = false

try {
Expand All @@ -230,41 +230,7 @@ export function userOptedOut(posthog: PostHog, silenceErrors: boolean | undefine
})
}
} catch (err) {
if (!silenceErrors) {
console.error('Unexpected error when checking capturing opt-out status: ' + err)
}
logger.error('Unexpected error when checking capturing opt-out status: ' + err)
}
return optedOut
}

/**
* Wrap a method with a check for whether the user is opted out of data capturing and cookies/localstorage for the given token
* If the user has opted out, return early instead of executing the method.
* If a callback argument was provided, execute it passing the 0 error code.
* @param {PostHog} posthog - the posthog instance
* @param {function} method - wrapped method to be executed if the user has not opted out
* @param silenceErrors
* @returns {*} the result of executing method OR undefined if the user has opted out
*/
export function addOptOutCheck<M extends (...args: any[]) => any = (...args: any[]) => any>(
benjackwhite marked this conversation as resolved.
Show resolved Hide resolved
posthog: PostHog,
method: M,
silenceErrors?: boolean
): M {
return function (...args) {
const optedOut = userOptedOut(posthog, silenceErrors)

if (!optedOut) {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
return method.apply(this, args)
}

const callback = args[args.length - 1]
if (typeof callback === 'function') {
callback(0)
}

return
} as M
}
Loading