Improve Logging (#1519)

Improve Logging

Signed-off-by: Tilman Vatteroth <git@tilmanvatteroth.de>
This commit is contained in:
Tilman Vatteroth 2021-09-28 22:06:35 +02:00 committed by GitHub
parent 1172a1d7b8
commit 0e512531a0
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
41 changed files with 361 additions and 92 deletions

View file

@ -11,6 +11,9 @@ import { createSetUpTaskList, InitTask } from './initializers'
import { LoadingScreen } from './loading-screen'
import { useCustomizeAssetsUrl } from '../../hooks/common/use-customize-assets-url'
import { useFrontendAssetsUrl } from '../../hooks/common/use-frontend-assets-url'
import { Logger } from '../../utils/logger'
const log = new Logger('ApplicationLoader')
export const ApplicationLoader: React.FC = ({ children }) => {
const frontendAssetsUrl = useFrontendAssetsUrl()
@ -36,7 +39,7 @@ export const ApplicationLoader: React.FC = ({ children }) => {
useEffect(() => {
for (const task of initTasks) {
runTask(task.task).catch((reason: Error) => {
console.error(reason)
log.error('Error while initialising application', reason)
setFailedTitle(task.name)
})
}

View file

@ -6,8 +6,10 @@
import { setBanner } from '../../../redux/banner/methods'
import { defaultFetchConfig } from '../../../api/utils'
import { Logger } from '../../../utils/logger'
export const BANNER_LOCAL_STORAGE_KEY = 'banner.lastModified'
const log = new Logger('Banner')
export const fetchAndSetBanner = async (customizeAssetsUrl: string): Promise<void> => {
const cachedLastModified = window.localStorage.getItem(BANNER_LOCAL_STORAGE_KEY)
@ -42,7 +44,7 @@ export const fetchAndSetBanner = async (customizeAssetsUrl: string): Promise<voi
const lastModified = response.headers.get('Last-Modified')
if (!lastModified) {
console.warn("'Last-Modified' not found for banner.txt!")
log.warn("'Last-Modified' not found for banner.txt!")
}
setBanner({

View file

@ -9,12 +9,15 @@ import { Overlay, Tooltip } from 'react-bootstrap'
import { Trans, useTranslation } from 'react-i18next'
import { v4 as uuid } from 'uuid'
import { ShowIf } from '../show-if/show-if'
import { Logger } from '../../../utils/logger'
export interface CopyOverlayProps {
content: string
clickComponent: RefObject<HTMLElement>
}
const log = new Logger('CopyOverlay')
export const CopyOverlay: React.FC<CopyOverlayProps> = ({ content, clickComponent }) => {
useTranslation()
const [showCopiedTooltip, setShowCopiedTooltip] = useState(false)
@ -27,9 +30,9 @@ export const CopyOverlay: React.FC<CopyOverlayProps> = ({ content, clickComponen
.then(() => {
setError(false)
})
.catch(() => {
.catch((error: Error) => {
setError(true)
console.error("couldn't copy")
log.error('Copy failed', error)
})
.finally(() => {
setShowCopiedTooltip(true)

View file

@ -10,6 +10,7 @@ import { useTranslation } from 'react-i18next'
import { ForkAwesomeIcon } from '../../fork-awesome/fork-awesome-icon'
import { ShowIf } from '../../show-if/show-if'
import { CopyOverlay } from '../copy-overlay'
import { Logger } from '../../../../utils/logger'
export interface CopyableFieldProps {
content: string
@ -17,6 +18,8 @@ export interface CopyableFieldProps {
url?: string
}
const log = new Logger('CopyableField')
export const CopyableField: React.FC<CopyableFieldProps> = ({ content, nativeShareButton, url }) => {
useTranslation()
const copyButton = useRef<HTMLButtonElement>(null)
@ -27,8 +30,8 @@ export const CopyableField: React.FC<CopyableFieldProps> = ({ content, nativeSha
text: content,
url: url
})
.catch((err) => {
console.error('Native sharing failed: ', err)
.catch((error) => {
log.error('Native sharing failed', error)
})
}, [content, url])

View file

@ -8,6 +8,9 @@ import { Revision } from '../../../../api/revisions/types'
import { getUserById } from '../../../../api/users'
import { UserResponse } from '../../../../api/users/types'
import { download } from '../../../common/download/download'
import { Logger } from '../../../../utils/logger'
const log = new Logger('RevisionsUtils')
export const downloadRevision = (noteId: string, revision: Revision | null): void => {
if (!revision) {
@ -26,7 +29,7 @@ export const getUserDataForRevision = (authors: string[]): UserResponse[] => {
.then((userData) => {
users.push(userData)
})
.catch((error) => console.error(error))
.catch((error) => log.error(error))
})
return users
}

View file

@ -29,6 +29,7 @@ import { useUpdateLocalHistoryEntry } from './hooks/useUpdateLocalHistoryEntry'
import { useApplicationState } from '../../hooks/common/use-application-state'
import { EditorDocumentRenderer } from './editor-document-renderer/editor-document-renderer'
import { EditorToRendererCommunicatorContextProvider } from './render-context/editor-to-renderer-communicator-context-provider'
import { Logger } from '../../utils/logger'
export interface EditorPagePathParams {
id: string
@ -39,6 +40,8 @@ export enum ScrollSource {
RENDERER
}
const log = new Logger('EditorPage')
export const EditorPage: React.FC = () => {
useTranslation()
const scrollSource = useRef<ScrollSource>(ScrollSource.EDITOR)
@ -55,7 +58,7 @@ export const EditorPage: React.FC = () => {
if (scrollSource.current === ScrollSource.RENDERER && editorSyncScroll) {
setScrollState((old) => {
const newState = { editorScrollState: newScrollState, rendererScrollState: old.rendererScrollState }
console.debug('[EditorPage] set scroll state because of renderer scroll', newState)
log.debug('Set scroll state because of renderer scroll', newState)
return newState
})
}
@ -68,7 +71,7 @@ export const EditorPage: React.FC = () => {
if (scrollSource.current === ScrollSource.EDITOR && editorSyncScroll) {
setScrollState((old) => {
const newState = { rendererScrollState: newScrollState, editorScrollState: old.editorScrollState }
console.debug('[EditorPage] set scroll state because of editor scroll', newState)
log.debug('Set scroll state because of editor scroll', newState)
return newState
})
}
@ -87,12 +90,12 @@ export const EditorPage: React.FC = () => {
const setRendererToScrollSource = useCallback(() => {
scrollSource.current = ScrollSource.RENDERER
console.debug('[EditorPage] Make renderer scroll source')
log.debug('Make renderer scroll source')
}, [])
const setEditorToScrollSource = useCallback(() => {
scrollSource.current = ScrollSource.EDITOR
console.debug('[EditorPage] Make editor scroll source')
log.debug('Make editor scroll source')
}, [])
useNotificationTest()

View file

@ -7,9 +7,11 @@
import { Editor, Hint, Hints, Pos } from 'codemirror'
import { findWordAtCursor, generateHintListByPrefix, Hinter } from './index'
import { showErrorNotification } from '../../../../redux/ui-notifications/methods'
import { Logger } from '../../../../utils/logger'
type highlightJsImport = typeof import('../../../common/hljs/hljs')
const log = new Logger('Autocompletion > CodeBlock')
const wordRegExp = /^```((\w|-|_|\+)*)$/
let allSupportedLanguages: string[] = []
@ -22,7 +24,7 @@ const loadHighlightJs = async (): Promise<highlightJsImport | null> => {
return await import('../../../common/hljs/hljs')
} catch (error) {
showErrorNotification('common.errorWhileLoadingLibrary', { name: 'highlight.js' })(error as Error)
console.error("can't load highlight js", error)
log.error('Error while loading highlight.js', error)
return null
}
}

View file

@ -10,9 +10,11 @@ import { Emoji, EmojiClickEventDetail, NativeEmoji } from 'emoji-picker-element/
import { emojiPickerConfig } from '../tool-bar/emoji-picker/emoji-picker'
import { getEmojiIcon, getEmojiShortCode } from '../tool-bar/utils/emojiUtils'
import { findWordAtCursor, Hinter } from './index'
import { Logger } from '../../../../utils/logger'
const emojiIndex = new Database(emojiPickerConfig)
const emojiWordRegex = /^:([\w-_+]*)$/
const log = new Logger('Autocompletion > Emoji')
const findEmojiInDatabase = async (emojiIndex: Database, term: string): Promise<Emoji[]> => {
try {
@ -26,7 +28,7 @@ const findEmojiInDatabase = async (emojiIndex: Database, term: string): Promise<
return queryResult
}
} catch (error) {
console.error(error)
log.error('Error while searching for emoji', term, error)
return []
}
}

View file

@ -9,6 +9,9 @@ import i18n from 'i18next'
import { uploadFile } from '../../../api/media'
import { store } from '../../../redux'
import { supportedMimeTypes } from '../../common/upload-image-mimetypes'
import { Logger } from '../../../utils/logger'
const log = new Logger('File Uploader Handler')
export const handleUpload = (file: File, editor: Editor): void => {
if (!file) {
@ -30,7 +33,7 @@ export const handleUpload = (file: File, editor: Editor): void => {
insertCode(`![](${link})`)
})
.catch((error) => {
console.error('error while uploading file', error)
log.error('error while uploading file', error)
insertCode('')
})
}

View file

@ -9,6 +9,9 @@ import { useParams } from 'react-router'
import { getNote } from '../../../api/notes'
import { setNoteDataFromServer } from '../../../redux/note-details/methods'
import { EditorPagePathParams } from '../editor-page'
import { Logger } from '../../../utils/logger'
const log = new Logger('Load Note From Server')
export const useLoadNoteFromServer = (): [boolean, boolean] => {
const { id } = useParams<EditorPagePathParams>()
@ -21,9 +24,9 @@ export const useLoadNoteFromServer = (): [boolean, boolean] => {
.then((note) => {
setNoteDataFromServer(note)
})
.catch((e) => {
.catch((error) => {
setError(true)
console.error(e)
log.error('Error while fetching note from server', error)
})
.finally(() => setLoading(false))
}, [id])

View file

@ -6,6 +6,9 @@
import { RefObject, useCallback, useRef } from 'react'
import { EditorToRendererCommunicator } from '../../../render-page/window-post-message-communicator/editor-to-renderer-communicator'
import { Logger } from '../../../../utils/logger'
const log = new Logger('IframeLoader')
export const useOnIframeLoad = (
frameReference: RefObject<HTMLIFrameElement>,
@ -29,7 +32,7 @@ export const useOnIframeLoad = (
return
} else {
onNavigateAway()
console.error('Navigated away from unknown URL')
log.error('Navigated away from unknown URL')
frame.src = renderPageUrl
sendToRenderPage.current = true
}

View file

@ -5,6 +5,9 @@
*/
import React, { MutableRefObject, useCallback, useEffect, useRef } from 'react'
import { Logger } from '../../../utils/logger'
const log = new Logger('UploadInput')
export interface UploadInputProps {
onLoad: (file: File) => Promise<void>
@ -30,7 +33,7 @@ export const UploadInput: React.FC<UploadInputProps> = ({ onLoad, acceptedFiles,
fileInput.value = ''
})
.catch((error) => {
console.error(error)
log.error('Error while uploading file', error)
})
})
fileInput.click()

View file

@ -6,8 +6,10 @@
import { useEffect } from 'react'
import { dispatchUiNotification } from '../../redux/ui-notifications/methods'
import { Logger } from '../../utils/logger'
const localStorageKey = 'dontshowtestnotification'
const log = new Logger('Notification Test')
/**
* Spawns a notification to test the system. Only for tech demo show case.
@ -17,7 +19,7 @@ export const useNotificationTest = (): void => {
if (window.localStorage.getItem(localStorageKey)) {
return
}
console.debug('[Notifications] Dispatched test notification')
log.debug('Dispatched test notification')
void dispatchUiNotification('notificationTest.title', 'notificationTest.content', {
icon: 'info-circle',
buttons: [

View file

@ -10,6 +10,9 @@ import links from '../../links.json'
import frontendVersion from '../../version.json'
import { ForkAwesomeIcon } from '../common/fork-awesome/fork-awesome-icon'
import { ExternalLink } from '../common/links/external-link'
import { Logger } from '../../utils/logger'
const log = new Logger('ErrorBoundary')
export class ErrorBoundary extends Component {
state: {
@ -27,8 +30,7 @@ export class ErrorBoundary extends Component {
}
componentDidCatch(error: Error, errorInfo: ErrorInfo): void {
console.error('error caught', error)
console.error('additional information', errorInfo)
log.error('Error catched', error, errorInfo)
}
refreshPage(): void {

View file

@ -8,7 +8,9 @@ import { Settings } from 'luxon'
import React, { useCallback, useMemo } from 'react'
import { Form } from 'react-bootstrap'
import { useTranslation } from 'react-i18next'
import { Logger } from '../../../utils/logger'
const log = new Logger('LanguagePicker')
const languages = {
en: 'English',
'zh-CN': '简体中文',
@ -61,7 +63,7 @@ export const LanguagePicker: React.FC = () => {
(event: React.ChangeEvent<HTMLSelectElement>) => {
const language = event.currentTarget.value
Settings.defaultLocale = language
i18n.changeLanguage(language).catch((error) => console.error('Error while switching language', error))
i18n.changeLanguage(language).catch((error) => log.error('Error while switching language', error))
},
[i18n]
)

View file

@ -5,11 +5,14 @@
*/
import MarkdownIt from 'markdown-it/lib'
import { Logger } from '../../../utils/logger'
const log = new Logger('MarkdownItParserDebugger')
export const MarkdownItParserDebugger: MarkdownIt.PluginSimple = (md: MarkdownIt) => {
if (process.env.NODE_ENV !== 'production') {
md.core.ruler.push('test', (state) => {
console.log(state)
log.debug('Current state', state)
return false
})
}

View file

@ -6,6 +6,9 @@
import React, { useEffect, useRef } from 'react'
import './abc.scss'
import { Logger } from '../../../../utils/logger'
const log = new Logger('AbcFrame')
export interface AbcFrameProps {
code: string
@ -23,8 +26,8 @@ export const AbcFrame: React.FC<AbcFrameProps> = ({ code }) => {
.then((imp) => {
imp.renderAbc(actualContainer, code, {})
})
.catch(() => {
console.error('error while loading abcjs')
.catch((error) => {
log.error('Error while loading abcjs', error)
})
}, [code])

View file

@ -8,6 +8,9 @@ import React, { useEffect, useRef, useState } from 'react'
import { Alert } from 'react-bootstrap'
import { Trans, useTranslation } from 'react-i18next'
import { useIsDarkModeActivated } from '../../../../../hooks/common/use-is-dark-mode-activated'
import { Logger } from '../../../../../utils/logger'
const log = new Logger('FlowChart')
export interface FlowChartProps {
code: string
@ -43,7 +46,7 @@ export const FlowChart: React.FC<FlowChartProps> = ({ code }) => {
setError(true)
}
})
.catch(() => console.error('error while loading flowchart.js'))
.catch((error) => log.error('Error while loading flowchart.js', error))
return () => {
Array.from(currentDiagramRef.children).forEach((value) => value.remove())

View file

@ -8,6 +8,9 @@ import React, { Fragment, useCallback, useEffect, useRef, useState } from 'react
import { Alert } from 'react-bootstrap'
import { ShowIf } from '../../../common/show-if/show-if'
import { useFrontendBaseUrl } from '../../../../hooks/common/use-frontend-base-url'
import { Logger } from '../../../../utils/logger'
const log = new Logger('GraphvizFrame')
export interface GraphvizFrameProps {
code: string
@ -22,7 +25,7 @@ export const GraphvizFrame: React.FC<GraphvizFrameProps> = ({ code }) => {
return
}
setError(error)
console.error(error)
log.error(error)
container.current.querySelectorAll('svg').forEach((child) => child.remove())
}, [])
@ -53,8 +56,8 @@ export const GraphvizFrame: React.FC<GraphvizFrameProps> = ({ code }) => {
showError(error as string)
}
})
.catch(() => {
console.error('error while loading graphviz')
.catch((error) => {
log.error('Error while loading graphviz', error)
})
}, [code, error, frontendBaseUrl, showError])

View file

@ -9,6 +9,9 @@ import convertHtmlToReact from '@hedgedoc/html-to-react'
import { CopyToClipboardButton } from '../../../../common/copyable/copy-to-clipboard-button/copy-to-clipboard-button'
import '../../../utils/button-inside.scss'
import './highlighted-code.scss'
import { Logger } from '../../../../../utils/logger'
const log = new Logger('HighlightedCode')
export interface HighlightedCodeProps {
code: string
@ -55,8 +58,8 @@ export const HighlightedCode: React.FC<HighlightedCodeProps> = ({ code, language
))
setDom(replacedDom)
})
.catch(() => {
console.error('error while loading highlight.js')
.catch((error) => {
log.error('Error while loading highlight.js', error)
})
}, [code, language, startLineNumber])

View file

@ -7,6 +7,9 @@
import React, { useEffect, useState } from 'react'
import { getProxiedUrl } from '../../../../api/media'
import { useApplicationState } from '../../../../hooks/common/use-application-state'
import { Logger } from '../../../../utils/logger'
const log = new Logger('ProxyImageFrame')
export const ProxyImageFrame: React.FC<React.ImgHTMLAttributes<HTMLImageElement>> = ({ src, title, alt, ...props }) => {
const [imageUrl, setImageUrl] = useState('')
@ -18,7 +21,7 @@ export const ProxyImageFrame: React.FC<React.ImgHTMLAttributes<HTMLImageElement>
}
getProxiedUrl(src)
.then((proxyResponse) => setImageUrl(proxyResponse.src))
.catch((err) => console.error(err))
.catch((err) => log.error(err))
}, [imageProxyEnabled, src])
return <img src={imageProxyEnabled ? imageUrl : src ?? ''} title={title ?? alt ?? ''} alt={alt} {...props} />

View file

@ -8,6 +8,9 @@ import React, { useEffect, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { LockButton } from '../../../common/lock-button/lock-button'
import '../../utils/button-inside.scss'
import { Logger } from '../../../../utils/logger'
const log = new Logger('MarkmapFrame')
export interface MarkmapFrameProps {
code: string
@ -54,11 +57,11 @@ export const MarkmapFrame: React.FC<MarkmapFrameProps> = ({ code }) => {
actualContainer.appendChild(svg)
markmapLoader(svg, code)
} catch (error) {
console.error(error)
log.error(error)
}
})
.catch(() => {
console.error('error while loading markmap')
.catch((error) => {
log.error('Error while loading markmap', error)
})
}, [code])

View file

@ -9,7 +9,9 @@ import { Alert } from 'react-bootstrap'
import { useTranslation } from 'react-i18next'
import { ShowIf } from '../../../common/show-if/show-if'
import './mermaid.scss'
import { Logger } from '../../../../utils/logger'
const log = new Logger('MermaidChart')
export interface MermaidChartProps {
code: string
}
@ -32,8 +34,8 @@ export const MermaidChart: React.FC<MermaidChartProps> = ({ code }) => {
mermaid.default.initialize({ startOnLoad: false })
mermaidInitialized = true
})
.catch(() => {
console.error('error while loading mermaid')
.catch((error) => {
log.error('Error while loading mermaid', error)
})
}
}, [])
@ -41,7 +43,7 @@ export const MermaidChart: React.FC<MermaidChartProps> = ({ code }) => {
const showError = useCallback(
(error: string) => {
setError(error)
console.error(error)
log.error(error)
if (!diagramContainer.current) {
return
}

View file

@ -10,6 +10,9 @@ import { IconName } from '../../../common/fork-awesome/types'
import { ShowIf } from '../../../common/show-if/show-if'
import './one-click-embedding.scss'
import { ProxyImageFrame } from '../image/proxy-image-frame'
import { Logger } from '../../../../utils/logger'
const log = new Logger('OneClickEmbedding')
interface OneClickFrameProps {
onImageFetch?: () => Promise<string>
@ -52,7 +55,7 @@ export const OneClickEmbedding: React.FC<OneClickFrameProps> = ({
setPreviewImageUrl(imageLink)
})
.catch((message) => {
console.error(message)
log.error(message)
})
}, [onImageFetch])

View file

@ -9,6 +9,9 @@ import { Alert } from 'react-bootstrap'
import { useTranslation } from 'react-i18next'
import { VisualizationSpec } from 'vega-embed'
import { ShowIf } from '../../../common/show-if/show-if'
import { Logger } from '../../../../utils/logger'
const log = new Logger('VegaChart')
export interface VegaChartProps {
code: string
@ -23,7 +26,7 @@ export const VegaChart: React.FC<VegaChartProps> = ({ code }) => {
if (!diagramContainer.current) {
return
}
console.error(error)
log.error(error)
setError(error)
}, [])
@ -58,8 +61,8 @@ export const VegaChart: React.FC<VegaChartProps> = ({ code }) => {
showError(t('renderer.vega-lite.errorJson'))
}
})
.catch(() => {
console.error('error while loading vega-light')
.catch((error) => {
log.error('Error while loading vega-light', error)
})
}, [code, showError, t])

View file

@ -12,8 +12,10 @@ import { ShowIf } from '../common/show-if/show-if'
import { IconName } from '../common/fork-awesome/types'
import { dismissUiNotification } from '../../redux/ui-notifications/methods'
import { Trans, useTranslation } from 'react-i18next'
import { Logger } from '../../utils/logger'
const STEPS_PER_SECOND = 10
const log = new Logger('UiNotificationToast')
export interface UiNotificationProps extends UiNotification {
notificationId: number
@ -42,7 +44,7 @@ export const UiNotificationToast: React.FC<UiNotificationProps> = ({
}, [])
const dismissThisNotification = useCallback(() => {
console.debug(`[Notifications] Dismissed notification ${notificationId}`)
log.debug(`Dismissed notification ${notificationId}`)
dismissUiNotification(notificationId)
}, [notificationId])
@ -50,7 +52,7 @@ export const UiNotificationToast: React.FC<UiNotificationProps> = ({
if (dismissed || !!interval.current) {
return
}
console.debug(`[Notifications] Show notification ${notificationId}`)
log.debug(`Show notification ${notificationId}`)
setEta(durationInSecond * STEPS_PER_SECOND)
interval.current = setInterval(
() =>

View file

@ -15,6 +15,9 @@ import { IconButton } from '../../common/icon-button/icon-button'
import { CommonModal } from '../../common/modals/common-modal'
import { DeletionModal } from '../../common/modals/deletion-modal'
import { ShowIf } from '../../common/show-if/show-if'
import { Logger } from '../../../utils/logger'
const log = new Logger('ProfileAccessTokens')
export const ProfileAccessTokens: React.FC = () => {
const { t } = useTranslation()
@ -37,7 +40,7 @@ export const ProfileAccessTokens: React.FC = () => {
setNewTokenLabel('')
})
.catch((error) => {
console.error(error)
log.error(error)
setError(true)
})
},
@ -50,7 +53,7 @@ export const ProfileAccessTokens: React.FC = () => {
setSelectedForDeletion(0)
})
.catch((error) => {
console.error(error)
log.error(error)
setError(true)
})
.finally(() => {
@ -74,7 +77,7 @@ export const ProfileAccessTokens: React.FC = () => {
setAccessTokens(tokens)
})
.catch((err) => {
console.error(err)
log.error(err)
setError(true)
})
}, [showAddedModal])

View file

@ -13,6 +13,9 @@ import { useApplicationState } from '../../hooks/common/use-application-state'
import { TranslatedExternalLink } from '../common/links/translated-external-link'
import { ShowIf } from '../common/show-if/show-if'
import { fetchAndSetUser } from '../login-page/auth/utils'
import { Logger } from '../../utils/logger'
const log = new Logger('RegisterPage')
export enum RegisterError {
NONE = 'none',
@ -37,7 +40,7 @@ export const RegisterPage: React.FC = () => {
doInternalRegister(username, password)
.then(() => fetchAndSetUser())
.catch((err: Error) => {
console.error(err)
log.error(err)
setError(err.message === RegisterError.USERNAME_EXISTING ? err.message : RegisterError.OTHER)
})
event.preventDefault()

View file

@ -6,6 +6,7 @@
import { WindowPostMessageCommunicator } from './window-post-message-communicator'
import { CommunicationMessages, EditorToRendererMessageType, RendererToEditorMessageType } from './rendering-message'
import { Logger } from '../../../utils/logger'
/**
* The communicator that is used to send messages from the editor to the renderer.
@ -15,7 +16,7 @@ export class EditorToRendererCommunicator extends WindowPostMessageCommunicator<
EditorToRendererMessageType,
CommunicationMessages
> {
protected generateLogIdentifier(): string {
return 'E=>R'
protected createLogger(): Logger {
return new Logger('EditorToRendererCommunicator')
}
}

View file

@ -6,6 +6,7 @@
import { WindowPostMessageCommunicator } from './window-post-message-communicator'
import { CommunicationMessages, EditorToRendererMessageType, RendererToEditorMessageType } from './rendering-message'
import { Logger } from '../../../utils/logger'
/**
* The communicator that is used to send messages from the renderer to the editor.
@ -15,7 +16,7 @@ export class RendererToEditorCommunicator extends WindowPostMessageCommunicator<
RendererToEditorMessageType,
CommunicationMessages
> {
protected generateLogIdentifier(): string {
return 'E<=R'
protected createLogger(): Logger {
return new Logger('RendererToEditorCommunicator')
}
}

View file

@ -4,6 +4,8 @@
* SPDX-License-Identifier: AGPL-3.0-only
*/
import { Logger } from '../../../utils/logger'
/**
* Error that will be thrown if a message couldn't be sent.
*/
@ -33,12 +35,16 @@ export abstract class WindowPostMessageCommunicator<
private targetOrigin?: string
private communicationEnabled: boolean
private handlers: HandlerMap<MESSAGES, RECEIVE_TYPE> = {}
private log
constructor() {
window.addEventListener('message', this.handleEvent.bind(this))
this.communicationEnabled = false
this.log = this.createLogger()
}
protected abstract createLogger(): Logger
/**
* Removes the message event listener from the {@link window}
*/
@ -91,7 +97,7 @@ export abstract class WindowPostMessageCommunicator<
`Communication isn't enabled. Maybe the other side is not ready?\nMessage was: ${JSON.stringify(message)}`
)
}
console.debug('[WPMC ' + this.generateLogIdentifier() + '] Sent event', message)
this.log.debug('Sent event', message)
this.messageTarget.postMessage(message, this.targetOrigin)
}
@ -106,12 +112,6 @@ export abstract class WindowPostMessageCommunicator<
this.handlers[messageType] = handler as Handler<MESSAGES, RECEIVE_TYPE>
}
/**
* Generates a unique identifier that helps to separate log messages in the console from different communicators.
* @return the identifier
*/
protected abstract generateLogIdentifier(): string
/**
* Receives the message events and calls the handler that is mapped to the correct type.
*
@ -125,7 +125,7 @@ export abstract class WindowPostMessageCommunicator<
if (!handler) {
return true
}
console.debug('[WPMC ' + this.generateLogIdentifier() + '] Received event ', data)
this.log.debug('Received event', data)
handler(data as Extract<MESSAGES, PostMessage<RECEIVE_TYPE>>)
return false
}