diff --git a/.eslintrc.js b/.eslintrc.js index 355b34298a1..6ddf3697a99 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -35,6 +35,7 @@ const config = { rules: { // Rules that are specific to this repo // All other rules should go into https://github.com/sourcegraph/eslint-config + 'no-console': 'error', 'monorepo/no-relative-import': 'error', '@sourcegraph/sourcegraph/check-help-links': 'error', '@typescript-eslint/consistent-type-exports': 'warn', @@ -221,6 +222,12 @@ See https://handbook.sourcegraph.com/community/faq#is-all-of-sourcegraph-open-so 'import/no-default-export': 'off', }, }, + { + files: ['**/gulpfile.js', '**/story/**.tsx', '**/story/**.ts', '*.story.tsx'], + rules: { + 'no-console': 'off', + }, + }, ], } diff --git a/client/branded/src/components/panel/views/FileLocations.tsx b/client/branded/src/components/panel/views/FileLocations.tsx index d299d2c1879..0d217eea1a1 100644 --- a/client/branded/src/components/panel/views/FileLocations.tsx +++ b/client/branded/src/components/panel/views/FileLocations.tsx @@ -8,7 +8,7 @@ import { Observable, Subject, Subscription } from 'rxjs' import { catchError, distinctUntilChanged, map, startWith, switchMap } from 'rxjs/operators' import { Badged } from 'sourcegraph' -import { asError, ErrorLike, isErrorLike, isDefined, property } from '@sourcegraph/common' +import { asError, ErrorLike, isErrorLike, isDefined, property, logger } from '@sourcegraph/common' import { Location } from '@sourcegraph/extension-api-types' import { FileSearchResult, FetchFileParameters } from '@sourcegraph/search-ui' import { VirtualList } from '@sourcegraph/shared/src/components/VirtualList' @@ -105,7 +105,7 @@ export class FileLocations extends React.PureComponent { ) .subscribe( stateUpdate => this.setState(stateUpdate), - error => console.error(error) + error => logger.error(error) ) ) diff --git a/client/browser/.eslintrc.js b/client/browser/.eslintrc.js index 3b4c4be8f52..8d40fef3d71 100644 --- a/client/browser/.eslintrc.js +++ b/client/browser/.eslintrc.js @@ -5,5 +5,8 @@ module.exports = { ...baseConfig.parserOptions, project: [__dirname + '/tsconfig.json', __dirname + '/src/end-to-end/tsconfig.json'], }, + rules: { + 'no-console': 'off', + }, overrides: baseConfig.overrides, } diff --git a/client/build-config/.eslintrc.js b/client/build-config/.eslintrc.js index 3747f40c469..c751a8fcdbc 100644 --- a/client/build-config/.eslintrc.js +++ b/client/build-config/.eslintrc.js @@ -8,6 +8,8 @@ module.exports = { ...baseConfig.parserOptions, project: [__dirname + '/tsconfig.json'], }, - rules: {}, + rules: { + 'no-console': 'off', + }, overrides: baseConfig.overrides, } diff --git a/client/codeintellify/src/hoverifier.ts b/client/codeintellify/src/hoverifier.ts index 65f14fa89d4..3decb70dd29 100644 --- a/client/codeintellify/src/hoverifier.ts +++ b/client/codeintellify/src/hoverifier.ts @@ -37,7 +37,7 @@ import { } from 'rxjs/operators' import { Key } from 'ts-key-enum' -import { asError, ErrorLike, isErrorLike } from '@sourcegraph/common' +import { asError, ErrorLike, isErrorLike, logger } from '@sourcegraph/common' import { Position, Range } from '@sourcegraph/extension-api-types' import { elementOverlaps, scrollRectangleIntoCenterIfNeeded, toMaybeLoadingProviderResult } from './helpers' @@ -563,7 +563,7 @@ export function createHoverifier({ if (target) { part = dom.getDiffCodePart?.(target) } else { - console.warn('Could not find target for position in file', position) + logger.warn('Could not find target for position in file', position) } } } @@ -904,7 +904,7 @@ export function createHoverifier({ // Get the document highlights for that position return from(getDocumentHighlights(position)).pipe( catchError(error => { - console.error(error) + logger.error(error) return [] }), map(documentHighlights => ({ diff --git a/client/common/src/util/index.ts b/client/common/src/util/index.ts index d3afac5d7ef..b90dbdc6261 100644 --- a/client/common/src/util/index.ts +++ b/client/common/src/util/index.ts @@ -10,3 +10,4 @@ export * from './rxjs' export * from './strings' export * from './types' export * from './url' +export * from './logger' diff --git a/client/common/src/util/logger.ts b/client/common/src/util/logger.ts new file mode 100644 index 00000000000..2a5fbf65cd9 --- /dev/null +++ b/client/common/src/util/logger.ts @@ -0,0 +1,38 @@ +/* eslint-disable no-console, jsdoc/check-indentation */ +export interface Logger { + log: Console['log'] + warn: Console['warn'] + error: Console['error'] + info: Console['info'] + debug: Console['debug'] +} + +type LoggerArgsType = Parameters + +/** + * The logger utility to be used instead of `console.*` methods in browser environments to: + * 1. Avoid leaving `console.*` added for debugging purposes during development. + * 2. Have more control over logging pipelines. E.g., + * - Forward errors to the error monitoring services. + * - Dynamically change logging level depending on the environment. + * + * Check out the Unified logger service RFC for more context: + * https://docs.google.com/document/d/1PolGRDS9XfKj-IJEBi7BTbVZeUsQfM-3qpjLsLlB-yw/edit + */ +export const logger: Logger = { + log: (...args: LoggerArgsType) => { + console.log(...args) + }, + error: (...args: LoggerArgsType) => { + console.error(...args) + }, + warn: (...args: LoggerArgsType) => { + console.warn(...args) + }, + info: (...args: LoggerArgsType) => { + console.info(...args) + }, + debug: (...args: LoggerArgsType) => { + console.debug(...args) + }, +} diff --git a/client/common/src/util/markdown/markdown.ts b/client/common/src/util/markdown/markdown.ts index 78f098cd01a..1bb03f5d65b 100644 --- a/client/common/src/util/markdown/markdown.ts +++ b/client/common/src/util/markdown/markdown.ts @@ -6,6 +6,8 @@ import { marked } from 'marked' import sanitize from 'sanitize-html' import { Overwrite } from 'utility-types' +import { logger } from '../logger' + /** * Escapes HTML by replacing characters like `<` with their HTML escape sequences like `<` */ @@ -37,7 +39,7 @@ export const highlightCodeSafe = (code: string, language?: string): string => { } return highlightAuto(code).value } catch (error) { - console.warn('Error syntax-highlighting hover markdown code block', error) + logger.warn('Error syntax-highlighting hover markdown code block', error) return escapeHTML(code) } } diff --git a/client/http-client/src/graphql/apollo/fromObservableQuery.ts b/client/http-client/src/graphql/apollo/fromObservableQuery.ts index e514f5551b7..ee1896d5f65 100644 --- a/client/http-client/src/graphql/apollo/fromObservableQuery.ts +++ b/client/http-client/src/graphql/apollo/fromObservableQuery.ts @@ -1,6 +1,8 @@ import { ApolloQueryResult, ObservableQuery, OperationVariables } from '@apollo/client' import { Observable } from 'rxjs' +import { logger } from '@sourcegraph/common' + /** * Converts ObservableQuery returned by `client.watchQuery` to `rxjs` Observable. * @@ -39,7 +41,7 @@ export function fromObservableQueryPromise( return function unsubscribe() { subscriber.unsubscribe() - subscriptionPromise.then(subscription => subscription?.unsubscribe()).catch(error => console.log(error)) + subscriptionPromise.then(subscription => subscription?.unsubscribe()).catch(error => logger.error(error)) } }) } diff --git a/client/jetbrains/.eslintrc.js b/client/jetbrains/.eslintrc.js index 23c93898412..68c77e2e670 100644 --- a/client/jetbrains/.eslintrc.js +++ b/client/jetbrains/.eslintrc.js @@ -8,5 +8,6 @@ module.exports = { ...baseConfig.parserOptions, project: [__dirname + '/tsconfig.json'], }, + rules: { 'no-console': 'off' }, overrides: baseConfig.overrides, } diff --git a/client/observability-client/src/exporters/consoleBatchSpanExporter.ts b/client/observability-client/src/exporters/consoleBatchSpanExporter.ts index 00be07f19f6..d4fba2dcc01 100644 --- a/client/observability-client/src/exporters/consoleBatchSpanExporter.ts +++ b/client/observability-client/src/exporters/consoleBatchSpanExporter.ts @@ -2,6 +2,8 @@ import { Attributes } from '@opentelemetry/api' import { ExportResultCode, hrTimeToMilliseconds, ExportResult } from '@opentelemetry/core' import { SpanExporter, ReadableSpan } from '@opentelemetry/sdk-trace-base' +import { logger } from '@sourcegraph/common' + import { parseAttributes } from '../sdk/pareAttributes' interface FormattedSpan { @@ -73,7 +75,7 @@ export class ConsoleBatchSpanExporter implements SpanExporter { const formattedSpans = this.groupSpans(spans).map(this.nestSpans) for (const span of formattedSpans) { - console.debug(span) + logger.debug(span) } return resultCallback({ code: ExportResultCode.SUCCESS }) diff --git a/client/observability-server/.eslintrc.js b/client/observability-server/.eslintrc.js index 3747f40c469..c751a8fcdbc 100644 --- a/client/observability-server/.eslintrc.js +++ b/client/observability-server/.eslintrc.js @@ -8,6 +8,8 @@ module.exports = { ...baseConfig.parserOptions, project: [__dirname + '/tsconfig.json'], }, - rules: {}, + rules: { + 'no-console': 'off', + }, overrides: baseConfig.overrides, } diff --git a/client/search-ui/src/components/CommitSearchResultMatch.tsx b/client/search-ui/src/components/CommitSearchResultMatch.tsx index 80cde228d1b..bca949c041c 100644 --- a/client/search-ui/src/components/CommitSearchResultMatch.tsx +++ b/client/search-ui/src/components/CommitSearchResultMatch.tsx @@ -6,7 +6,7 @@ import { of } from 'rxjs' import { catchError } from 'rxjs/operators' import sanitizeHtml from 'sanitize-html' -import { highlightNode } from '@sourcegraph/common' +import { highlightNode, logger } from '@sourcegraph/common' import { highlightCode } from '@sourcegraph/search' import { Markdown } from '@sourcegraph/shared/src/components/Markdown' import { PlatformContextProps } from '@sourcegraph/shared/src/platform/context' @@ -47,7 +47,7 @@ export const CommitSearchResultMatch: React.FunctionComponent { - console.log(error) + logger.log(error) return of('
' + sanitizeHtml(item.content) + '
') }) ) diff --git a/client/shared/.eslintrc.js b/client/shared/.eslintrc.js index e75d9b1f3de..eec5aab0c6e 100644 --- a/client/shared/.eslintrc.js +++ b/client/shared/.eslintrc.js @@ -6,5 +6,11 @@ module.exports = { ...baseConfig.parserOptions, project: [__dirname + '/tsconfig.json', __dirname + '/src/testing/tsconfig.json'], }, - overrides: baseConfig.overrides, + overrides: [ + ...baseConfig.overrides, + { + files: ['dev/**/*.*'], + rules: { 'no-console': 'off' }, + }, + ], } diff --git a/client/shared/src/actions/ActionItem.tsx b/client/shared/src/actions/ActionItem.tsx index 95bfe75d09f..c218f7bddca 100644 --- a/client/shared/src/actions/ActionItem.tsx +++ b/client/shared/src/actions/ActionItem.tsx @@ -7,7 +7,7 @@ import { from, Subject, Subscription } from 'rxjs' import { catchError, map, mapTo, mergeMap, startWith, tap } from 'rxjs/operators' import { ActionContribution, Evaluated } from '@sourcegraph/client-api' -import { asError, ErrorLike, isErrorLike, isExternalLink } from '@sourcegraph/common' +import { asError, ErrorLike, isErrorLike, isExternalLink, logger } from '@sourcegraph/common' import { LoadingSpinner, Button, @@ -161,7 +161,7 @@ export class ActionItem extends React.PureComponent this.setState(stateUpdate), - error => console.error(error) + error => logger.error(error) ) ) } diff --git a/client/shared/src/api/client/api/common.ts b/client/shared/src/api/client/api/common.ts index 4a1945f261a..5f9ab280596 100644 --- a/client/shared/src/api/client/api/common.ts +++ b/client/shared/src/api/client/api/common.ts @@ -4,7 +4,7 @@ import { from, Observable, observable as symbolObservable, Subscription } from ' import { mergeMap, finalize } from 'rxjs/operators' import { Subscribable } from 'sourcegraph' -import { asError } from '@sourcegraph/common' +import { asError, logger } from '@sourcegraph/common' import { ProxySubscribable } from '../../extension/api/common' import { isPromiseLike, syncRemoteSubscription } from '../../util' @@ -111,7 +111,7 @@ export const wrapRemoteObservable = ( export const finallyReleaseProxy = () => (source: Observable & Partial): Observable => { const { proxySubscription } = source if (!proxySubscription) { - console.warn('finallyReleaseProxy() used on Observable without proxy subscription') + logger.warn('finallyReleaseProxy() used on Observable without proxy subscription') return source } return source.pipe(finalize(() => proxySubscription.unsubscribe())) diff --git a/client/shared/src/api/client/connection.ts b/client/shared/src/api/client/connection.ts index 12a3d192869..8a5fc46a178 100644 --- a/client/shared/src/api/client/connection.ts +++ b/client/shared/src/api/client/connection.ts @@ -3,6 +3,8 @@ import { from, Subscription } from 'rxjs' import { first } from 'rxjs/operators' import { Unsubscribable } from 'sourcegraph' +import { logger } from '@sourcegraph/common' + import { PlatformContext, ClosableEndpointPair } from '../../platform/context' import { isSettingsValid } from '../../settings/settings' import { FlatExtensionHostAPI, MainThreadAPI } from '../contract' @@ -88,7 +90,7 @@ export async function createExtensionHostClientConnection( comlink.expose(clientAPI, endpoints.expose) proxy.mainThreadAPIInitialized().catch(() => { - console.error('Error notifying extension host of main thread API init.') + logger.error('Error notifying extension host of main thread API init.') }) // TODO(tj): return MainThreadAPI and add to Controller interface diff --git a/client/shared/src/api/client/enabledExtensions.ts b/client/shared/src/api/client/enabledExtensions.ts index a9e2b2b1642..8d9017d0b53 100644 --- a/client/shared/src/api/client/enabledExtensions.ts +++ b/client/shared/src/api/client/enabledExtensions.ts @@ -3,7 +3,7 @@ import { combineLatest, from, Observable, of, throwError } from 'rxjs' import { fromFetch } from 'rxjs/fetch' import { catchError, distinctUntilChanged, map, publishReplay, refCount, shareReplay, switchMap } from 'rxjs/operators' -import { asError, isErrorLike } from '@sourcegraph/common' +import { asError, isErrorLike, logger } from '@sourcegraph/common' import { checkOk } from '@sourcegraph/http-client' import { @@ -95,7 +95,7 @@ export const getEnabledExtensions = once( const sideloadedExtension = from(context.sideloadedExtensionURL).pipe( switchMap(url => (url ? getConfiguredSideloadedExtension(url) : of(null))), catchError(error => { - console.error('Error sideloading extension', error) + logger.error('Error sideloading extension', error) return of(null) }) ) diff --git a/client/shared/src/api/client/mainthread-api.ts b/client/shared/src/api/client/mainthread-api.ts index 241bf4ad317..2ed08ef3fb6 100644 --- a/client/shared/src/api/client/mainthread-api.ts +++ b/client/shared/src/api/client/mainthread-api.ts @@ -3,7 +3,7 @@ import { Subscription, from, Observable, Subject, of } from 'rxjs' import { publishReplay, refCount, switchMap } from 'rxjs/operators' import * as sourcegraph from 'sourcegraph' -import { asError } from '@sourcegraph/common' +import { asError, logger } from '@sourcegraph/common' import { registerBuiltinClientCommands } from '../../commands/commands' import { PlatformContext } from '../../platform/context' @@ -177,7 +177,7 @@ export const initMainThreadAPI = ( return proxySubscribable(getEnabledExtensions(platformContext)) }, logEvent: (eventName, eventProperties) => platformContext.telemetryService?.log(eventName, eventProperties), - logExtensionMessage: (...data) => console.log(...data), + logExtensionMessage: (...data) => logger.log(...data), } return { api, exposedToClient, subscription } diff --git a/client/shared/src/api/client/preload.ts b/client/shared/src/api/client/preload.ts index 3d8a998f623..e7a896214db 100644 --- a/client/shared/src/api/client/preload.ts +++ b/client/shared/src/api/client/preload.ts @@ -1,4 +1,4 @@ -import { isDefined } from '@sourcegraph/common' +import { isDefined, logger } from '@sourcegraph/common' import { ConfiguredExtension, getScriptURLFromExtensionManifest } from '../../extensions/extension' import { ExecutableExtension, extensionsWithMatchedActivationEvent } from '../extension/activation' @@ -54,6 +54,6 @@ export function preloadExtensions({ loadedScriptURLs.add(activeExtension.scriptURL) } } catch (error) { - console.error('Error preloading Sourcegraph extensions:', error) + logger.error('Error preloading Sourcegraph extensions:', error) } } diff --git a/client/shared/src/api/client/search.ts b/client/shared/src/api/client/search.ts index f1ebe6ca4b4..598f75b4f1a 100644 --- a/client/shared/src/api/client/search.ts +++ b/client/shared/src/api/client/search.ts @@ -4,6 +4,8 @@ import { Remote } from 'comlink' import { from, Observable, of, TimeoutError } from 'rxjs' import { catchError, filter, first, switchMap, timeout } from 'rxjs/operators' +import { logger } from '@sourcegraph/common' + import { FlatExtensionHostAPI } from '../contract' import { SharedEventLogger } from '../sharedEventLogger' @@ -57,7 +59,7 @@ export function transformSearchQuery({ timeout(TRANSFORM_QUERY_TIMEOUT), catchError(error => { if (error instanceof TimeoutError) { - console.error(`Extension query transformers took more than ${TRANSFORM_QUERY_TIMEOUT}ms`) + logger.error(`Extension query transformers took more than ${TRANSFORM_QUERY_TIMEOUT}ms`) } return of(query) }) diff --git a/client/shared/src/api/extension/activation.ts b/client/shared/src/api/extension/activation.ts index 16b43b06020..181d682250b 100644 --- a/client/shared/src/api/extension/activation.ts +++ b/client/shared/src/api/extension/activation.ts @@ -4,7 +4,7 @@ import { catchError, concatMap, distinctUntilChanged, first, map, switchMap, tap import sourcegraph from 'sourcegraph' import { Contributions } from '@sourcegraph/client-api' -import { asError, ErrorLike, isErrorLike, hashCode, memoizeObservable } from '@sourcegraph/common' +import { asError, ErrorLike, isErrorLike, hashCode, memoizeObservable, logger } from '@sourcegraph/common' import { ConfiguredExtension, getScriptURLFromExtensionManifest, splitExtensionID } from '../../extensions/extension' import { areExtensionsSame, getEnabledExtensionsForSubject } from '../../extensions/extensions' @@ -192,20 +192,20 @@ export function activateExtensions( // noop }) } catch (error) { - console.error( + logger.error( `Fail to log ExtensionActivation event for extension ${id}:`, asError(error) ) } } - console.log(`Activating Sourcegraph extension: ${id}`) + logger.log(`Activating Sourcegraph extension: ${id}`) return activate(id, scriptURL, createExtensionAPI).catch(error => - console.error(`Error activating extension ${id}:`, asError(error)) + logger.error(`Error activating extension ${id}:`, asError(error)) ) }), [...toDeactivate].map(id => deactivate(id).catch(error => - console.error(`Error deactivating extension ${id}:`, asError(error)) + logger.error(`Error deactivating extension ${id}:`, asError(error)) ) ), ]) @@ -213,7 +213,7 @@ export function activateExtensions( }), map(() => ({ activated: toActivate, deactivated: toDeactivate })), catchError(error => { - console.error('Uncaught error during extension activation', error) + logger.error('Uncaught error during extension activation', error) return [] }) ) @@ -343,29 +343,29 @@ export function extensionsWithMatchedActivationEvent event === '*' || languageActivationEvents.has(event) ) } catch (error) { - console.error(error) + logger.error(error) } return false }) diff --git a/client/shared/src/api/extension/api/callViewProvidersInParallel.ts b/client/shared/src/api/extension/api/callViewProvidersInParallel.ts index c95d4b082ce..0ff501b2326 100644 --- a/client/shared/src/api/extension/api/callViewProvidersInParallel.ts +++ b/client/shared/src/api/extension/api/callViewProvidersInParallel.ts @@ -3,7 +3,7 @@ import { catchError, defaultIfEmpty, map, mergeMap, scan, startWith, switchMap } import sourcegraph from 'sourcegraph' import { ContributableViewContainer } from '@sourcegraph/client-api' -import { allOf, asError, ErrorLike, isDefined, isExactly, isNot, property } from '@sourcegraph/common' +import { allOf, asError, ErrorLike, isDefined, isExactly, isNot, logger, property } from '@sourcegraph/common' import { RegisteredViewProvider, ViewContexts, ViewProviderResult } from '../extensionHostApi' @@ -61,7 +61,7 @@ export function callViewProvidersInParallel(null), catchError((error: unknown): [ErrorLike] => { - console.error('View provider errored:', error) + logger.error('View provider errored:', error) // Pass only primitive copied values because Error object is not // cloneable in Firefox and Safari diff --git a/client/shared/src/api/extension/extensionApi.ts b/client/shared/src/api/extension/extensionApi.ts index 083d2247ad7..d8293acbf2c 100644 --- a/client/shared/src/api/extension/extensionApi.ts +++ b/client/shared/src/api/extension/extensionApi.ts @@ -4,7 +4,7 @@ import { BehaviorSubject, EMPTY, ReplaySubject } from 'rxjs' import { debounceTime, mapTo } from 'rxjs/operators' import * as sourcegraph from 'sourcegraph' -import { asError } from '@sourcegraph/common' +import { asError, logger } from '@sourcegraph/common' import { Location, MarkupKind, Position, Range, Selection } from '@sourcegraph/extension-api-classes' import { ClientAPI } from '../client/api/api' @@ -286,19 +286,19 @@ export function createExtensionAPIFactory( // These were removed, but keep them here so that calls from old extensions do not throw // an exception and completely break. registerTypeDefinitionProvider: () => { - console.warn( + logger.warn( 'sourcegraph.languages.registerTypeDefinitionProvider was removed. Use sourcegraph.languages.registerLocationProvider instead.' ) return { unsubscribe: () => undefined } }, registerImplementationProvider: () => { - console.warn( + logger.warn( 'sourcegraph.languages.registerImplementationProvider was removed. Use sourcegraph.languages.registerLocationProvider instead.' ) return { unsubscribe: () => undefined } }, registerCompletionItemProvider: (): sourcegraph.Unsubscribable => { - console.warn('sourcegraph.languages.registerCompletionItemProvider was removed.') + logger.warn('sourcegraph.languages.registerCompletionItemProvider was removed.') return { unsubscribe: () => undefined } }, } @@ -337,7 +337,7 @@ export function createExtensionAPIFactory( clientAPI .logExtensionMessage(`🧩 %c${extensionID}`, 'background-color: lightgrey;', ...data) .catch(error => { - console.error('Error sending extension message to main thread:', error) + logger.error('Error sending extension message to main thread:', error) }) } }, diff --git a/client/shared/src/api/extension/extensionHostApi.ts b/client/shared/src/api/extension/extensionHostApi.ts index 2387f53bf0c..8f7c9d189b1 100644 --- a/client/shared/src/api/extension/extensionHostApi.ts +++ b/client/shared/src/api/extension/extensionHostApi.ts @@ -27,6 +27,7 @@ import { isDefined, isExactly, isNot, + logger, property, } from '@sourcegraph/common' import * as clientType from '@sourcegraph/extension-api-types' @@ -407,7 +408,7 @@ export function createExtensionHostAPI(state: ExtensionHostState): FlatExtension } catch (error) { // An error during evaluation causes all of the contributions in the same entry to be // discarded. - console.log('Discarding contributions: evaluating expressions or templates failed.', { + logger.error('Discarding contributions: evaluating expressions or templates failed.', { contributions, error, }) @@ -455,7 +456,7 @@ export function createExtensionHostAPI(state: ExtensionHostState): FlatExtension return providerResultToObservable(provider.viewProvider.provideView(context)) }), catchError((error: unknown) => { - console.error('View provider errored:', error) + logger.error('View provider errored:', error) // Pass only primitive copied values because Error object is not // cloneable in Firefox and Safari const { message, name, stack } = asError(error) @@ -575,7 +576,7 @@ export function callProviders> { const logError = (...args: any): void => { if (logErrors) { - console.error('Provider errored:', ...args) + logger.error('Provider errored:', ...args) } } const safeInvokeProvider = (provider: TRegisteredProvider): sourcegraph.ProviderResult => { @@ -721,7 +722,7 @@ function callViewProviders( providerResultToObservable(viewProvider.provideView(context)).pipe( defaultIfEmpty(null), catchError((error: unknown): [ErrorLike] => { - console.error('View provider errored:', error) + logger.error('View provider errored:', error) // Pass only primitive copied values because Error object is not // cloneable in Firefox and Safari const { message, name, stack } = asError(error) diff --git a/client/shared/src/api/extension/main.worker.ts b/client/shared/src/api/extension/main.worker.ts index c96b9e01ed1..33aa832e0c0 100644 --- a/client/shared/src/api/extension/main.worker.ts +++ b/client/shared/src/api/extension/main.worker.ts @@ -3,7 +3,7 @@ import '../../polyfills' import { fromEvent } from 'rxjs' import { take } from 'rxjs/operators' -import { hasProperty } from '@sourcegraph/common' +import { hasProperty, logger } from '@sourcegraph/common' import { isEndpointPair } from '../../platform/context' @@ -34,7 +34,7 @@ async function extensionHostMain(): Promise { const extensionHost = startExtensionHost(endpoints) self.addEventListener('unload', () => extensionHost.unsubscribe()) } catch (error) { - console.error('Error starting the extension host:', error) + logger.error('Error starting the extension host:', error) self.close() } } diff --git a/client/shared/src/api/extension/test/extensionHost.logging.test.ts b/client/shared/src/api/extension/test/extensionHost.logging.test.ts index bc5e6238d7f..aff997aae8c 100644 --- a/client/shared/src/api/extension/test/extensionHost.logging.test.ts +++ b/client/shared/src/api/extension/test/extensionHost.logging.test.ts @@ -1,6 +1,8 @@ import { BehaviorSubject } from 'rxjs' import sinon from 'sinon' +import { logger } from '@sourcegraph/common' + import { ClientAPI } from '../../client/api/api' import { pretendRemote } from '../../util' import { proxySubscribable } from '../api/common' @@ -10,7 +12,7 @@ import { initializeExtensionHostTest } from './test-helpers' const noopMain = pretendRemote({ getEnabledExtensions: () => proxySubscribable(new BehaviorSubject([])), getScriptURLForExtension: () => undefined, - logExtensionMessage: (...data) => console.log(...data), + logExtensionMessage: (...data) => logger.log(...data), }) describe('Extension logging', () => { diff --git a/client/shared/src/commandPalette/CommandList.tsx b/client/shared/src/commandPalette/CommandList.tsx index 0ffd0fb9abf..5e5b091cc9c 100644 --- a/client/shared/src/commandPalette/CommandList.tsx +++ b/client/shared/src/commandPalette/CommandList.tsx @@ -11,7 +11,7 @@ import stringScore from 'string-score' import { Key } from 'ts-key-enum' import { ContributableMenu, Contributions, Evaluated } from '@sourcegraph/client-api' -import { memoizeObservable } from '@sourcegraph/common' +import { memoizeObservable, logger } from '@sourcegraph/common' import { Shortcut } from '@sourcegraph/shared/src/react-shortcuts' import { ButtonProps, @@ -122,7 +122,7 @@ export class CommandList extends React.PureComponent { } return null } catch (error) { - console.error('Error reading recent actions:', error) + logger.error('Error reading recent actions:', error) } CommandList.writeRecentActions(null) return null @@ -137,7 +137,7 @@ export class CommandList extends React.PureComponent { localStorage.setItem(CommandList.RECENT_ACTIONS_STORAGE_KEY, value) } } catch (error) { - console.error('Error writing recent actions:', error) + logger.error('Error writing recent actions:', error) } } diff --git a/client/shared/src/hover/actions.ts b/client/shared/src/hover/actions.ts index 77385083db6..5b1919f0480 100644 --- a/client/shared/src/hover/actions.ts +++ b/client/shared/src/hover/actions.ts @@ -18,7 +18,7 @@ import { import { ContributableMenu, TextDocumentPositionParameters } from '@sourcegraph/client-api' import { HoveredToken, LOADER_DELAY, MaybeLoadingResult, emitLoading } from '@sourcegraph/codeintellify' -import { asError, ErrorLike, isErrorLike, isExternalLink } from '@sourcegraph/common' +import { asError, ErrorLike, isErrorLike, isExternalLink, logger } from '@sourcegraph/common' import { Location } from '@sourcegraph/extension-api-types' import { Context } from '@sourcegraph/template-parser' @@ -534,7 +534,7 @@ export function registerHoverContributions({ // Don't expose remote subscriptions, only sync subscriptions bag .then(() => undefined) .catch(() => { - console.error('Failed to register "Go to Definition" and "Find references" actions with extension host') + logger.error('Failed to register "Go to Definition" and "Find references" actions with extension host') }) // Return promise to provide a way for callers to know when contributions have been successfully registered diff --git a/client/shared/src/notifications/Notifications.tsx b/client/shared/src/notifications/Notifications.tsx index 14d522d980d..7fa7c329ab2 100644 --- a/client/shared/src/notifications/Notifications.tsx +++ b/client/shared/src/notifications/Notifications.tsx @@ -5,7 +5,7 @@ import { from, merge, Subscription } from 'rxjs' import { delay, map, mergeMap, switchMap, takeWhile } from 'rxjs/operators' import { tabbable } from 'tabbable' -import { asError } from '@sourcegraph/common' +import { asError, logger } from '@sourcegraph/common' import { wrapRemoteObservable } from '../api/client/api/common' import { NotificationType } from '../api/extension/extensionHostApi' @@ -180,7 +180,7 @@ export class Notifications extends React.PureComponent 0, }) ) - .catch(error => console.error('Error updating context for notifications', error)) + .catch(error => logger.error('Error updating context for notifications', error)) } public componentWillUnmount(): void { diff --git a/client/shared/src/settings/temporary/TemporarySettingsProvider.tsx b/client/shared/src/settings/temporary/TemporarySettingsProvider.tsx index c5c05501715..19447549be6 100644 --- a/client/shared/src/settings/temporary/TemporarySettingsProvider.tsx +++ b/client/shared/src/settings/temporary/TemporarySettingsProvider.tsx @@ -1,5 +1,7 @@ import React, { createContext, useEffect } from 'react' +import { logger } from '@sourcegraph/common' + import { migrateLocalStorageToTemporarySettings } from './migrateLocalStorageToTemporarySettings' import { TemporarySettingsStorage } from './TemporarySettingsStorage' @@ -23,7 +25,7 @@ export const TemporarySettingsProvider: React.FunctionComponent< await migrateLocalStorageToTemporarySettings(temporarySettingsStorage) } - migrate().catch(console.error) + migrate().catch(logger.error) }, [temporarySettingsStorage]) // Dispose temporary settings storage on unmount. diff --git a/client/shared/src/settings/temporary/TemporarySettingsStorage.ts b/client/shared/src/settings/temporary/TemporarySettingsStorage.ts index b25fc33691f..a0d34f382c9 100644 --- a/client/shared/src/settings/temporary/TemporarySettingsStorage.ts +++ b/client/shared/src/settings/temporary/TemporarySettingsStorage.ts @@ -3,6 +3,7 @@ import { isEqual } from 'lodash' import { Observable, of, Subscription, from, ReplaySubject, Subscriber } from 'rxjs' import { distinctUntilChanged, map } from 'rxjs/operators' +import { logger } from '@sourcegraph/common' import { fromObservableQuery } from '@sourcegraph/http-client' import { GetTemporarySettingsResult } from '../../graphql-operations' @@ -93,7 +94,7 @@ class LocalStorageSettingsBackend implements SettingsBackend { settingsLoaded = true } } catch (error: unknown) { - console.error(error) + logger.error(error) } if (!settingsLoaded) { @@ -121,7 +122,7 @@ class LocalStorageSettingsBackend implements SettingsBackend { const currentSettings = JSON.parse(encodedCurrentSettings) as TemporarySettings localStorage.setItem(this.TemporarySettingsKey, JSON.stringify({ ...currentSettings, ...newSettings })) } catch (error: unknown) { - console.error(error) + logger.error(error) } return of() @@ -167,7 +168,7 @@ class ServersideSettingsBackend implements SettingsBackend { const settings = data.temporarySettings.contents parsedSettings = JSON.parse(settings) as TemporarySettings } catch (error: unknown) { - console.error(error) + logger.error(error) } return parsedSettings || {} @@ -205,7 +206,7 @@ class ServersideSettingsBackend implements SettingsBackend { map(() => {}) // Ignore return value, always empty ) } catch (error: unknown) { - console.error(error) + logger.error(error) } return of() diff --git a/client/shared/src/settings/temporary/migrateLocalStorageToTemporarySettings.ts b/client/shared/src/settings/temporary/migrateLocalStorageToTemporarySettings.ts index a8612d1ccc2..f74126ead7d 100644 --- a/client/shared/src/settings/temporary/migrateLocalStorageToTemporarySettings.ts +++ b/client/shared/src/settings/temporary/migrateLocalStorageToTemporarySettings.ts @@ -1,5 +1,7 @@ import { take } from 'rxjs/operators' +import { logger } from '@sourcegraph/common' + import { TemporarySettings, TemporarySettingsSchema } from './TemporarySettings' import { TemporarySettingsStorage } from './TemporarySettingsStorage' @@ -78,7 +80,7 @@ export async function migrateLocalStorageToTemporarySettings(storage: TemporaryS localStorage.removeItem(migration.localStorageKey) } } catch (error) { - console.error( + logger.error( `Failed to migrate temporary settings "${migration.temporarySettingsKey}" from localStorage using key "${migration.localStorageKey}"`, error ) diff --git a/client/shared/src/testing/accessibility.ts b/client/shared/src/testing/accessibility.ts index fbac74e12d7..b9ee4370af3 100644 --- a/client/shared/src/testing/accessibility.ts +++ b/client/shared/src/testing/accessibility.ts @@ -2,6 +2,8 @@ import { AxePuppeteer } from '@axe-core/puppeteer' import type { Result, NodeResult, RunOptions } from 'axe-core' import { Page } from 'puppeteer' +import { logger } from '@sourcegraph/common' + /** * Takes a list of Axe violation nodes and formats them into a readable string. */ @@ -74,6 +76,6 @@ export async function accessibilityAudit(page: Page, config: AccessibilityAuditC throw new Error(errorMessage) } - console.warn(errorMessage) + logger.warn(errorMessage) } } diff --git a/client/shared/src/testing/coverage.ts b/client/shared/src/testing/coverage.ts index 73c2feb8715..324a2c6c989 100644 --- a/client/shared/src/testing/coverage.ts +++ b/client/shared/src/testing/coverage.ts @@ -3,6 +3,8 @@ import pTimeout from 'p-timeout' import { Browser, WebWorker } from 'puppeteer' import * as uuid from 'uuid' +import { logger } from '@sourcegraph/common' + import { Driver } from './driver' declare global { @@ -48,7 +50,7 @@ export async function recordCoverage(browser: Browser): Promise { 2000, () => { if (!warnedNoCoverage) { - console.error( + logger.error( `No coverage found in target ${target.url()}\n` + 'Run the dev Sourcegraph instance with COVERAGE_INSTRUMENT=true to track coverage.' ) diff --git a/client/shared/src/testing/driver.ts b/client/shared/src/testing/driver.ts index f52c3a01d09..b578ce36259 100644 --- a/client/shared/src/testing/driver.ts +++ b/client/shared/src/testing/driver.ts @@ -21,7 +21,7 @@ import { from, fromEvent, merge, Subscription } from 'rxjs' import { filter, map, concatAll, mergeMap, mergeAll, takeUntil } from 'rxjs/operators' import { Key } from 'ts-key-enum' -import { isDefined } from '@sourcegraph/common' +import { isDefined, logger } from '@sourcegraph/common' import { dataOrThrowErrors, gql, GraphQLResult } from '@sourcegraph/http-client' import { ExternalServiceKind } from '../graphql-operations' @@ -199,7 +199,7 @@ export class Driver { ) ) ) - .subscribe(formattedLine => console.log(formattedLine)) + .subscribe(formattedLine => logger.log(formattedLine)) ) } } @@ -295,7 +295,7 @@ export class Driver { if (!this.keepBrowser) { await this.browser.close() } - console.log( + logger.log( '\n Visited routes:\n' + [ ...new Set( @@ -407,7 +407,7 @@ export class Driver { } // Navigate to the add external service page. - console.log('Adding external service of kind', kind) + logger.log('Adding external service of kind', kind) await this.page.goto(this.sourcegraphBaseUrl + '/site-admin/external-services/new') await this.page.waitForSelector(`[data-test-external-service-card-link="${kind.toUpperCase()}"]`, { visible: true, @@ -800,7 +800,7 @@ export async function createDriverForTest(options?: Partial): Pro args.push(`--window-size=${config.windowWidth},${config.windowHeight}`) if (process.getuid() === 0) { // TODO don't run as root in CI - console.warn('Running as root, disabling sandbox') + logger.warn('Running as root, disabling sandbox') args.push('--no-sandbox', '--disable-setuid-sandbox') } if (loadExtension) { diff --git a/client/shared/src/testing/integration/context.ts b/client/shared/src/testing/integration/context.ts index 18c4b9f8e9f..3d96681eee0 100644 --- a/client/shared/src/testing/integration/context.ts +++ b/client/shared/src/testing/integration/context.ts @@ -14,7 +14,7 @@ import { Subject, Subscription, throwError } from 'rxjs' import { first, timeoutWith } from 'rxjs/operators' import { STATIC_ASSETS_PATH } from '@sourcegraph/build-config' -import { asError, keyExistsIn } from '@sourcegraph/common' +import { logger, asError, keyExistsIn } from '@sourcegraph/common' import { ErrorGraphQLResult, GraphQLResult } from '@sourcegraph/http-client' // eslint-disable-next-line no-restricted-imports import { SourcegraphContext } from '@sourcegraph/web/src/jscontext' @@ -208,7 +208,7 @@ export const createSharedIntegrationTestContext = async < if ((asError(error) as NodeJS.ErrnoException).code === 'ENOENT') { response.sendStatus(404) } else { - console.error(error) + logger.error(error) response.status(500).send(asError(error).message) } } @@ -318,11 +318,11 @@ export const createSharedIntegrationTestContext = async < try { localStorage.clear() } catch (error) { - console.error('Failed to clear localStorage!', error) + logger.error('Failed to clear localStorage!', error) } }), DISPOSE_ACTION_TIMEOUT, - () => console.warn('Failed to clear localStorage!') + () => logger.warn('Failed to clear localStorage!') ) } diff --git a/client/shared/src/testing/integration/polly/CdpAdapter.ts b/client/shared/src/testing/integration/polly/CdpAdapter.ts index dc4dfbc4b50..ca72c90a3bd 100644 --- a/client/shared/src/testing/integration/polly/CdpAdapter.ts +++ b/client/shared/src/testing/integration/polly/CdpAdapter.ts @@ -6,7 +6,7 @@ import { noop } from 'lodash' import Puppeteer from 'puppeteer' import { Observable, Subject } from 'rxjs' -import { isErrorLike } from '@sourcegraph/common' +import { isErrorLike, logger } from '@sourcegraph/common' function toBase64(input: string): string { return Buffer.from(input).toString('base64') @@ -183,7 +183,7 @@ export class CdpAdapter extends PollyAdapter { return new Promise((resolve, reject) => { this.passthroughPromises.set(requestId, { resolve, reject }) - this.continuePausedRequest({ requestId }, cdpSession).catch(console.error) + this.continuePausedRequest({ requestId }, cdpSession).catch(logger.error) }) } @@ -329,7 +329,7 @@ export class CdpAdapter extends PollyAdapter { // Passthrough missing Chrome extension request because it's expected to fail if the extension is not installed. if (request.url.includes('chrome-extension://invalid')) { - this.continuePausedRequest({ requestId: event.requestId }, cdpSession).catch(console.error) + this.continuePausedRequest({ requestId: event.requestId }, cdpSession).catch(logger.error) return } @@ -376,7 +376,7 @@ export class CdpAdapter extends PollyAdapter { this.pendingRequests.get(requestId)?.resolve(pollyResponse) this.pendingRequests.delete(requestId) }) - .catch(console.error) + .catch(logger.error) } } diff --git a/client/shared/src/testing/screenshotReporter.ts b/client/shared/src/testing/screenshotReporter.ts index 9847f3c884e..6af51cd4ed3 100644 --- a/client/shared/src/testing/screenshotReporter.ts +++ b/client/shared/src/testing/screenshotReporter.ts @@ -4,6 +4,8 @@ import { afterEach } from 'mocha' import { mkdir } from 'mz/fs' import * as puppeteer from 'puppeteer' +import { logger } from '@sourcegraph/common' + /** * Registers an `afterEach` hook (for use with Mocha) that takes a screenshot of * the browser when a test fails. It is used by e2e and integration tests. @@ -38,12 +40,12 @@ async function takeScreenshot({ const screenshot = await page.screenshot({ path: filePath }) if (process.env.CI) { // Print image with ANSI escape code for Buildkite: https://buildkite.com/docs/builds/images-in-log-output. - console.log(`\u001B]1338;url="artifact://${path.relative(repoRootDir, filePath)}";alt="Screenshot"\u0007`) + logger.log(`\u001B]1338;url="artifact://${path.relative(repoRootDir, filePath)}";alt="Screenshot"\u0007`) } else if (process.env.TERM_PROGRAM === 'iTerm.app') { // Print image inline for iTerm2 const nameBase64 = Buffer.from(fileName).toString('base64') - console.log(`\u001B]1337;File=name=${nameBase64};inline=1;width=500px:${screenshot.toString('base64')}\u0007`) + logger.log(`\u001B]1337;File=name=${nameBase64};inline=1;width=500px:${screenshot.toString('base64')}\u0007`) } else { - console.log(`📸 Saved screenshot of failure to ${path.relative(process.cwd(), filePath)}`) + logger.log(`📸 Saved screenshot of failure to ${path.relative(process.cwd(), filePath)}`) } } diff --git a/client/shared/src/util/useCodeIntelViewerUpdates.ts b/client/shared/src/util/useCodeIntelViewerUpdates.ts index fd9e638376f..0c7354fa448 100644 --- a/client/shared/src/util/useCodeIntelViewerUpdates.ts +++ b/client/shared/src/util/useCodeIntelViewerUpdates.ts @@ -2,6 +2,8 @@ import { useMemo, useEffect } from 'react' import { ReplaySubject } from 'rxjs' +import { logger } from '@sourcegraph/common' + import { ViewerId } from '../api/viewerTypes' import { ExtensionsControllerProps } from '../extensions/controller' import { HoverContext } from '../hover/HoverOverlay' @@ -64,14 +66,14 @@ export function useCodeIntelViewerUpdates(props?: UseCodeIntelViewerUpdatesProps }) }) .catch(error => { - console.error('Extension host API error', error) + logger.error('Extension host API error', error) }) return () => { // Remove from extension host extensionsController.extHostAPI .then(extensionHostAPI => previousViewerId && extensionHostAPI.removeViewer(previousViewerId)) - .catch(error => console.error('Error removing viewer from extension host', error)) + .catch(error => logger.error('Error removing viewer from extension host', error)) } }, [props, viewerUpdates]) diff --git a/client/storybook/src/apollo/MockedStoryProvider.tsx b/client/storybook/src/apollo/MockedStoryProvider.tsx index d291c10ae1e..a43962f25aa 100644 --- a/client/storybook/src/apollo/MockedStoryProvider.tsx +++ b/client/storybook/src/apollo/MockedStoryProvider.tsx @@ -4,6 +4,7 @@ import { ApolloLink } from '@apollo/client' import { MockedProvider, MockedProviderProps, MockedResponse, MockLink } from '@apollo/client/testing' import { getOperationName } from '@apollo/client/utilities' +import { logger } from '@sourcegraph/common' import { cache } from '@sourcegraph/http-client' /** @@ -16,7 +17,7 @@ const forceMockVariablesLink = (mocks: readonly MockedResponse[]): ApolloLink => if (mock) { operation.variables = mock.request.variables || {} } else { - console.warn(`Unable to find a mock for query: ${operation.operationName}. Did you mean to mock this?`) + logger.warn(`Unable to find a mock for query: ${operation.operationName}. Did you mean to mock this?`) } return forward(operation) }) diff --git a/client/vscode/.eslintrc.js b/client/vscode/.eslintrc.js index 29989a6a88d..80b0e6a6b6d 100644 --- a/client/vscode/.eslintrc.js +++ b/client/vscode/.eslintrc.js @@ -8,5 +8,8 @@ module.exports = { ...baseConfig.parserOptions, project: [__dirname + '/tsconfig.json'], }, + rules: { + 'no-console': 'off', + }, overrides: baseConfig.overrides, } diff --git a/client/web/.eslintrc.js b/client/web/.eslintrc.js index 2b400b8ed53..bae4a1079cb 100644 --- a/client/web/.eslintrc.js +++ b/client/web/.eslintrc.js @@ -11,5 +11,11 @@ module.exports = { files: ['src/stores/**.ts', 'src/__mocks__/zustand.ts'], rules: { 'no-restricted-imports': 'off' }, }, + { + files: 'dev/**/*.ts', + rules: { + 'no-console': 'off', + }, + }, ], } diff --git a/client/web/src/SourcegraphWebApp.tsx b/client/web/src/SourcegraphWebApp.tsx index 95ce4da1458..f6577ad4384 100644 --- a/client/web/src/SourcegraphWebApp.tsx +++ b/client/web/src/SourcegraphWebApp.tsx @@ -11,6 +11,7 @@ import { combineLatest, from, Subscription, fromEvent, of, Subject, Observable } import { distinctUntilChanged, first, map, startWith, switchMap } from 'rxjs/operators' import * as uuid from 'uuid' +import { logger } from '@sourcegraph/common' import { GraphQLClient, HTTPStatusError } from '@sourcegraph/http-client' import { fetchAutoDefinedSearchContexts, @@ -238,7 +239,7 @@ export class SourcegraphWebApp extends React.Component< }) }) .catch(error => { - console.error('Error initializing GraphQL client', error) + logger.error('Error initializing GraphQL client', error) }) this.subscriptions.add( @@ -295,7 +296,7 @@ export class SourcegraphWebApp extends React.Component< } this.setWorkspaceSearchContext(this.state.selectedSearchContextSpec).catch(error => { - console.error('Error sending search context to extensions!', error) + logger.error('Error sending search context to extensions!', error) }) // Update search query state whenever the URL changes @@ -484,7 +485,7 @@ export class SourcegraphWebApp extends React.Component< localStorage.setItem(LAST_SEARCH_CONTEXT_KEY, availableSearchContextSpecOrDefault) this.setWorkspaceSearchContext(availableSearchContextSpecOrDefault).catch(error => { - console.error('Error sending search context to extensions', error) + logger.error('Error sending search context to extensions', error) }) }) ) diff --git a/client/web/src/api/ApiConsole.tsx b/client/web/src/api/ApiConsole.tsx index 1ea32f5b3a9..e2b1d491d3e 100644 --- a/client/web/src/api/ApiConsole.tsx +++ b/client/web/src/api/ApiConsole.tsx @@ -6,7 +6,7 @@ import { from as fromPromise, Subject, Subscription } from 'rxjs' import { catchError, debounceTime } from 'rxjs/operators' import { ErrorAlert } from '@sourcegraph/branded/src/components/alerts' -import { asError, ErrorLike, isErrorLike } from '@sourcegraph/common' +import { asError, ErrorLike, isErrorLike, logger } from '@sourcegraph/common' import { LoadingSpinner, Button, Alert, Link } from '@sourcegraph/wildcard' import { PageTitle } from '../components/PageTitle' @@ -104,7 +104,7 @@ export class ApiConsole extends React.PureComponent { fromPromise(import('graphiql')) .pipe( catchError(error => { - console.error(error) + logger.error(error) return [asError(error)] }) ) diff --git a/client/web/src/auth.ts b/client/web/src/auth.ts index 63662b1c076..9d0fdb5a0ec 100644 --- a/client/web/src/auth.ts +++ b/client/web/src/auth.ts @@ -1,6 +1,7 @@ import { Observable, ReplaySubject } from 'rxjs' import { catchError, map, mergeMap, tap } from 'rxjs/operators' +import { logger } from '@sourcegraph/common' import { dataOrThrowErrors } from '@sourcegraph/http-client' import { AuthenticatedUser as SharedAuthenticatedUser, currentAuthStateQuery } from '@sourcegraph/shared/src/auth' import { CurrentAuthStateResult } from '@sourcegraph/shared/src/graphql-operations' @@ -48,7 +49,7 @@ if (window.context?.isAuthenticatedUser) { refreshAuthenticatedUser() .toPromise() .then(() => undefined) - .catch(error => console.error(error)) + .catch(error => logger.error(error)) } else { authenticatedUser.next(null) } diff --git a/client/web/src/auth/ResetPasswordPage.tsx b/client/web/src/auth/ResetPasswordPage.tsx index 468e7ffa2f2..9e907a68a73 100644 --- a/client/web/src/auth/ResetPasswordPage.tsx +++ b/client/web/src/auth/ResetPasswordPage.tsx @@ -5,7 +5,7 @@ import { useLocation } from 'react-router-dom-v5-compat' import { ErrorAlert } from '@sourcegraph/branded/src/components/alerts' import { Form } from '@sourcegraph/branded/src/components/Form' -import { asError, ErrorLike, isErrorLike } from '@sourcegraph/common' +import { asError, ErrorLike, isErrorLike, logger } from '@sourcegraph/common' import { Button, Link, LoadingSpinner, Alert, Text, Input } from '@sourcegraph/wildcard' import { AuthenticatedUser } from '../auth' @@ -137,7 +137,7 @@ class ResetPasswordInitForm extends React.PureComponent<{}, ResetPasswordInitFor .text() .catch(() => null) .then(text => this.setState({ submitOrError: new Error(text || 'Unknown error') })) - .catch(error => console.error(error)) + .catch(error => logger.error(error)) } }) .catch(error => this.setState({ submitOrError: asError(error) })) diff --git a/client/web/src/auth/TosConsentModal.tsx b/client/web/src/auth/TosConsentModal.tsx index 266288304b4..1422d93a6e6 100644 --- a/client/web/src/auth/TosConsentModal.tsx +++ b/client/web/src/auth/TosConsentModal.tsx @@ -2,6 +2,7 @@ import React, { useCallback, useState } from 'react' import { gql, useMutation } from '@apollo/client' +import { logger } from '@sourcegraph/common' import { Link, Alert, AnchorLink, Checkbox, H1, Text } from '@sourcegraph/wildcard' import { LoaderButton } from '../components/LoaderButton' @@ -37,7 +38,7 @@ export const TosConsentModal: React.FunctionComponent { - console.error('Auth error:', error) + logger.error('Auth error:', error) setLoading(false) onAuthError(asError(error)) }) diff --git a/client/web/src/codeintel/ReferencesPanel.test.tsx b/client/web/src/codeintel/ReferencesPanel.test.tsx index df341d2dd05..177536552da 100644 --- a/client/web/src/codeintel/ReferencesPanel.test.tsx +++ b/client/web/src/codeintel/ReferencesPanel.test.tsx @@ -2,6 +2,7 @@ import { render, RenderResult, within, fireEvent } from '@testing-library/react' import * as H from 'history' import { EMPTY, NEVER, noop, of, Subscription } from 'rxjs' +import { logger } from '@sourcegraph/common' import { FlatExtensionHostAPI } from '@sourcegraph/shared/src/api/contract' import { pretendProxySubscribable, pretendRemote } from '@sourcegraph/shared/src/api/util' import { ViewerId } from '@sourcegraph/shared/src/api/viewerTypes' @@ -59,7 +60,7 @@ const defaultProps: Omit console.error(error) + error => logger.error(error) ) ) diff --git a/client/web/src/components/PageTitle.tsx b/client/web/src/components/PageTitle.tsx index cfb44011052..3fc8031a87c 100644 --- a/client/web/src/components/PageTitle.tsx +++ b/client/web/src/components/PageTitle.tsx @@ -1,5 +1,6 @@ import React, { useEffect } from 'react' +import { logger } from '@sourcegraph/common' import { screenReaderAnnounce } from '@sourcegraph/wildcard' interface PageTitleProps { @@ -19,7 +20,7 @@ let titleSet = false export const PageTitle: React.FunctionComponent> = ({ title }) => { useEffect(() => { if (titleSet) { - console.error('more than one PageTitle used at the same time') + logger.error('more than one PageTitle used at the same time') } titleSet = true document.title = title ? `${title} - ${getBrandName()}` : getBrandName() diff --git a/client/web/src/components/diff/FileDiffConnection.tsx b/client/web/src/components/diff/FileDiffConnection.tsx index 87d955be8eb..c0b9dcbf5d5 100644 --- a/client/web/src/components/diff/FileDiffConnection.tsx +++ b/client/web/src/components/diff/FileDiffConnection.tsx @@ -7,7 +7,7 @@ import { Omit } from 'utility-types' import { HoverMerged } from '@sourcegraph/client-api' import { Hoverifier } from '@sourcegraph/codeintellify' -import { ErrorLike, isDefined, isErrorLike, property } from '@sourcegraph/common' +import { ErrorLike, isDefined, isErrorLike, logger, property } from '@sourcegraph/common' import { ActionItemAction } from '@sourcegraph/shared/src/actions/ActionItem' import { TextDocumentData, ViewerData, ViewerId } from '@sourcegraph/shared/src/api/viewerTypes' import { Controller as ExtensionsController } from '@sourcegraph/shared/src/extensions/controller' @@ -103,7 +103,7 @@ export const FileDiffConnection: React.FunctionComponent { - console.error('Error removing viewers from extension host', error) + logger.error('Error removing viewers from extension host', error) }) }, [getCurrentViewerIdByUri, extensionInfo?.extensionsController] @@ -234,7 +234,7 @@ export const FileDiffConnection: React.FunctionComponent console.error(error) }) + refreshSiteFlags().subscribe({ error: error => logger.error(error) }) history.push(afterCreateRoute) } }, [afterCreateRoute, createdExternalService, history]) diff --git a/client/web/src/enterprise/batches/settings/AddCredentialModal.tsx b/client/web/src/enterprise/batches/settings/AddCredentialModal.tsx index 94ae5b08d37..d0c71f37220 100644 --- a/client/web/src/enterprise/batches/settings/AddCredentialModal.tsx +++ b/client/web/src/enterprise/batches/settings/AddCredentialModal.tsx @@ -4,6 +4,7 @@ import classNames from 'classnames' import { ErrorAlert } from '@sourcegraph/branded/src/components/alerts' import { Form } from '@sourcegraph/branded/src/components/Form' +import { logger } from '@sourcegraph/common' import { Button, Modal, Link, Code, Label, Text, Input } from '@sourcegraph/wildcard' import { LoaderButton } from '../../../components/LoaderButton' @@ -119,7 +120,7 @@ export const AddCredentialModal: React.FunctionComponent => { map(dataOrThrowErrors), map(data => { if (!data.resetTriggerQueryTimestamps) { - console.log('DATA', data) + logger.log('DATA', data) throw createInvalidGraphQLMutationResponseError('ResetTriggerQueryTimestamps') } }) diff --git a/client/web/src/enterprise/extensions/extension/RegistryExtensionDeleteButton.tsx b/client/web/src/enterprise/extensions/extension/RegistryExtensionDeleteButton.tsx index 2f8cf511c35..16fcebc4623 100644 --- a/client/web/src/enterprise/extensions/extension/RegistryExtensionDeleteButton.tsx +++ b/client/web/src/enterprise/extensions/extension/RegistryExtensionDeleteButton.tsx @@ -5,7 +5,7 @@ import { upperFirst } from 'lodash' import { Subject, Subscription } from 'rxjs' import { catchError, map, mapTo, startWith, switchMap, tap } from 'rxjs/operators' -import { asError, ErrorLike, isErrorLike } from '@sourcegraph/common' +import { asError, ErrorLike, isErrorLike, logger } from '@sourcegraph/common' import * as GQL from '@sourcegraph/shared/src/schema' import { Button, ButtonGroup, Icon } from '@sourcegraph/wildcard' @@ -62,7 +62,7 @@ export class RegistryExtensionDeleteButton extends React.PureComponent< ) .subscribe( stateUpdate => this.setState(stateUpdate), - error => console.error(error) + error => logger.error(error) ) ) } diff --git a/client/web/src/enterprise/extensions/extension/RegistryExtensionManagePage.tsx b/client/web/src/enterprise/extensions/extension/RegistryExtensionManagePage.tsx index cece65c1967..6e3321f03f0 100644 --- a/client/web/src/enterprise/extensions/extension/RegistryExtensionManagePage.tsx +++ b/client/web/src/enterprise/extensions/extension/RegistryExtensionManagePage.tsx @@ -10,7 +10,7 @@ import { catchError, concatMap, map, tap } from 'rxjs/operators' import { ErrorAlert } from '@sourcegraph/branded/src/components/alerts' import { Form } from '@sourcegraph/branded/src/components/Form' -import { asError, createAggregateError, ErrorLike, isErrorLike } from '@sourcegraph/common' +import { asError, createAggregateError, ErrorLike, isErrorLike, logger } from '@sourcegraph/common' import { gql } from '@sourcegraph/http-client' import * as GQL from '@sourcegraph/shared/src/schema' import { Button, LoadingSpinner, Link, CardHeader, CardBody, Card, Alert, Icon, Code, H2 } from '@sourcegraph/wildcard' @@ -113,7 +113,7 @@ export const RegistryExtensionManagePage = withAuthenticatedUser( ) .subscribe( stateUpdate => this.setState(stateUpdate as State), - error => console.error(error) + error => logger.error(error) ) ) diff --git a/client/web/src/enterprise/extensions/registry/RegistryNewExtensionPage.tsx b/client/web/src/enterprise/extensions/registry/RegistryNewExtensionPage.tsx index 6b317163955..df223d6a2ed 100644 --- a/client/web/src/enterprise/extensions/registry/RegistryNewExtensionPage.tsx +++ b/client/web/src/enterprise/extensions/registry/RegistryNewExtensionPage.tsx @@ -10,7 +10,7 @@ import { catchError, concatMap, map, tap } from 'rxjs/operators' import { ErrorAlert } from '@sourcegraph/branded/src/components/alerts' import { Form } from '@sourcegraph/branded/src/components/Form' -import { asError, ErrorLike, isErrorLike } from '@sourcegraph/common' +import { asError, ErrorLike, isErrorLike, logger } from '@sourcegraph/common' import { Scalars } from '@sourcegraph/shared/src/graphql-operations' import * as GQL from '@sourcegraph/shared/src/schema' import { Button, Code, Container, Icon, Label, Link, LoadingSpinner, PageHeader } from '@sourcegraph/wildcard' @@ -68,7 +68,7 @@ export const RegistryNewExtensionPage = withAuthenticatedUser( ) ).subscribe( stateUpdate => this.setState(stateUpdate as State), - error => console.error(error) + error => logger.error(error) ) ) @@ -92,7 +92,7 @@ export const RegistryNewExtensionPage = withAuthenticatedUser( ) .subscribe( stateUpdate => this.setState(stateUpdate as State), - error => console.error(error) + error => logger.error(error) ) ) diff --git a/client/web/src/enterprise/insights/core/backend/gql-backend/methods/get-built-in-insight-data/get-search-insight-content.ts b/client/web/src/enterprise/insights/core/backend/gql-backend/methods/get-built-in-insight-data/get-search-insight-content.ts index 1f8679c76c5..5c759a6224f 100644 --- a/client/web/src/enterprise/insights/core/backend/gql-backend/methods/get-built-in-insight-data/get-search-insight-content.ts +++ b/client/web/src/enterprise/insights/core/backend/gql-backend/methods/get-built-in-insight-data/get-search-insight-content.ts @@ -3,6 +3,8 @@ import escapeRegExp from 'lodash/escapeRegExp' import { defer } from 'rxjs' import { retry } from 'rxjs/operators' +import { logger } from '@sourcegraph/common' + import { InsightContentType } from '../../../../types/insight/common' import { GetSearchInsightContentInput, InsightSeriesContent } from '../../../code-insights-backend-types' @@ -142,7 +144,7 @@ async function determineCommitsToSearch(dates: Date[], repo: string): Promise(CREATE_FEATURE_FLAG_OVERRIDE, { - onError: apolloError => console.error('Error when creating feature flag override', apolloError), + onError: apolloError => logger.error('Error when creating feature flag override', apolloError), }) const [getOrgID, { loading: orgLoading, error: orgError }] = useLazyQuery( diff --git a/client/web/src/enterprise/site-admin/SiteAdminRegistryExtensionsPage.tsx b/client/web/src/enterprise/site-admin/SiteAdminRegistryExtensionsPage.tsx index a61f299559f..4b84da82dac 100644 --- a/client/web/src/enterprise/site-admin/SiteAdminRegistryExtensionsPage.tsx +++ b/client/web/src/enterprise/site-admin/SiteAdminRegistryExtensionsPage.tsx @@ -7,7 +7,7 @@ import { Observable, Subject, Subscription } from 'rxjs' import { catchError, map, mapTo, startWith, switchMap, tap } from 'rxjs/operators' import { ErrorAlert } from '@sourcegraph/branded/src/components/alerts' -import { asError, createAggregateError, ErrorLike, isErrorLike } from '@sourcegraph/common' +import { asError, createAggregateError, ErrorLike, isErrorLike, logger } from '@sourcegraph/common' import { gql } from '@sourcegraph/http-client' import * as GQL from '@sourcegraph/shared/src/schema' import { Button, ButtonLink, Link, Icon, H2, Text } from '@sourcegraph/wildcard' @@ -66,7 +66,7 @@ class RegistryExtensionNodeSiteAdminRow extends React.PureComponent< ) .subscribe( stateUpdate => this.setState(stateUpdate), - error => console.error(error) + error => logger.error(error) ) ) } diff --git a/client/web/src/enterprise/user/settings/ExternalAccountNode.tsx b/client/web/src/enterprise/user/settings/ExternalAccountNode.tsx index 25462f80028..8866eb9813d 100644 --- a/client/web/src/enterprise/user/settings/ExternalAccountNode.tsx +++ b/client/web/src/enterprise/user/settings/ExternalAccountNode.tsx @@ -4,7 +4,7 @@ import { Observable, Subject, Subscription } from 'rxjs' import { catchError, filter, map, mapTo, startWith, switchMap, tap } from 'rxjs/operators' import { ErrorAlert } from '@sourcegraph/branded/src/components/alerts' -import { asError, ErrorLike, isErrorLike } from '@sourcegraph/common' +import { asError, ErrorLike, isErrorLike, logger } from '@sourcegraph/common' import { dataOrThrowErrors, gql } from '@sourcegraph/http-client' import { Badge, Button, Link, AnchorLink } from '@sourcegraph/wildcard' @@ -108,7 +108,7 @@ export class ExternalAccountNode extends React.PureComponent this.setState(stateUpdate), - error => console.error(error) + error => logger.error(error) ) ) } diff --git a/client/web/src/extensions/components/StatusBar.tsx b/client/web/src/extensions/components/StatusBar.tsx index ec34f511e26..df15bc49677 100644 --- a/client/web/src/extensions/components/StatusBar.tsx +++ b/client/web/src/extensions/components/StatusBar.tsx @@ -8,7 +8,7 @@ import { filter, first, mapTo, switchMap } from 'rxjs/operators' import { tabbable } from 'tabbable' import { useMergeRefs } from 'use-callback-ref' -import { isDefined } from '@sourcegraph/common' +import { isDefined, logger } from '@sourcegraph/common' import { urlForClientCommandOpen } from '@sourcegraph/shared/src/actions/ActionItem' import { StatusBarItemWithKey } from '@sourcegraph/shared/src/api/extension/api/codeEditor' import { haveInitialExtensionsLoaded } from '@sourcegraph/shared/src/api/features' @@ -123,7 +123,7 @@ export const StatusBar: React.FunctionComponent console.error('Error registering "Focus status bar" command', error)) + .catch(error => logger.error('Error registering "Focus status bar" command', error)) } return () => subscription.unsubscribe() diff --git a/client/web/src/extensions/extension/ExtensionArea.tsx b/client/web/src/extensions/extension/ExtensionArea.tsx index 0ffe4a749af..042f7759c48 100644 --- a/client/web/src/extensions/extension/ExtensionArea.tsx +++ b/client/web/src/extensions/extension/ExtensionArea.tsx @@ -7,7 +7,7 @@ import { combineLatest, merge, Observable, of, Subject, Subscription } from 'rxj import { catchError, distinctUntilChanged, map, mapTo, startWith, switchMap } from 'rxjs/operators' import { ErrorMessage } from '@sourcegraph/branded/src/components/alerts' -import { createAggregateError, ErrorLike, isErrorLike, asError } from '@sourcegraph/common' +import { createAggregateError, ErrorLike, isErrorLike, asError, logger } from '@sourcegraph/common' import { gql } from '@sourcegraph/http-client' import { ConfiguredRegistryExtension, @@ -176,7 +176,7 @@ export class ExtensionArea extends React.Component { ) .subscribe( stateUpdate => this.setState(stateUpdate), - error => console.error(error) + error => logger.error(error) ) ) diff --git a/client/web/src/featureFlags/FeatureFlagsProvider.tsx b/client/web/src/featureFlags/FeatureFlagsProvider.tsx index d1362a9682d..5b570d90294 100644 --- a/client/web/src/featureFlags/FeatureFlagsProvider.tsx +++ b/client/web/src/featureFlags/FeatureFlagsProvider.tsx @@ -2,6 +2,8 @@ import React, { createContext, useEffect, useMemo } from 'react' import { Observable, of, throwError } from 'rxjs' +import { logger } from '@sourcegraph/common' + import { requestGraphQL } from '../backend/graphql' import { FeatureFlagName } from './featureFlags' @@ -36,13 +38,13 @@ const FeatureFlagsLocalOverrideAgent = React.memo(() => { } else if ([0, 'false'].includes(value)) { setFeatureFlagOverride(flagName, false) } else { - console.warn( + logger.warn( `[FeatureFlagsLocalOverrideAgent]: can not override feature flag "${flagName}" with value "${value}". Only boolean values are supported.` ) } } } catch (error) { - console.error(error) + logger.error(error) } }, []) return null diff --git a/client/web/src/featureFlags/useFeatureFlag.ts b/client/web/src/featureFlags/useFeatureFlag.ts index 4ff48c4e903..c808e26234e 100644 --- a/client/web/src/featureFlags/useFeatureFlag.ts +++ b/client/web/src/featureFlags/useFeatureFlag.ts @@ -1,5 +1,7 @@ import { useContext, useEffect, useState } from 'react' +import { logger } from '@sourcegraph/common' + import { FeatureFlagName } from './featureFlags' import { FeatureFlagsContext } from './FeatureFlagsProvider' @@ -24,7 +26,7 @@ export function useFeatureFlag(flagName: FeatureFlagName, defaultValue = false): if (!client) { const errorMessage = '[useFeatureFlag]: No FeatureFlagClient is configured. All feature flags will default to "false" value.' - console.warn(errorMessage) + logger.warn(errorMessage) setResult(({ value }) => ({ value, status: 'error', error: new Error(errorMessage) })) return } diff --git a/client/web/src/hooks/useScrollManager/useScrollManager.ts b/client/web/src/hooks/useScrollManager/useScrollManager.ts index ad56590b20e..8d97b49fd38 100644 --- a/client/web/src/hooks/useScrollManager/useScrollManager.ts +++ b/client/web/src/hooks/useScrollManager/useScrollManager.ts @@ -3,6 +3,8 @@ import { useEffect } from 'react' import { debounce } from 'lodash' import { useHistory } from 'react-router' +import { logger } from '@sourcegraph/common' + import { MutationObserverError, MutationObserverPromise, @@ -94,7 +96,7 @@ export function useScrollManager(containerKey: string, containerRef: React.RefOb ) .catch((error: MutationObserverError) => { if (!error.cancelled) { - console.error( + logger.error( `Failed to scroll to position '${scrollPosition}' for pathname '${pathname}' in container '${containerKey}'.` ) } diff --git a/client/web/src/notebooks/blocks/compute/NotebookComputeBlock.tsx b/client/web/src/notebooks/blocks/compute/NotebookComputeBlock.tsx index 5c3d472b289..b9c0247ccc1 100644 --- a/client/web/src/notebooks/blocks/compute/NotebookComputeBlock.tsx +++ b/client/web/src/notebooks/blocks/compute/NotebookComputeBlock.tsx @@ -3,6 +3,7 @@ import React from 'react' import { fetchEventSource } from '@microsoft/fetch-event-source' import ElmComponent from 'react-elm-components' +import { logger } from '@sourcegraph/common' import { PlatformContext } from '@sourcegraph/shared/src/platform/context' import { ThemeProps } from '@sourcegraph/shared/src/theme' @@ -55,7 +56,7 @@ const setupPorts = (sourcegraphURL: string, updateBlockInputWithID: (blockInput: } ports.openStream.subscribe((args: string[]) => { - console.log(`stream: ${args[0]}`) + logger.log(`stream: ${args[0]}`) const address = args[0] // Close any open streams if we receive a request to open a new stream before seeing 'done'. @@ -73,7 +74,7 @@ const setupPorts = (sourcegraphURL: string, updateBlockInputWithID: (blockInput: }, signal: ctrl.signal, onerror(error) { - console.log(`Compute EventSource error: ${JSON.stringify(error)}`) + logger.error(`Compute EventSource error: ${JSON.stringify(error)}`) }, onclose() { // Note: 'done:true' is sent in progress too. But we want a 'done' for the entire stream in case we don't see it. @@ -87,7 +88,7 @@ const setupPorts = (sourcegraphURL: string, updateBlockInputWithID: (blockInput: } fetch().catch(error => { - console.log(`Compute fetch error: ${JSON.stringify(error)}`) + logger.error(`Compute fetch error: ${JSON.stringify(error)}`) }) }) diff --git a/client/web/src/open-in-editor/OpenInEditorActionItem.tsx b/client/web/src/open-in-editor/OpenInEditorActionItem.tsx index f78a5f4f9fc..1b72f336464 100644 --- a/client/web/src/open-in-editor/OpenInEditorActionItem.tsx +++ b/client/web/src/open-in-editor/OpenInEditorActionItem.tsx @@ -3,6 +3,7 @@ import { useCallback, useEffect, useMemo, useState } from 'react' import { from } from 'rxjs' +import { logger } from '@sourcegraph/common' import { SimpleActionItem } from '@sourcegraph/shared/src/actions/SimpleActionItem' import { PlatformContext } from '@sourcegraph/shared/src/platform/context' import { isSettingsValid, Settings } from '@sourcegraph/shared/src/settings/settings' @@ -138,10 +139,10 @@ function upgradeSettings(platformContext: PlatformContext, settings: Settings, u value: openInEditor, }) .then(() => { - console.log('Migrated items successfully.') + logger.log('Migrated items successfully.') }) .catch(error => { - console.error('Setting migration failed.', error) + logger.error('Setting migration failed.', error) }) } } diff --git a/client/web/src/org/area/OrgArea.tsx b/client/web/src/org/area/OrgArea.tsx index 3dca0e521a8..c439dbbfc89 100644 --- a/client/web/src/org/area/OrgArea.tsx +++ b/client/web/src/org/area/OrgArea.tsx @@ -7,7 +7,7 @@ import { combineLatest, merge, Observable, of, Subject, Subscription } from 'rxj import { catchError, distinctUntilChanged, map, mapTo, startWith, switchMap } from 'rxjs/operators' import { ErrorMessage } from '@sourcegraph/branded/src/components/alerts' -import { ErrorLike, isErrorLike, asError } from '@sourcegraph/common' +import { ErrorLike, isErrorLike, asError, logger } from '@sourcegraph/common' import { gql, dataOrThrowErrors } from '@sourcegraph/http-client' import { ExtensionsControllerProps } from '@sourcegraph/shared/src/extensions/controller' import { PlatformContextProps } from '@sourcegraph/shared/src/platform/context' @@ -241,7 +241,7 @@ export class OrgArea extends React.Component { this.setState(stateUpdate) } }, - error => console.error(error) + error => logger.error(error) ) ) diff --git a/client/web/src/org/area/OrgInvitationPageLegacy.tsx b/client/web/src/org/area/OrgInvitationPageLegacy.tsx index fea6ca981e4..f93467b4de4 100644 --- a/client/web/src/org/area/OrgInvitationPageLegacy.tsx +++ b/client/web/src/org/area/OrgInvitationPageLegacy.tsx @@ -6,7 +6,7 @@ import { catchError, concatMap, distinctUntilKeyChanged, map, mapTo, tap, withLa import { ErrorAlert } from '@sourcegraph/branded/src/components/alerts' import { Form } from '@sourcegraph/branded/src/components/Form' -import { asError, ErrorLike, isErrorLike } from '@sourcegraph/common' +import { asError, ErrorLike, isErrorLike, logger } from '@sourcegraph/common' import { dataOrThrowErrors, gql } from '@sourcegraph/http-client' import { OrganizationInvitationResponseType } from '@sourcegraph/shared/src/graphql-operations' import { LoadingSpinner, Button, Link, Alert, H3, Text } from '@sourcegraph/wildcard' @@ -90,7 +90,7 @@ export const OrgInvitationPageLegacy = withAuthenticatedUser( ) .subscribe( stateUpdate => this.setState(stateUpdate as State), - error => console.error(error) + error => logger.error(error) ) ) diff --git a/client/web/src/org/invitations/OrgInvitationPage.tsx b/client/web/src/org/invitations/OrgInvitationPage.tsx index 34061c5ea07..eb51a5f76d2 100644 --- a/client/web/src/org/invitations/OrgInvitationPage.tsx +++ b/client/web/src/org/invitations/OrgInvitationPage.tsx @@ -4,6 +4,7 @@ import classNames from 'classnames' import { RouteComponentProps } from 'react-router-dom' import { Form } from '@sourcegraph/branded/src/components/Form' +import { logger } from '@sourcegraph/common' import { gql, useMutation, useQuery } from '@sourcegraph/http-client' import { OrganizationInvitationResponseType } from '@sourcegraph/shared/src/graphql-operations' import { Alert, AnchorLink, Button, LoadingSpinner, Link, H2, H3 } from '@sourcegraph/wildcard' @@ -100,7 +101,7 @@ export const OrgInvitationPage: React.FunctionComponent(RESPOND_TO_ORG_INVITATION, { onError: apolloError => { - console.error('Error when responding to invitation', apolloError) + logger.error('Error when responding to invitation', apolloError) }, }) diff --git a/client/web/src/org/settings/members-v1/OrgSettingsMembersPage.tsx b/client/web/src/org/settings/members-v1/OrgSettingsMembersPage.tsx index 8bb45b34521..3ea2b603339 100644 --- a/client/web/src/org/settings/members-v1/OrgSettingsMembersPage.tsx +++ b/client/web/src/org/settings/members-v1/OrgSettingsMembersPage.tsx @@ -7,7 +7,7 @@ import { Observable, Subject, Subscription } from 'rxjs' import { catchError, distinctUntilChanged, filter, map, startWith, switchMap, tap } from 'rxjs/operators' import { ErrorAlert } from '@sourcegraph/branded/src/components/alerts' -import { asError, createAggregateError, ErrorLike, isErrorLike } from '@sourcegraph/common' +import { asError, createAggregateError, ErrorLike, isErrorLike, logger } from '@sourcegraph/common' import { gql } from '@sourcegraph/http-client' import { Container, PageHeader, Button, Link, Alert } from '@sourcegraph/wildcard' @@ -99,7 +99,7 @@ class UserNode extends React.PureComponent { stateUpdate => { this.setState(stateUpdate) }, - error => console.error(error) + error => logger.error(error) ) ) } diff --git a/client/web/src/platform/context.ts b/client/web/src/platform/context.ts index ec173fbcd5b..785c3d98998 100644 --- a/client/web/src/platform/context.ts +++ b/client/web/src/platform/context.ts @@ -1,7 +1,13 @@ import { ApolloQueryResult, ObservableQuery } from '@apollo/client' import { map, publishReplay, refCount, shareReplay } from 'rxjs/operators' -import { createAggregateError, asError, LocalStorageSubject, appendSubtreeQueryParameter } from '@sourcegraph/common' +import { + createAggregateError, + asError, + LocalStorageSubject, + appendSubtreeQueryParameter, + logger, +} from '@sourcegraph/common' import { fromObservableQueryPromise, getDocumentNode } from '@sourcegraph/http-client' import { viewerSettingsQuery } from '@sourcegraph/shared/src/backend/settings' import { ViewerSettingsResult, ViewerSettingsVariables } from '@sourcegraph/shared/src/graphql-operations' @@ -67,7 +73,7 @@ export function createPlatformContext(): PlatformContext { } // The error will be emitted to consumers from the `context.settings` observable. - await settingsQueryWatcher.refetch().catch(error => console.error(error)) + await settingsQueryWatcher.refetch().catch(error => logger.error(error)) }, getGraphQLClient: getWebGraphQLClient, requestGraphQL: ({ request, variables }) => requestGraphQL(request, variables), diff --git a/client/web/src/regression/core.test.ts b/client/web/src/regression/core.test.ts index f1b2e73c9f5..536f6c08baa 100644 --- a/client/web/src/regression/core.test.ts +++ b/client/web/src/regression/core.test.ts @@ -3,6 +3,7 @@ import expect from 'expect' import { describe, before, beforeEach, after, afterEach, test } from 'mocha' import { map } from 'rxjs/operators' +import { logger } from '@sourcegraph/common' import { gql, dataOrThrowErrors } from '@sourcegraph/http-client' // import { overwriteSettings } from '@sourcegraph/shared/src/settings/edit' import { getConfig } from '@sourcegraph/shared/src/testing/config' @@ -67,7 +68,7 @@ describe('Core functionality regression test suite', () => { await driver.close() } if (screenshots.screenshots.length > 0) { - console.log(screenshots.verificationInstructions()) + logger.log(screenshots.verificationInstructions()) } }) diff --git a/client/web/src/regression/util/TestResourceManager.ts b/client/web/src/regression/util/TestResourceManager.ts index f1229b2def8..d99f41e77d2 100644 --- a/client/web/src/regression/util/TestResourceManager.ts +++ b/client/web/src/regression/util/TestResourceManager.ts @@ -1,4 +1,4 @@ -import { asError } from '@sourcegraph/common' +import { asError, logger } from '@sourcegraph/common' export type ResourceDestructor = () => Promise @@ -63,14 +63,14 @@ export class TestResourceManager { try { await resource.destroy() } catch (error) { - console.error( + logger.error( `Error when destroying resource ${resource.type} ${JSON.stringify(resource.name)}: ${ asError(error).message }` ) continue } - console.log(`Test resource destroyed: ${resource.type} ${JSON.stringify(resource.name)}`) + logger.log(`Test resource destroyed: ${resource.type} ${JSON.stringify(resource.name)}`) } } } diff --git a/client/web/src/regression/util/api.ts b/client/web/src/regression/util/api.ts index 7ede1e42fd4..34aff80fc8e 100644 --- a/client/web/src/regression/util/api.ts +++ b/client/web/src/regression/util/api.ts @@ -5,7 +5,7 @@ import { zip, timer, concat, throwError, defer, Observable } from 'rxjs' import { map, tap, retryWhen, delayWhen, take, mergeMap } from 'rxjs/operators' -import { isErrorLike, createAggregateError } from '@sourcegraph/common' +import { isErrorLike, createAggregateError, logger } from '@sourcegraph/common' import { gql, dataOrThrowErrors, @@ -109,7 +109,7 @@ export function waitForRepo( if (isErrorLike(error) && error.message === 'Repo exists') { // Delay retry by 2s. if (logStatusMessages) { - console.log( + logger.log( `Waiting for ${repoName} to be removed (attempt ${ retryCount + 1 } of ${numberRetries})` @@ -147,7 +147,7 @@ export function waitForRepo( if (isCloneInProgressErrorLike(error)) { // Delay retry by 2s. if (logStatusMessages) { - console.log( + logger.log( `Waiting for ${repoName} to finish cloning (attempt ${ retryCount + 1 } of ${numberRetries})` @@ -267,7 +267,7 @@ export async function updateExternalService( map(dataOrThrowErrors), tap(({ updateExternalService: { warning } }) => { if (warning) { - console.warn('updateExternalService warning:', warning) + logger.warn('updateExternalService warning:', warning) } }) ) diff --git a/client/web/src/regression/util/helpers.ts b/client/web/src/regression/util/helpers.ts index 96a206169fc..80638f9f3b8 100644 --- a/client/web/src/regression/util/helpers.ts +++ b/client/web/src/regression/util/helpers.ts @@ -4,7 +4,7 @@ import { throwError } from 'rxjs' import { catchError, map } from 'rxjs/operators' import { Key } from 'ts-key-enum' -import { asError } from '@sourcegraph/common' +import { asError, logger } from '@sourcegraph/common' import { gql, dataOrThrowErrors } from '@sourcegraph/http-client' import { PlatformContext } from '@sourcegraph/shared/src/platform/context' import * as GQL from '@sourcegraph/shared/src/schema' @@ -63,7 +63,7 @@ export async function ensureLoggedInOrCreateTestUser( await driver.ensureLoggedIn({ username, password: testUserPassword }) return userDestructor } catch (error) { - console.log( + logger.error( `Login failed (error: ${asError(error).message}), will attempt to create user ${JSON.stringify( username )}` diff --git a/client/web/src/repo/RepoContainer.tsx b/client/web/src/repo/RepoContainer.tsx index 90aeaa2d610..7a4332f2925 100644 --- a/client/web/src/repo/RepoContainer.tsx +++ b/client/web/src/repo/RepoContainer.tsx @@ -9,7 +9,7 @@ import { matchPath, Route, RouteComponentProps, Switch } from 'react-router' import { NEVER, of } from 'rxjs' import { catchError, switchMap } from 'rxjs/operators' -import { asError, ErrorLike, isErrorLike, encodeURIPathComponent, repeatUntil } from '@sourcegraph/common' +import { asError, ErrorLike, isErrorLike, encodeURIPathComponent, repeatUntil, logger } from '@sourcegraph/common' import { SearchContextProps } from '@sourcegraph/search' import { StreamingSearchResultsListProps } from '@sourcegraph/search-ui' import { isCloneInProgressErrorLike, isRepoSeeOtherErrorLike } from '@sourcegraph/shared/src/backend/errors' @@ -247,7 +247,7 @@ export const RepoContainer: React.FunctionComponent { - console.error('Error adding workspace root', error) + logger.error('Error adding workspace root', error) }) } @@ -257,7 +257,7 @@ export const RepoContainer: React.FunctionComponent extensionHostAPI.removeWorkspaceRoot(workspaceRootUri)) .catch(error => { - console.error('Error removing workspace root', error) + logger.error('Error removing workspace root', error) }) } } diff --git a/client/web/src/repo/RepositoryNotFoundPage.tsx b/client/web/src/repo/RepositoryNotFoundPage.tsx index 8a4e31c15d7..b4d48239c5d 100644 --- a/client/web/src/repo/RepositoryNotFoundPage.tsx +++ b/client/web/src/repo/RepositoryNotFoundPage.tsx @@ -5,7 +5,7 @@ import MapSearchIcon from 'mdi-react/MapSearchIcon' import { merge, of, Subject, Subscription } from 'rxjs' import { catchError, distinctUntilChanged, map, switchMap } from 'rxjs/operators' -import { asError, ErrorLike, isErrorLike } from '@sourcegraph/common' +import { asError, ErrorLike, isErrorLike, logger } from '@sourcegraph/common' import { Link, Text } from '@sourcegraph/wildcard' import { HeroPage } from '../components/HeroPage' @@ -73,7 +73,7 @@ export class RepositoryNotFoundPage extends React.PureComponent { ) .subscribe( stateUpdate => this.setState(stateUpdate), - error => console.error(error) + error => logger.error(error) ) ) diff --git a/client/web/src/repo/blob/Blob.tsx b/client/web/src/repo/blob/Blob.tsx index f0b4a7bf865..4bb083c2fc6 100644 --- a/client/web/src/repo/blob/Blob.tsx +++ b/client/web/src/repo/blob/Blob.tsx @@ -53,6 +53,7 @@ import { toPositionOrRangeQueryParameter, addLineRangeQueryParameter, formatSearchParameters, + logger, } from '@sourcegraph/common' import { TextDocumentDecoration } from '@sourcegraph/extension-api-types' import { ActionItemAction } from '@sourcegraph/shared/src/actions/ActionItem' @@ -550,7 +551,7 @@ export const Blob: React.FunctionComponent> = subscriptions.add(() => { extensionHostAPI .removeViewer(viewerId) - .catch(error => console.error('Error removing viewer from extension host', error)) + .catch(error => logger.error('Error removing viewer from extension host', error)) }) viewerUpdates.next({ viewerId, blobInfo, extensionHostAPI, subscriptions }) @@ -626,7 +627,7 @@ export const Blob: React.FunctionComponent> = viewerData.extensionHostAPI .setEditorSelections(viewerData.viewerId, lprToSelectionsZeroIndexed(position)) .catch(error => - console.error('Error updating editor selections on extension host', error) + logger.error('Error updating editor selections on extension host', error) ) }) ) diff --git a/client/web/src/repo/blob/codemirror/highlight.ts b/client/web/src/repo/blob/codemirror/highlight.ts index 8c03694408a..d27f0892170 100644 --- a/client/web/src/repo/blob/codemirror/highlight.ts +++ b/client/web/src/repo/blob/codemirror/highlight.ts @@ -1,6 +1,7 @@ import { Facet, RangeSetBuilder } from '@codemirror/state' import { Decoration, DecorationSet, EditorView, PluginValue, ViewPlugin, ViewUpdate } from '@codemirror/view' +import { logger } from '@sourcegraph/common' import { Occurrence, SyntaxKind } from '@sourcegraph/shared/src/codeintel/scip' import { BlobInfo } from '../Blob' @@ -51,7 +52,7 @@ function createHighlightTable(info: BlobInfo): HighlightIndex { return { occurrences, lineIndex } } catch (error) { - console.error(`Unable to process SCIP highlight data: ${info.lsif}`, error) + logger.error(`Unable to process SCIP highlight data: ${info.lsif}`, error) return { occurrences: [], lineIndex } } } @@ -136,7 +137,7 @@ class SyntaxHighlightManager implements PluginValue { } } } catch (error) { - console.error('Failed to compute decorations from SCIP occurrences', error) + logger.error('Failed to compute decorations from SCIP occurrences', error) } return builder.finish() } diff --git a/client/web/src/repo/blob/codemirror/sourcegraph-extensions.ts b/client/web/src/repo/blob/codemirror/sourcegraph-extensions.ts index 42d321e4e64..3e13c71e895 100644 --- a/client/web/src/repo/blob/codemirror/sourcegraph-extensions.ts +++ b/client/web/src/repo/blob/codemirror/sourcegraph-extensions.ts @@ -15,7 +15,7 @@ import { combineLatest, EMPTY, from, Observable, of, Subject, Subscription } fro import { filter, map, catchError, switchMap, distinctUntilChanged, startWith, shareReplay } from 'rxjs/operators' import { DocumentHighlight, LOADER_DELAY, MaybeLoadingResult, emitLoading } from '@sourcegraph/codeintellify' -import { asError, ErrorLike, LineOrPositionOrRange, lprToSelectionsZeroIndexed } from '@sourcegraph/common' +import { asError, ErrorLike, LineOrPositionOrRange, lprToSelectionsZeroIndexed, logger } from '@sourcegraph/common' import { Position, TextDocumentDecoration } from '@sourcegraph/extension-api-types' import { wrapRemoteObservable } from '@sourcegraph/shared/src/api/client/api/common' import { FlatExtensionHostAPI } from '@sourcegraph/shared/src/api/contract' @@ -103,14 +103,14 @@ export function sourcegraphExtensions({ }) ).pipe( catchError(() => { - console.error('Unable to initialize extensions context') + logger.error('Unable to initialize extensions context') return EMPTY }), map(([viewerId, extensionHostAPI]) => { subscriptions.add(() => { extensionHostAPI .removeViewer(viewerId) - .catch(error => console.error('Error removing viewer from extension host', error)) + .catch(error => logger.error('Error removing viewer from extension host', error)) }) return { @@ -232,7 +232,7 @@ class SelectionManager implements PluginValue { this.subscription = combineLatest([context, this.nextSelection]).subscribe(([context, selection]) => { context.extensionHostAPI .setEditorSelections(context.viewerId, lprToSelectionsZeroIndexed(selection ?? {})) - .catch(error => console.error('Error updating editor selections on extension host', error)) + .catch(error => logger.error('Error updating editor selections on extension host', error)) }) } diff --git a/client/web/src/repo/branches/RepositoryBranchesOverviewPage.tsx b/client/web/src/repo/branches/RepositoryBranchesOverviewPage.tsx index 6258f22eae9..0dce99226d9 100644 --- a/client/web/src/repo/branches/RepositoryBranchesOverviewPage.tsx +++ b/client/web/src/repo/branches/RepositoryBranchesOverviewPage.tsx @@ -6,7 +6,7 @@ import { Observable, Subject, Subscription } from 'rxjs' import { catchError, distinctUntilChanged, map, startWith, switchMap } from 'rxjs/operators' import { ErrorAlert } from '@sourcegraph/branded/src/components/alerts' -import { asError, createAggregateError, ErrorLike, isErrorLike, memoizeObservable } from '@sourcegraph/common' +import { asError, createAggregateError, ErrorLike, isErrorLike, logger, memoizeObservable } from '@sourcegraph/common' import { gql } from '@sourcegraph/http-client' import { Scalars } from '@sourcegraph/shared/src/graphql-operations' import * as GQL from '@sourcegraph/shared/src/schema' @@ -105,7 +105,7 @@ export class RepositoryBranchesOverviewPage extends React.PureComponent this.setState(stateUpdate), - error => console.error(error) + error => logger.error(error) ) ) this.componentUpdates.next(this.props) diff --git a/client/web/src/repo/commit/RepositoryCommitPage.tsx b/client/web/src/repo/commit/RepositoryCommitPage.tsx index 1380033d07b..7a63e26c0df 100644 --- a/client/web/src/repo/commit/RepositoryCommitPage.tsx +++ b/client/web/src/repo/commit/RepositoryCommitPage.tsx @@ -17,6 +17,7 @@ import { isDefined, memoizeObservable, property, + logger, } from '@sourcegraph/common' import { gql } from '@sourcegraph/http-client' import { ActionItemAction } from '@sourcegraph/shared/src/actions/ActionItem' @@ -238,7 +239,7 @@ export class RepositoryCommitPage extends React.Component this.setState(stateUpdate), - error => console.error(error) + error => logger.error(error) ) ) this.componentUpdates.next(this.props) diff --git a/client/web/src/repo/compare/RepositoryCompareOverviewPage.tsx b/client/web/src/repo/compare/RepositoryCompareOverviewPage.tsx index 1303ab35df9..ef49ba34049 100644 --- a/client/web/src/repo/compare/RepositoryCompareOverviewPage.tsx +++ b/client/web/src/repo/compare/RepositoryCompareOverviewPage.tsx @@ -7,7 +7,7 @@ import { catchError, distinctUntilChanged, map, switchMap } from 'rxjs/operators import { ErrorAlert } from '@sourcegraph/branded/src/components/alerts' import { HoverMerged } from '@sourcegraph/client-api' import { Hoverifier } from '@sourcegraph/codeintellify' -import { asError, createAggregateError, ErrorLike, isErrorLike } from '@sourcegraph/common' +import { asError, createAggregateError, ErrorLike, isErrorLike, logger } from '@sourcegraph/common' import { gql } from '@sourcegraph/http-client' import { ActionItemAction } from '@sourcegraph/shared/src/actions/ActionItem' import { ExtensionsControllerProps } from '@sourcegraph/shared/src/extensions/controller' @@ -140,7 +140,7 @@ export class RepositoryCompareOverviewPage extends React.PureComponent this.setState(stateUpdate), - error => console.error(error) + error => logger.error(error) ) ) this.componentUpdates.next(this.props) diff --git a/client/web/src/repo/tree/TreePage.tsx b/client/web/src/repo/tree/TreePage.tsx index 732c5200353..1447a283341 100644 --- a/client/web/src/repo/tree/TreePage.tsx +++ b/client/web/src/repo/tree/TreePage.tsx @@ -7,7 +7,7 @@ import { Redirect, Route, Switch, useRouteMatch } from 'react-router-dom' import { catchError } from 'rxjs/operators' import { ErrorAlert } from '@sourcegraph/branded/src/components/alerts' -import { asError, encodeURIPathComponent, ErrorLike, isErrorLike } from '@sourcegraph/common' +import { asError, encodeURIPathComponent, ErrorLike, isErrorLike, logger } from '@sourcegraph/common' import { gql } from '@sourcegraph/http-client' import { SearchContextProps } from '@sourcegraph/search' import { fetchTreeEntries } from '@sourcegraph/shared/src/backend/repo' @@ -176,7 +176,7 @@ export const TreePage: React.FunctionComponent> = }) ) .catch(error => { - console.error('Error adding viewer to extension host:', error) + logger.error('Error adding viewer to extension host:', error) return null }) @@ -188,7 +188,7 @@ export const TreePage: React.FunctionComponent> = } return }) - .catch(error => console.error('Error removing viewer from extension host:', error)) + .catch(error => logger.error('Error removing viewer from extension host:', error)) } }, [uri, showCodeInsights, extensionsController]) diff --git a/client/web/src/savedSearches/SavedSearchListPage.tsx b/client/web/src/savedSearches/SavedSearchListPage.tsx index e60236f2f1d..c9374b1f2a8 100644 --- a/client/web/src/savedSearches/SavedSearchListPage.tsx +++ b/client/web/src/savedSearches/SavedSearchListPage.tsx @@ -9,7 +9,7 @@ import { catchError, map, mapTo, startWith, switchMap } from 'rxjs/operators' import { useCallbackRef } from 'use-callback-ref' import { ErrorAlert } from '@sourcegraph/branded/src/components/alerts' -import { asError, ErrorLike, isErrorLike } from '@sourcegraph/common' +import { asError, ErrorLike, isErrorLike, logger } from '@sourcegraph/common' import { SearchPatternTypeProps } from '@sourcegraph/search' import * as GQL from '@sourcegraph/shared/src/schema' import { buildSearchURLQuery } from '@sourcegraph/shared/src/util/url' @@ -50,7 +50,7 @@ class SavedSearchNode extends React.PureComponent { deleteSavedSearch(search.id).pipe( mapTo(undefined), catchError(error => { - console.error(error) + logger.error(error) return [] }) ) diff --git a/client/web/src/search/home/DynamicWebFonts/useDynamicWebFonts.ts b/client/web/src/search/home/DynamicWebFonts/useDynamicWebFonts.ts index 33ae693b5ed..a3bf7a85d19 100644 --- a/client/web/src/search/home/DynamicWebFonts/useDynamicWebFonts.ts +++ b/client/web/src/search/home/DynamicWebFonts/useDynamicWebFonts.ts @@ -1,5 +1,7 @@ import { useEffect, useState } from 'react' +import { logger } from '@sourcegraph/common' + /** * Add `document.fonts` to Typescript type definitions based on the issue: * https://github.com/Microsoft/TypeScript/issues/30984#issuecomment-631991019 @@ -56,7 +58,7 @@ export function useDynamicWebFonts(fonts: DynamicWebFont[]): boolean { // If fonts are available, skip redundant network request and proceed to UI rendering. if (!areFontsLoaded) { loadFonts().catch(error => { - console.error(error) + logger.error(error) setHasNetworkError(true) }) } diff --git a/client/web/src/search/results/components/compute/public/js/ports.js b/client/web/src/search/results/components/compute/public/js/ports.js index 02fe550334e..0b5db986b64 100644 --- a/client/web/src/search/results/components/compute/public/js/ports.js +++ b/client/web/src/search/results/components/compute/public/js/ports.js @@ -1,6 +1,8 @@ /* eslint-disable unicorn/no-abusive-eslint-disable */ /* eslint-disable */ +const { logger } = require('@sourcegraph/common') + function initElmPorts(app) { // Compute streaming var sources = {} @@ -31,18 +33,18 @@ function initElmPorts(app) { app.ports.openStream.subscribe(function (args) { deleteAllEventSources() // Pre-emptively close any open streams if we receive a request to open a new stream before seeing 'done'. - console.log(`stream: ${args[0]}`) + logger.log(`stream: ${args[0]}`) var address = args[0] var eventSource = newEventSource(address) eventSource.onerror = function (err) { - console.log(`EventSource failed: ${JSON.stringify(err)}`) + logger.log(`EventSource failed: ${JSON.stringify(err)}`) } eventSource.addEventListener('results', sendEventToElm) eventSource.addEventListener('alert', sendEventToElm) eventSource.addEventListener('error', sendEventToElm) eventSource.addEventListener('done', function (event) { - console.log('Done') + logger.log('Done') deleteEventSource(address) // Note: 'done:true' is sent in progress too. But we want a 'done' for the entire stream in case we don't see it. sendEventToElm({ type: 'done', data: '' }) diff --git a/client/web/src/settings/DynamicallyImportedMonacoSettingsEditor.tsx b/client/web/src/settings/DynamicallyImportedMonacoSettingsEditor.tsx index e5b2b882268..7888c2a07f2 100644 --- a/client/web/src/settings/DynamicallyImportedMonacoSettingsEditor.tsx +++ b/client/web/src/settings/DynamicallyImportedMonacoSettingsEditor.tsx @@ -4,6 +4,7 @@ import * as H from 'history' import * as _monaco from 'monaco-editor' // type only import { Subscription } from 'rxjs' +import { logger } from '@sourcegraph/common' import { TelemetryProps } from '@sourcegraph/shared/src/telemetry/telemetryService' import { ThemeProps } from '@sourcegraph/shared/src/theme' import { LoadingSpinner } from '@sourcegraph/wildcard' @@ -225,7 +226,7 @@ export class DynamicallyImportedMonacoSettingsEditor exte const action = this.configEditor.getAction(id) action.run().then( () => undefined, - error => console.error(error) + error => logger.error(error) ) } else { alert('Wait for editor to load before running action.') diff --git a/client/web/src/settings/SettingsArea.tsx b/client/web/src/settings/SettingsArea.tsx index 08b5454088b..3fbcdc3c258 100644 --- a/client/web/src/settings/SettingsArea.tsx +++ b/client/web/src/settings/SettingsArea.tsx @@ -8,7 +8,7 @@ import { combineLatest, from, Observable, of, Subject, Subscription } from 'rxjs import { catchError, distinctUntilChanged, map, startWith, switchMap } from 'rxjs/operators' import { ErrorMessage } from '@sourcegraph/branded/src/components/alerts' -import { asError, createAggregateError, ErrorLike, isErrorLike, isDefined } from '@sourcegraph/common' +import { asError, createAggregateError, ErrorLike, isErrorLike, isDefined, logger } from '@sourcegraph/common' import { gql } from '@sourcegraph/http-client' import { getConfiguredSideloadedExtension } from '@sourcegraph/shared/src/api/client/enabledExtensions' import { extensionIDsFromSettings } from '@sourcegraph/shared/src/extensions/extension' @@ -108,7 +108,7 @@ export class SettingsArea extends React.Component { ) .subscribe( stateUpdate => this.setState(stateUpdate), - error => console.error(error) + error => logger.error(error) ) ) @@ -193,14 +193,14 @@ export class SettingsArea extends React.Component { extensionIDsFromSettings(gqlToCascade(cascade)) ).pipe( catchError(error => { - console.warn('Unable to get extension settings JSON Schemas for settings editor.', { error }) + logger.warn('Unable to get extension settings JSON Schemas for settings editor.', { error }) return of([]) }) ), from(this.props.platformContext.sideloadedExtensionURL).pipe( switchMap(url => (url ? getConfiguredSideloadedExtension(url) : of(null))), catchError(error => { - console.error('Error sideloading extension', error) + logger.error('Error sideloading extension', error) return of(null) }) ), diff --git a/client/web/src/settings/SettingsPage.tsx b/client/web/src/settings/SettingsPage.tsx index 486a7b6fe04..557aa524b2e 100644 --- a/client/web/src/settings/SettingsPage.tsx +++ b/client/web/src/settings/SettingsPage.tsx @@ -2,6 +2,7 @@ import * as React from 'react' import { RouteComponentProps } from 'react-router' +import { logger } from '@sourcegraph/common' import { overwriteSettings } from '@sourcegraph/shared/src/settings/edit' import { TelemetryProps } from '@sourcegraph/shared/src/telemetry/telemetryService' import { ThemeProps } from '@sourcegraph/shared/src/theme' @@ -70,7 +71,7 @@ export class SettingsPage extends React.PureComponent { this.props.onUpdate() } catch (commitError) { this.setState({ commitError }) - console.error(commitError) + logger.error(commitError) } } diff --git a/client/web/src/site-admin/SiteAdminAllUsersPage/UserManagement/components/UsersList.tsx b/client/web/src/site-admin/SiteAdminAllUsersPage/UserManagement/components/UsersList.tsx index b980cf701c9..100d16ec1a5 100644 --- a/client/web/src/site-admin/SiteAdminAllUsersPage/UserManagement/components/UsersList.tsx +++ b/client/web/src/site-admin/SiteAdminAllUsersPage/UserManagement/components/UsersList.tsx @@ -14,6 +14,7 @@ import classNames from 'classnames' import { formatDistanceToNowStrict, startOfDay, endOfDay } from 'date-fns' import { ErrorAlert } from '@sourcegraph/branded/src/components/alerts' +import { logger } from '@sourcegraph/common' import { useQuery } from '@sourcegraph/http-client' import { H2, @@ -153,7 +154,7 @@ export const UsersList: React.FunctionComponent = ({ onActionEnd (error?: any) => { if (!error) { // reload data - refetch(variables).catch(console.error) + refetch(variables).catch(logger.error) onActionEnd?.() } }, diff --git a/client/web/src/site-admin/SiteAdminAllUsersPage/UserManagement/components/useUserListActions.tsx b/client/web/src/site-admin/SiteAdminAllUsersPage/UserManagement/components/useUserListActions.tsx index 26404230cc7..41ab7c59293 100644 --- a/client/web/src/site-admin/SiteAdminAllUsersPage/UserManagement/components/useUserListActions.tsx +++ b/client/web/src/site-admin/SiteAdminAllUsersPage/UserManagement/components/useUserListActions.tsx @@ -1,5 +1,6 @@ import React, { useState, useCallback } from 'react' +import { logger } from '@sourcegraph/common' import { useMutation } from '@sourcegraph/http-client' import { Text } from '@sourcegraph/wildcard' @@ -31,7 +32,7 @@ export function useUserListActions(onEnd: (error?: any) => void): UseUserListAct ), isError: true, }) - console.error(error) + logger.error(error) onEnd(error) }, [onEnd] diff --git a/client/web/src/site-admin/SiteAdminAllUsersPage/index.tsx b/client/web/src/site-admin/SiteAdminAllUsersPage/index.tsx index 8ef1056f81a..cc68dbc81aa 100644 --- a/client/web/src/site-admin/SiteAdminAllUsersPage/index.tsx +++ b/client/web/src/site-admin/SiteAdminAllUsersPage/index.tsx @@ -8,7 +8,7 @@ import { merge, of, Subject, Subscription } from 'rxjs' import { catchError, distinctUntilChanged, map, switchMap } from 'rxjs/operators' import { ErrorAlert } from '@sourcegraph/branded/src/components/alerts' -import { asError } from '@sourcegraph/common' +import { asError, logger } from '@sourcegraph/common' import * as GQL from '@sourcegraph/shared/src/schema' import { Button, Link, Alert, Icon, H2, Text, Tooltip } from '@sourcegraph/wildcard' @@ -98,7 +98,7 @@ class UserNode extends React.PureComponent { this.props.onDidUpdate() } }, - error => console.error(error) + error => logger.error(error) ) ) } diff --git a/client/web/src/site-admin/SiteAdminConfigurationPage.tsx b/client/web/src/site-admin/SiteAdminConfigurationPage.tsx index ccd60ab93f3..40deebea126 100644 --- a/client/web/src/site-admin/SiteAdminConfigurationPage.tsx +++ b/client/web/src/site-admin/SiteAdminConfigurationPage.tsx @@ -8,6 +8,7 @@ import { Subject, Subscription } from 'rxjs' import { delay, mergeMap, retryWhen, tap, timeout } from 'rxjs/operators' import { ErrorAlert } from '@sourcegraph/branded/src/components/alerts' +import { logger } from '@sourcegraph/common' import * as GQL from '@sourcegraph/shared/src/schema' import { SiteConfiguration } from '@sourcegraph/shared/src/schema/site.schema' import { TelemetryProps } from '@sourcegraph/shared/src/telemetry/telemetryService' @@ -433,7 +434,7 @@ export class SiteAdminConfigurationPage extends React.Component { try { restartToApply = await updateSiteConfiguration(lastConfigurationID, newContents).toPromise() } catch (error) { - console.error(error) + logger.error(error) this.setState({ saving: false, error }) } @@ -457,7 +458,7 @@ export class SiteAdminConfigurationPage extends React.Component { try { await refreshSiteFlags().toPromise() } catch (error) { - console.error(error) + logger.error(error) } } this.setState({ restartToApply }) diff --git a/client/web/src/site-admin/SiteAdminCreateUserPage.tsx b/client/web/src/site-admin/SiteAdminCreateUserPage.tsx index 2f37ce12428..fc6c0da1c9c 100644 --- a/client/web/src/site-admin/SiteAdminCreateUserPage.tsx +++ b/client/web/src/site-admin/SiteAdminCreateUserPage.tsx @@ -7,7 +7,7 @@ import { catchError, mergeMap, tap } from 'rxjs/operators' import { ErrorAlert } from '@sourcegraph/branded/src/components/alerts' import { Form } from '@sourcegraph/branded/src/components/Form' -import { asError } from '@sourcegraph/common' +import { asError, logger } from '@sourcegraph/common' import * as GQL from '@sourcegraph/shared/src/schema' import { Button, Link, Alert, Label, H2, Text } from '@sourcegraph/wildcard' @@ -63,7 +63,7 @@ export class SiteAdminCreateUserPage extends React.Component createUser(username, email).pipe( catchError(error => { - console.error(error) + logger.error(error) this.setState({ createUserResult: undefined, loading: false, @@ -81,7 +81,7 @@ export class SiteAdminCreateUserPage extends React.Component console.error(error) + error => logger.error(error) ) ) } diff --git a/client/web/src/site-admin/SiteAdminRepositoriesPage.tsx b/client/web/src/site-admin/SiteAdminRepositoriesPage.tsx index b805681b73b..ff87ff18aa8 100644 --- a/client/web/src/site-admin/SiteAdminRepositoriesPage.tsx +++ b/client/web/src/site-admin/SiteAdminRepositoriesPage.tsx @@ -5,6 +5,7 @@ import { RouteComponentProps } from 'react-router' import { Observable } from 'rxjs' import { ErrorAlert } from '@sourcegraph/branded/src/components/alerts' +import { logger } from '@sourcegraph/common' import { useQuery } from '@sourcegraph/http-client' import { RepoLink } from '@sourcegraph/shared/src/components/RepoLink' import { TelemetryProps } from '@sourcegraph/shared/src/telemetry/telemetryService' @@ -149,11 +150,11 @@ export const SiteAdminRepositoriesPage: React.FunctionComponent { refreshSiteFlags() .toPromise() - .then(null, error => console.error(error)) + .then(null, error => logger.error(error)) return () => { refreshSiteFlags() .toPromise() - .then(null, error => console.error(error)) + .then(null, error => logger.error(error)) } }, []) diff --git a/client/web/src/site-admin/init/SiteInitPage.tsx b/client/web/src/site-admin/init/SiteInitPage.tsx index 2571c9cc5ca..2dff1ae8070 100644 --- a/client/web/src/site-admin/init/SiteInitPage.tsx +++ b/client/web/src/site-admin/init/SiteInitPage.tsx @@ -2,6 +2,7 @@ import React from 'react' import { Redirect } from 'react-router' +import { logger } from '@sourcegraph/common' import { ThemeProps } from '@sourcegraph/shared/src/theme' import { CardBody, Card, H2, Text } from '@sourcegraph/wildcard' @@ -24,7 +25,7 @@ const initSite = async (args: SignUpArguments): Promise => { }) .then() // no op .catch((error): void => { - console.error(error) + logger.error(error) }) const response = await fetch('/-/site-init', { credentials: 'same-origin', diff --git a/client/web/src/site/backend.ts b/client/web/src/site/backend.ts index b1afe116440..b2aa3cc3ac8 100644 --- a/client/web/src/site/backend.ts +++ b/client/web/src/site/backend.ts @@ -1,7 +1,7 @@ import { Observable, ReplaySubject } from 'rxjs' import { filter, mergeMap, take, tap } from 'rxjs/operators' -import { createAggregateError } from '@sourcegraph/common' +import { createAggregateError, logger } from '@sourcegraph/common' import { gql } from '@sourcegraph/http-client' import { authRequired } from '../auth' @@ -67,5 +67,5 @@ refreshSiteFlags() .toPromise() .then( () => undefined, - error => console.error(error) + error => logger.error(error) ) diff --git a/client/web/src/tracking/eventLogger.ts b/client/web/src/tracking/eventLogger.ts index 07b82b36231..c297fcfc73f 100644 --- a/client/web/src/tracking/eventLogger.ts +++ b/client/web/src/tracking/eventLogger.ts @@ -3,7 +3,7 @@ import { EMPTY, fromEvent, merge, Observable } from 'rxjs' import { catchError, map, publishReplay, refCount, take } from 'rxjs/operators' import * as uuid from 'uuid' -import { isErrorLike, isFirefox } from '@sourcegraph/common' +import { isErrorLike, isFirefox, logger } from '@sourcegraph/common' import { SharedEventLogger } from '@sourcegraph/shared/src/api/sharedEventLogger' import { TelemetryService } from '@sourcegraph/shared/src/telemetry/telemetryService' import { UTMMarker } from '@sourcegraph/shared/src/tracking/utm' @@ -99,7 +99,7 @@ export class EventLogger implements TelemetryService, SharedEventLogger { this.log('BrowserExtensionConnectedToServer', args, args) if (localStorage && localStorage.getItem('eventLogDebug') === 'true') { - console.debug('%cBrowser extension detected, sync completed', 'color: #aaa') + logger.debug('%cBrowser extension detected, sync completed', 'color: #aaa') } }) @@ -169,7 +169,7 @@ export class EventLogger implements TelemetryService, SharedEventLogger { private logToConsole(eventLabel: string, eventProperties?: any, publicArgument?: any): void { if (localStorage && localStorage.getItem('eventLogDebug') === 'true') { - console.debug('%cEVENT %s', 'color: #aaa', eventLabel, eventProperties, publicArgument) + logger.debug('%cEVENT %s', 'color: #aaa', eventLabel, eventProperties, publicArgument) } } diff --git a/client/web/src/tree/TreeLayer.tsx b/client/web/src/tree/TreeLayer.tsx index 336702f9e6c..3be6fd54c13 100644 --- a/client/web/src/tree/TreeLayer.tsx +++ b/client/web/src/tree/TreeLayer.tsx @@ -15,7 +15,7 @@ import { } from 'rxjs/operators' import { FileDecoration } from 'sourcegraph' -import { asError, ErrorLike, isErrorLike } from '@sourcegraph/common' +import { asError, ErrorLike, isErrorLike, logger } from '@sourcegraph/common' import { FileDecorationsByPath } from '@sourcegraph/shared/src/api/extension/extensionHostApi' import { fetchTreeEntries } from '@sourcegraph/shared/src/backend/repo' import { Scalars, TreeFields } from '@sourcegraph/shared/src/graphql-operations' @@ -104,7 +104,7 @@ export class TreeLayer extends React.Component { // clear file decorations before latest file decorations come this.setState({ treeOrError, fileDecorationsByPath: {} }) }, - error => console.error(error) + error => logger.error(error) ) ) diff --git a/client/web/src/tree/TreeRoot.tsx b/client/web/src/tree/TreeRoot.tsx index cd0dc59d377..a9c1f50f70c 100644 --- a/client/web/src/tree/TreeRoot.tsx +++ b/client/web/src/tree/TreeRoot.tsx @@ -15,7 +15,7 @@ import { takeUntil, } from 'rxjs/operators' -import { asError, ErrorLike, isErrorLike } from '@sourcegraph/common' +import { asError, ErrorLike, isErrorLike, logger } from '@sourcegraph/common' import { FileDecorationsByPath } from '@sourcegraph/shared/src/api/extension/extensionHostApi' import { fetchTreeEntries } from '@sourcegraph/shared/src/backend/repo' import { ExtensionsControllerProps } from '@sourcegraph/shared/src/extensions/controller' @@ -117,7 +117,7 @@ export class TreeRoot extends React.Component { // clear file decorations before latest file decorations come this.setState({ treeOrError, fileDecorationsByPath: {} }) }, - error => console.error(error) + error => logger.error(error) ) ) diff --git a/client/web/src/user/settings/auth/UserSettingsPasswordPage.tsx b/client/web/src/user/settings/auth/UserSettingsPasswordPage.tsx index 5b2a73fbd38..3a2b1bbb2b6 100644 --- a/client/web/src/user/settings/auth/UserSettingsPasswordPage.tsx +++ b/client/web/src/user/settings/auth/UserSettingsPasswordPage.tsx @@ -6,6 +6,7 @@ import { catchError, filter, mergeMap, tap } from 'rxjs/operators' import { ErrorAlert } from '@sourcegraph/branded/src/components/alerts' import { Form } from '@sourcegraph/branded/src/components/Form' +import { logger } from '@sourcegraph/common' import { Button, Container, PageHeader, LoadingSpinner, Link, Alert, Input, Label } from '@sourcegraph/wildcard' import { AuthenticatedUser } from '../../../auth' @@ -226,7 +227,7 @@ export class UserSettingsPasswordPage extends React.Component { } private handleError = (error: Error): [] => { - console.error(error) + logger.error(error) this.setState({ loading: false, saved: false, error }) return [] } diff --git a/client/web/src/util/security.ts b/client/web/src/util/security.ts index 7ef4f8502ae..1354a1e4336 100644 --- a/client/web/src/util/security.ts +++ b/client/web/src/util/security.ts @@ -1,3 +1,5 @@ +import { logger } from '@sourcegraph/common' + import { SourcegraphContext } from '../jscontext' export function validatePassword( @@ -73,7 +75,7 @@ export function getPasswordRequirements( let requirements: string = 'At least ' + context.authMinPasswordLength.toString() + ' characters' if (passwordPolicyReference?.enabled) { - console.log('Using enhanced password policy.') + logger.log('Using enhanced password policy.') if ( passwordPolicyReference.numberOfSpecialCharacters && diff --git a/dev/release/.eslintrc.js b/dev/release/.eslintrc.js index 73efb3a16e6..25cc7500fb0 100644 --- a/dev/release/.eslintrc.js +++ b/dev/release/.eslintrc.js @@ -5,5 +5,6 @@ module.exports = { ...baseConfig.parserOptions, project: __dirname + '/tsconfig.json', }, + rules: { 'no-console': 'off' }, overrides: baseConfig.overrides, }