From 42b40636991b97fe818007fab19091764fc5db73 Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Fri, 15 Jul 2022 15:30:14 +0200 Subject: Add ability for client to create server logs --- client/src/app/core/auth/auth.service.ts | 12 +++++------ .../src/app/core/notification/notifier.service.ts | 7 ++++--- client/src/app/core/plugins/hooks.service.ts | 3 ++- client/src/app/core/rest/rest-extractor.service.ts | 7 ++++--- client/src/app/core/rest/rest-table.ts | 9 +++++---- client/src/app/core/rest/rest.service.ts | 6 +++--- .../src/app/core/routing/custom-reuse-strategy.ts | 7 ++++--- client/src/app/core/routing/redirect.service.ts | 23 ++++++++++------------ client/src/app/core/routing/scroll.service.ts | 9 +++++---- client/src/app/core/server/server.service.ts | 3 ++- client/src/app/core/theme/theme.service.ts | 11 ++++++----- .../app/core/users/user-local-storage.service.ts | 7 ++++--- 12 files changed, 55 insertions(+), 49 deletions(-) (limited to 'client/src/app/core') diff --git a/client/src/app/core/auth/auth.service.ts b/client/src/app/core/auth/auth.service.ts index 2ac88c185..ece6bc5d1 100644 --- a/client/src/app/core/auth/auth.service.ts +++ b/client/src/app/core/auth/auth.service.ts @@ -5,7 +5,7 @@ import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http' import { Injectable } from '@angular/core' import { Router } from '@angular/router' import { Notifier } from '@app/core/notification/notifier.service' -import { objectToUrlEncoded, peertubeLocalStorage, UserTokens } from '@root-helpers/index' +import { logger, objectToUrlEncoded, peertubeLocalStorage, UserTokens } from '@root-helpers/index' import { HttpStatusCode, MyUser as UserServerModel, OAuthClientLocal, User, UserLogin, UserRefreshToken } from '@shared/models' import { environment } from '../../../environments/environment' import { RestExtractor } from '../rest/rest-extractor.service' @@ -90,7 +90,7 @@ export class AuthService { peertubeLocalStorage.setItem(AuthService.LOCAL_STORAGE_OAUTH_CLIENT_KEYS.CLIENT_ID, this.clientId) peertubeLocalStorage.setItem(AuthService.LOCAL_STORAGE_OAUTH_CLIENT_KEYS.CLIENT_SECRET, this.clientSecret) - console.log('Client credentials loaded.') + logger.info('Client credentials loaded.') }, error: err => { @@ -177,7 +177,7 @@ Ensure you have correctly configured PeerTube (config/ directory), in particular } }, - error: err => console.error(err) + error: err => logger.error(err) }) this.user = null @@ -190,7 +190,7 @@ Ensure you have correctly configured PeerTube (config/ directory), in particular refreshAccessToken () { if (this.refreshingTokenObservable) return this.refreshingTokenObservable - console.log('Refreshing token...') + logger.info('Refreshing token...') const refreshToken = this.getRefreshToken() @@ -212,8 +212,8 @@ Ensure you have correctly configured PeerTube (config/ directory), in particular catchError(err => { this.refreshingTokenObservable = null - console.error(err) - console.log('Cannot refresh token -> logout...') + logger.error(err) + logger.info('Cannot refresh token -> logout...') this.logout() this.router.navigate([ '/login' ]) diff --git a/client/src/app/core/notification/notifier.service.ts b/client/src/app/core/notification/notifier.service.ts index 165bb0c76..15af5c1b6 100644 --- a/client/src/app/core/notification/notifier.service.ts +++ b/client/src/app/core/notification/notifier.service.ts @@ -1,5 +1,6 @@ import { MessageService } from 'primeng/api' import { Injectable } from '@angular/core' +import { logger } from '@root-helpers/logger' @Injectable() export class Notifier { @@ -10,21 +11,21 @@ export class Notifier { info (text: string, title?: string, timeout?: number, sticky?: boolean) { if (!title) title = $localize`Info` - console.info(`${title}: ${text}`) + logger.info(`${title}: ${text}`) return this.notify('info', text, title, timeout, sticky) } error (text: string, title?: string, timeout?: number, sticky?: boolean) { if (!title) title = $localize`Error` - console.error(`${title}: ${text}`) + logger.error(`${title}: ${text}`) return this.notify('error', text, title, timeout, sticky) } success (text: string, title?: string, timeout?: number, sticky?: boolean) { if (!title) title = $localize`Success` - console.log(`${title}: ${text}`) + logger.info(`${title}: ${text}`) return this.notify('success', text, title, timeout, sticky) } diff --git a/client/src/app/core/plugins/hooks.service.ts b/client/src/app/core/plugins/hooks.service.ts index 062083fd1..7fd56d92e 100644 --- a/client/src/app/core/plugins/hooks.service.ts +++ b/client/src/app/core/plugins/hooks.service.ts @@ -2,6 +2,7 @@ import { from, Observable } from 'rxjs' import { mergeMap, switchMap } from 'rxjs/operators' import { Injectable } from '@angular/core' import { PluginService } from '@app/core/plugins/plugin.service' +import { logger } from '@root-helpers/logger' import { ClientActionHookName, ClientFilterHookName, PluginClientScope } from '@shared/models' import { AuthService, AuthStatus } from '../auth' @@ -50,7 +51,7 @@ export class HooksService { runAction (hookName: U, scope: PluginClientScope, params?: T) { this.pluginService.ensurePluginsAreLoaded(scope) .then(() => this.pluginService.runHook(hookName, undefined, params)) - .catch((err: any) => console.error('Fatal hook error.', { err })) + .catch((err: any) => logger.error('Fatal hook error.', err)) } async wrapObject (result: T, scope: PluginClientScope, hookName: U) { diff --git a/client/src/app/core/rest/rest-extractor.service.ts b/client/src/app/core/rest/rest-extractor.service.ts index 86c7484a5..8a2974563 100644 --- a/client/src/app/core/rest/rest-extractor.service.ts +++ b/client/src/app/core/rest/rest-extractor.service.ts @@ -3,6 +3,7 @@ import { Injectable } from '@angular/core' import { Router } from '@angular/router' import { dateToHuman } from '@app/helpers' import { HttpStatusCode, ResultList } from '@shared/models' +import { logger } from '@root-helpers/logger' @Injectable() export class RestExtractor { @@ -64,7 +65,7 @@ export class RestExtractor { if (err.error instanceof Error) { // A client-side or network error occurred. Handle it accordingly. const errorMessage = err.error.detail || err.error.title - console.error('An error occurred:', errorMessage) + logger.error('An error occurred:', errorMessage) return errorMessage } @@ -75,12 +76,12 @@ export class RestExtractor { if (err.status !== undefined) { const errorMessage = this.buildServerErrorMessage(err) - console.error(`Backend returned code ${err.status}, errorMessage is: ${errorMessage}`) + logger.error(`Backend returned code ${err.status}, errorMessage is: ${errorMessage}`) return errorMessage } - console.error(err) + logger.error(err) return err } diff --git a/client/src/app/core/rest/rest-table.ts b/client/src/app/core/rest/rest-table.ts index cb5bd0b89..ec5646b5d 100644 --- a/client/src/app/core/rest/rest-table.ts +++ b/client/src/app/core/rest/rest-table.ts @@ -1,10 +1,11 @@ -import * as debug from 'debug' +import debug from 'debug' import { LazyLoadEvent, SortMeta } from 'primeng/api' import { ActivatedRoute, Router } from '@angular/router' +import { logger } from '@root-helpers/logger' import { peertubeLocalStorage } from '@root-helpers/peertube-web-storage' import { RestPagination } from './rest-pagination' -const logger = debug('peertube:tables:RestTable') +const debugLogger = debug('peertube:tables:RestTable') export abstract class RestTable { @@ -34,7 +35,7 @@ export abstract class RestTable { try { this.sort = JSON.parse(result) } catch (err) { - console.error('Cannot load sort of local storage key ' + this.getSortLocalStorageKey(), err) + logger.error('Cannot load sort of local storage key ' + this.getSortLocalStorageKey(), err) } } } @@ -44,7 +45,7 @@ export abstract class RestTable { } loadLazy (event: LazyLoadEvent) { - logger('Load lazy %o.', event) + debugLogger('Load lazy %o.', event) this.sort = { order: event.sortOrder, diff --git a/client/src/app/core/rest/rest.service.ts b/client/src/app/core/rest/rest.service.ts index fc729f0f6..d8b5ffb18 100644 --- a/client/src/app/core/rest/rest.service.ts +++ b/client/src/app/core/rest/rest.service.ts @@ -5,7 +5,7 @@ import { Injectable } from '@angular/core' import { ComponentPaginationLight } from './component-pagination.model' import { RestPagination } from './rest-pagination' -const logger = debug('peertube:rest') +const debugLogger = debug('peertube:rest') interface QueryStringFilterPrefixes { [key: string]: { @@ -88,7 +88,7 @@ export class RestService { const prefixeStrings = Object.values(prefixes) .map(p => p.prefix) - logger(`Built tokens "${tokens.join(', ')}" for prefixes "${prefixeStrings.join(', ')}"`) + debugLogger(`Built tokens "${tokens.join(', ')}" for prefixes "${prefixeStrings.join(', ')}"`) // Search is the querystring minus defined filters const searchTokens = tokens.filter(t => { @@ -127,7 +127,7 @@ export class RestService { const search = searchTokens.join(' ') || undefined - logger('Built search: ' + search, additionalFilters) + debugLogger('Built search: ' + search, additionalFilters) return { search, diff --git a/client/src/app/core/routing/custom-reuse-strategy.ts b/client/src/app/core/routing/custom-reuse-strategy.ts index 5d3ad2e67..269b9d193 100644 --- a/client/src/app/core/routing/custom-reuse-strategy.ts +++ b/client/src/app/core/routing/custom-reuse-strategy.ts @@ -1,5 +1,6 @@ import { ComponentRef, Injectable } from '@angular/core' import { ActivatedRouteSnapshot, DetachedRouteHandle, RouteReuseStrategy } from '@angular/router' +import { logger } from '@root-helpers/logger' import { DisableForReuseHook } from './disable-for-reuse-hook' import { PeerTubeRouterService, RouterSetting } from './peertube-router.service' @@ -22,7 +23,7 @@ export class CustomReuseStrategy implements RouteReuseStrategy { const key = this.generateKey(route) this.recentlyUsed = key - console.log('Storing component %s to reuse later.', key) + logger.info(`Storing component ${key} to reuse later.`) const componentRef = (handle as any).componentRef as ComponentRef componentRef.instance.disableForReuse() @@ -46,7 +47,7 @@ export class CustomReuseStrategy implements RouteReuseStrategy { const key = this.generateKey(route) this.recentlyUsed = key - console.log('Reusing component %s.', key) + logger.info(`Reusing component ${key}.`) const handle = this.storedRouteHandles.get(key) if (!handle) return handle; @@ -66,7 +67,7 @@ export class CustomReuseStrategy implements RouteReuseStrategy { this.storedRouteHandles.forEach((r, key) => { if (key === this.recentlyUsed) return - console.log('Removing stored component %s.', key); + logger.info(`Removing stored component ${key}`); (r as any).componentRef.destroy() this.storedRouteHandles.delete(key) diff --git a/client/src/app/core/routing/redirect.service.ts b/client/src/app/core/routing/redirect.service.ts index 567fd432b..575b3b2a1 100644 --- a/client/src/app/core/routing/redirect.service.ts +++ b/client/src/app/core/routing/redirect.service.ts @@ -1,10 +1,11 @@ import * as debug from 'debug' import { Injectable } from '@angular/core' import { NavigationCancel, NavigationEnd, Router } from '@angular/router' +import { logger } from '@root-helpers/logger' import { ServerService } from '../server' import { SessionStorageService } from '../wrappers/storage.service' -const logger = debug('peertube:router:RedirectService') +const debugLogger = debug('peertube:router:RedirectService') @Injectable() export class RedirectService { @@ -40,7 +41,7 @@ export class RedirectService { this.latestSessionUrl = this.storage.getItem(RedirectService.SESSION_STORAGE_LATEST_SESSION_URL_KEY) this.storage.removeItem(RedirectService.SESSION_STORAGE_LATEST_SESSION_URL_KEY) - logger('Loaded latest session URL %s', this.latestSessionUrl) + debugLogger('Loaded latest session URL %s', this.latestSessionUrl) // Track previous url this.currentUrl = this.router.url @@ -51,8 +52,8 @@ export class RedirectService { this.previousUrl = this.currentUrl this.currentUrl = event.url - logger('Previous URL is %s, current URL is %s', this.previousUrl, this.currentUrl) - logger('Setting %s as latest URL in session storage.', this.currentUrl) + debugLogger('Previous URL is %s, current URL is %s', this.previousUrl, this.currentUrl) + debugLogger('Setting %s as latest URL in session storage.', this.currentUrl) this.storage.setItem(RedirectService.SESSION_STORAGE_LATEST_SESSION_URL_KEY, this.currentUrl) } @@ -84,18 +85,14 @@ export class RedirectService { this.redirectingToHomepage = true - console.log('Redirecting to %s...', this.defaultRoute) + logger.info(`Redirecting to ${this.defaultRoute}...`) this.router.navigateByUrl(this.defaultRoute, { skipLocationChange }) .then(() => this.redirectingToHomepage = false) .catch(() => { this.redirectingToHomepage = false - console.error( - 'Cannot navigate to %s, resetting default route to %s.', - this.defaultRoute, - RedirectService.INIT_DEFAULT_ROUTE - ) + logger.error(`Cannot navigate to ${this.defaultRoute}, resetting default route to ${RedirectService.INIT_DEFAULT_ROUTE}`) this.defaultRoute = RedirectService.INIT_DEFAULT_ROUTE return this.router.navigateByUrl(this.defaultRoute, { skipLocationChange }) @@ -104,18 +101,18 @@ export class RedirectService { } private doRedirect (redirectUrl: string, fallbackRoute?: string) { - logger('Redirecting on %s', redirectUrl) + debugLogger('Redirecting on %s', redirectUrl) if (this.isValidRedirection(redirectUrl)) { return this.router.navigateByUrl(redirectUrl) } - logger('%s is not a valid redirection, try fallback route %s', redirectUrl, fallbackRoute) + debugLogger('%s is not a valid redirection, try fallback route %s', redirectUrl, fallbackRoute) if (fallbackRoute) { return this.router.navigateByUrl(fallbackRoute) } - logger('There was no fallback route, redirecting to homepage') + debugLogger('There was no fallback route, redirecting to homepage') return this.redirectToHomepage() } diff --git a/client/src/app/core/routing/scroll.service.ts b/client/src/app/core/routing/scroll.service.ts index 6d37fde71..0966255b3 100644 --- a/client/src/app/core/routing/scroll.service.ts +++ b/client/src/app/core/routing/scroll.service.ts @@ -4,8 +4,9 @@ import { ViewportScroller } from '@angular/common' import { Injectable } from '@angular/core' import { RouterSetting } from '../' import { PeerTubeRouterService } from './peertube-router.service' +import { logger } from '@root-helpers/logger' -const logger = debug('peertube:main:ScrollService') +const debugLogger = debug('peertube:main:ScrollService') @Injectable() export class ScrollService { @@ -57,8 +58,8 @@ export class ScrollService { if (nextSearchParams.toString() !== previousSearchParams.toString()) { this.resetScroll = true } - } catch (e) { - console.error('Cannot parse URL to check next scroll.', e) + } catch (err) { + logger.error('Cannot parse URL to check next scroll.', err) this.resetScroll = true } }) @@ -67,7 +68,7 @@ export class ScrollService { private consumeScroll () { // Handle anchors/restore position this.peertubeRouter.getScrollEvents().subscribe(e => { - logger('Will schedule scroll after router event %o.', { e, resetScroll: this.resetScroll }) + debugLogger('Will schedule scroll after router event %o.', { e, resetScroll: this.resetScroll }) // scrollToAnchor first to preserve anchor position when using history navigation if (e.anchor) { diff --git a/client/src/app/core/server/server.service.ts b/client/src/app/core/server/server.service.ts index d01942139..9db455cb8 100644 --- a/client/src/app/core/server/server.service.ts +++ b/client/src/app/core/server/server.service.ts @@ -3,6 +3,7 @@ import { first, map, share, shareReplay, switchMap, tap } from 'rxjs/operators' import { HttpClient } from '@angular/common/http' import { Inject, Injectable, LOCALE_ID } from '@angular/core' import { getDevLocale, isOnDevLocale, sortBy } from '@app/helpers' +import { logger } from '@root-helpers/logger' import { getCompleteLocale, isDefaultLocale, peertubeTranslate } from '@shared/core-utils/i18n' import { HTMLServerConfig, ServerConfig, ServerStats, VideoConstant } from '@shared/models' import { environment } from '../../../environments/environment' @@ -43,7 +44,7 @@ export class ServerService { } catch (err) { // Expected in dev mode since we can't inject the config in the HTML if (environment.production !== false) { - console.error('Cannot load config locally. Fallback to API.') + logger.error('Cannot load config locally. Fallback to API.') } return this.getConfig() diff --git a/client/src/app/core/theme/theme.service.ts b/client/src/app/core/theme/theme.service.ts index 40939ecb8..ead1770ba 100644 --- a/client/src/app/core/theme/theme.service.ts +++ b/client/src/app/core/theme/theme.service.ts @@ -1,4 +1,5 @@ import { Injectable } from '@angular/core' +import { logger } from '@root-helpers/logger' import { capitalizeFirstLetter } from '@root-helpers/string' import { UserLocalStorageKeys } from '@root-helpers/users' import { HTMLServerConfig, ServerConfigTheme } from '@shared/models' @@ -57,7 +58,7 @@ export class ThemeService { private injectThemes (themes: ServerConfigTheme[], fromLocalStorage = false) { this.themes = themes - console.log('Injecting %d themes.', this.themes.length) + logger.info(`Injecting ${this.themes.length} themes.`) const head = this.getHeadElement() @@ -117,13 +118,13 @@ export class ThemeService { const currentTheme = this.getCurrentTheme() - console.log('Enabling %s theme.', currentTheme) + logger.info(`Enabling ${currentTheme} theme.`) this.loadTheme(currentTheme) const theme = this.getTheme(currentTheme) if (theme) { - console.log('Adding scripts of theme %s.', currentTheme) + logger.info(`Adding scripts of theme ${currentTheme}`) this.pluginService.addPlugin(theme, true) @@ -165,7 +166,7 @@ export class ThemeService { this.injectThemes([ lastActiveTheme ], true) this.updateCurrentTheme() } catch (err) { - console.error('Cannot parse last active theme.', err) + logger.error('Cannot parse last active theme.', err) return } } @@ -173,7 +174,7 @@ export class ThemeService { private removeThemePlugins (themeName: string) { const oldTheme = this.getTheme(themeName) if (oldTheme) { - console.log('Removing scripts of old theme %s.', themeName) + logger.info(`Removing scripts of old theme ${themeName}.`) this.pluginService.removePlugin(oldTheme) } } diff --git a/client/src/app/core/users/user-local-storage.service.ts b/client/src/app/core/users/user-local-storage.service.ts index d15bf735b..fff649eef 100644 --- a/client/src/app/core/users/user-local-storage.service.ts +++ b/client/src/app/core/users/user-local-storage.service.ts @@ -2,8 +2,9 @@ import { filter, throttleTime } from 'rxjs' import { Injectable } from '@angular/core' import { AuthService, AuthStatus } from '@app/core/auth' -import { UserLocalStorageKeys, UserTokens } from '@root-helpers/users' import { getBoolOrDefault } from '@root-helpers/local-storage-utils' +import { logger } from '@root-helpers/logger' +import { UserLocalStorageKeys, UserTokens } from '@root-helpers/users' import { UserRole, UserUpdateMe } from '@shared/models' import { NSFWPolicyType } from '@shared/models/videos' import { ServerService } from '../server' @@ -95,7 +96,7 @@ export class UserLocalStorageService { : null } catch (err) { videoLanguages = null - console.error('Cannot parse desired video languages from localStorage.', err) + logger.error('Cannot parse desired video languages from localStorage.', err) } const htmlConfig = this.server.getHTMLConfig() @@ -142,7 +143,7 @@ export class UserLocalStorageService { this.localStorageService.setItem(key, localStorageValue) } catch (err) { - console.error(`Cannot set ${key}->${value} in localStorage. Likely due to a value impossible to stringify.`, err) + logger.error(`Cannot set ${key}->${value} in localStorage. Likely due to a value impossible to stringify.`, err) } } } -- cgit v1.2.3