Skip to content

Improve logging #254

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Apr 12, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions src/actions/utils/loadWatchers.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import * as chokidar from 'chokidar'
import * as vscode from 'vscode'
import { COMMANDS } from '../../editor/commands'
import environment from '../../environment'
import { WORKSPACE_ROOT } from '../../environment'

// NOTE: vscode createFileWatcher doesn't seem to detect changes outside of vscode
// such as `npm install` of a package. Went with chokidar instead
Expand All @@ -26,7 +26,7 @@ const loadWatchers = (watchers: string[]) => {
// see how glob patterns are used in VSCode (not like a regex)
// https://code.visualstudio.com/api/references/vscode-api#GlobPattern
const fsWatcher: chokidar.FSWatcher = chokidar.watch(watcher, {
cwd: environment.WORKSPACE_ROOT,
cwd: WORKSPACE_ROOT,
interval: 1000,
})

Expand Down
2 changes: 1 addition & 1 deletion src/actions/utils/openFiles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ const openFiles = async (files: string[]) => {
// ensure the panel is redrawn on the right side first
vscode.commands.executeCommand(COMMANDS.OPEN_WEBVIEW)
} catch (error) {
console.log(`Failed to open file ${filePath}`, error)
console.log(`Failed to open file ${filePath}: ${error.message}`)
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/actions/utils/runCommands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ const runCommands = async (commands: string[], send: (action: T.Action) => void)
try {
result = await exec(command)
} catch (error) {
console.log(error)
console.log(`Test failed: ${error.message}`)
send({ type: 'COMMAND_FAIL', payload: { process: { ...process, status: 'FAIL' } } })
return
}
Expand Down
11 changes: 7 additions & 4 deletions src/channel/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import { openWorkspace, checkWorkspaceEmpty } from '../services/workspace'
import { readFile } from 'fs'
import { join } from 'path'
import { promisify } from 'util'
import environment from '../environment'
import { WORKSPACE_ROOT } from '../environment'

const readFileAsync = promisify(readFile)

Expand Down Expand Up @@ -45,12 +45,12 @@ class Channel implements Channel {
const actionType: string = typeof action === 'string' ? action : action.type
// const onError = (error: T.ErrorMessage) => this.send({ type: 'ERROR', payload: { error } })

// console.log(`ACTION: ${actionType}`)
logger(`EXT RECEIVED: "${actionType}"`)

switch (actionType) {
case 'EDITOR_STARTUP':
// check if a workspace is open, otherwise nothing works
const noActiveWorksapce = !environment.WORKSPACE_ROOT.length
const noActiveWorksapce = !WORKSPACE_ROOT.length
if (noActiveWorksapce) {
const error: E.ErrorMessage = {
type: 'NoWorkspaceFound',
Expand Down Expand Up @@ -260,7 +260,7 @@ class Channel implements Channel {
})

// log error to console for safe keeping
console.log(`ERROR:\n ${errorMarkdown}`)
logger(`ERROR:\n ${errorMarkdown}`)

if (errorMarkdown) {
// add a clearer error message for the user
Expand All @@ -270,6 +270,9 @@ class Channel implements Channel {

// action may be an object.type or plain string
const actionType: string = typeof action === 'string' ? action : action.type

logger(`EXT TO CLIENT: "${actionType}"`)

switch (actionType) {
case 'TEST_PASS':
const tutorial = this.context.tutorial.get()
Expand Down
33 changes: 15 additions & 18 deletions src/environment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,25 +2,22 @@ require('dotenv').config({
path: './web-app/.env',
})

import * as vscode from 'vscode'
import { getWorkspaceRoot } from './services/workspace'

interface Environment {
VERSION: string
NODE_ENV: string
LOG: boolean
API_URL: string
SENTRY_DSN: string | null
WORKSPACE_ROOT: string
}
// CodeRoad version
export const VERSION: string = process.env.npm_package_version || 'unknown'

const environment: Environment = {
VERSION: process.env.VERSION || 'unknown',
NODE_ENV: process.env.NODE_ENV || 'production',
LOG: (process.env.LOG || '').toLowerCase() === 'true',
API_URL: process.env.REACT_APP_GQL_URI || '',
SENTRY_DSN: process.env.SENTRY_DSN || null,
WORKSPACE_ROOT: getWorkspaceRoot(),
}
// Node env
export type Env = 'test' | 'local' | 'development' | 'production'
// @ts-ignore
export const NODE_ENV: Env = process.env.NODE_ENV || 'production'

export default environment
// toggle logging in development
export const LOG: boolean =
(process.env.REACT_APP_LOG || '').toLowerCase() === 'true' && process.env.NODE_ENV !== 'production'

// error logging tool
export const SENTRY_DSN: string | null = process.env.SENTRY_DSN || null

// uri path to the users project workspace
export const WORKSPACE_ROOT: string = getWorkspaceRoot()
4 changes: 2 additions & 2 deletions src/services/logger/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import enviroment from '../../environment'
import { LOG } from '../../environment'

const logger = (message: string | string[]) => {
if (!enviroment.LOG) {
if (!LOG) {
return
}
if (Array.isArray(message)) {
Expand Down
6 changes: 3 additions & 3 deletions src/services/node/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,16 @@ import { exec as cpExec } from 'child_process'
import * as fs from 'fs'
import { join } from 'path'
import { promisify } from 'util'
import environment from '../../environment'
import { WORKSPACE_ROOT } from '../../environment'

const asyncExec = promisify(cpExec)

export const exec = (cmd: string): Promise<{ stdout: string; stderr: string }> | never => {
return asyncExec(cmd, {
cwd: environment.WORKSPACE_ROOT,
cwd: WORKSPACE_ROOT,
})
}

export const exists = (...paths: string[]): boolean | never => {
return fs.existsSync(join(environment.WORKSPACE_ROOT, ...paths))
return fs.existsSync(join(WORKSPACE_ROOT, ...paths))
}
8 changes: 4 additions & 4 deletions src/services/sentry/init.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { init } from '@sentry/node'
import environment from '../../environment'
import { SENTRY_DSN, NODE_ENV } from '../../environment'

if (environment.SENTRY_DSN) {
if (SENTRY_DSN) {
init({
dsn: environment.SENTRY_DSN,
environment: environment.NODE_ENV,
dsn: SENTRY_DSN,
environment: NODE_ENV,
})
}
4 changes: 2 additions & 2 deletions src/services/sentry/onError.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import * as sentry from '@sentry/node'
// import { Scope } from '@sentry/hub'
import environment from '../../environment'
import { VERSION } from '../../environment'

const onError = (error: Error) => {
// set user scope https://docs.sentry.io/enriching-error-data/scopes/?platform=node
sentry.withScope((scope: any) => {
scope.setTag('VERSION', environment.VERSION)
scope.setTag('VERSION', VERSION)
// if (user) {
// scope.setUser({
// id: user.id,
Expand Down
4 changes: 2 additions & 2 deletions src/services/workspace/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import * as vscode from 'vscode'
import * as fs from 'fs'
import { promisify } from 'util'
import environment from '../../environment'
import { WORKSPACE_ROOT } from '../../environment'

const readDir = promisify(fs.readdir)

Expand All @@ -13,7 +13,7 @@ export const openWorkspace = () => {
export const checkWorkspaceEmpty = async () => {
let files
try {
files = await readDir(environment.WORKSPACE_ROOT)
files = await readDir(WORKSPACE_ROOT)
} catch (error) {
throw new Error('Failed to check workspace')
}
Expand Down
3 changes: 1 addition & 2 deletions src/webview/render.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import { JSDOM } from 'jsdom'
import * as path from 'path'
import * as vscode from 'vscode'
import onError from '../services/sentry/onError'
import environment from '../environment'

const getNonce = (): string => {
let text = ''
Expand Down Expand Up @@ -73,7 +72,7 @@ async function render(panel: vscode.WebviewPanel, rootPath: string) {
cspMeta.content =
[
`default-src 'self'`,
`connect-src https: http: ${environment.API_URL}`,
`connect-src https: http:`,
// @ts-ignore
`font-src ${panel.webview.cspSource} http: https: data:`,
// @ts-ignore
Expand Down
6 changes: 6 additions & 0 deletions web-app/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
SKIP_PREFLIGHT_CHECK=true
VERSION=0.1.0
NODE_ENV=local
REACT_APP_DEBUG=false
REACT_APP_LOG=false
REACT_APP_TUTORIAL_LIST_URL=https://raw.githubusercontent.com/coderoad/tutorials/master/tutorials.json
2 changes: 1 addition & 1 deletion web-app/.storybook/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import '../src/styles/index.css'
// @ts-ignore
global.acquireVsCodeApi = () => ({
postMessage(event: string) {
console.log('postMessage', event)
console.log('ERROR: VSCode did not load properly in CodeRoad extension', event)
},
})

Expand Down
2 changes: 1 addition & 1 deletion web-app/src/components/Error/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ const ErrorMarkdown = ({ error, send }: Props) => {
React.useEffect(() => {
if (error) {
// log error
console.log(error)
console.log(`ERROR in markdown: ${error.message}`)
}
}, [error])

Expand Down
5 changes: 3 additions & 2 deletions web-app/src/components/ErrorBoundary/index.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import * as React from 'react'
import onError from '../../services/sentry/onError'
import logger from '../../services/logger'

class ErrorBoundary extends React.Component {
public state = { errorMessage: null }
Expand All @@ -9,8 +10,8 @@ class ErrorBoundary extends React.Component {
// Display fallback UI
this.setState({ errorMessage: error.message })
// You can also log the error to an error reporting service
console.error(JSON.stringify(error))
console.log(JSON.stringify(info))
logger('ERROR in component:', JSON.stringify(error))
logger('ERROR info:', JSON.stringify(info))
}

public render() {
Expand Down
2 changes: 1 addition & 1 deletion web-app/src/components/Markdown/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ const Markdown = (props: Props) => {
try {
html = md.render(props.children)
} catch (error) {
const message = `failed to parse markdown for ${props.children}`
const message = `Failed to parse markdown for ${props.children}`
onError(new Error(message))
console.log(message)
html = `<div style='background-color: #FFB81A; padding: 0.5rem;'>
Expand Down
21 changes: 12 additions & 9 deletions web-app/src/components/Router/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { createMachine } from '../../services/state/machine'
import { useMachine } from '../../services/xstate-react'
import Route from './Route'
import onError from '../../services/sentry/onError'
import { LOG_STATE } from '../../environment'
import logger from '../../services/logger'

interface Output {
context: T.MachineContext
Expand All @@ -16,27 +16,30 @@ interface Output {
declare let acquireVsCodeApi: any

const editor = acquireVsCodeApi()
const editorSend = (action: T.Action) => {
logger(`CLIENT TO EXT: "${action.type}"`)
return editor.postMessage(action)
}

// router finds first state match of <Route path='' />
const useRouter = (): Output => {
const [state, send] = useMachine<T.MachineContext, any>(createMachine({ editorSend: editor.postMessage }))
const [state, send] = useMachine<T.MachineContext, any>(createMachine({ editorSend }))

if (LOG_STATE) {
console.log(JSON.stringify(state.value))
}
logger(`STATE: ${JSON.stringify(state.value)}`)

// event bus listener
React.useEffect(() => {
const listener = 'message'
// propograte channel event to state machine
const handler = (action: any) => {
const handler = (event: any) => {
// NOTE: must call event.data, cannot destructure. VSCode acts odd
const event = action.data
const action = event.data
// ignore browser events from plugins
if (event.source) {
if (action.source) {
return
}
send(event)
logger(`CLIENT RECEIVED: "${action.type}"`)
send(action)
}
window.addEventListener(listener, handler)
return () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ const LoadTutorialSummary = (props: Props) => {
return <Loading text="Loading tutorial summary..." />
}
if (error) {
console.log(error)
console.log(`Failed to load tutorial summary: ${error}`)
return <div>Error loading summary</div>
}
if (!data) {
Expand Down
3 changes: 2 additions & 1 deletion web-app/src/containers/SelectTutorial/forms/TutorialUrl.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import * as React from 'react'
import { Button, Form, Input } from '@alifd/next'
import logger from '../../../services/logger'

const FormItem = Form.Item

Expand All @@ -12,7 +13,7 @@ const TutorialUrl = (props: Props) => {
const [url, setUrl] = React.useState(props.defaultUrl)
const onSubmit = (e: any) => {
e.preventDefault()
console.log('tutorial url', url)
logger(`Tutorial url: ${url}`)
props.onTutorialLoad(url)
}

Expand Down
3 changes: 2 additions & 1 deletion web-app/src/environment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ for (const required of requiredKeys) {
export const DEBUG: boolean = (process.env.REACT_APP_DEBUG || '').toLowerCase() === 'true'
export const VERSION: string = process.env.VERSION || 'unknown'
export const NODE_ENV: string = process.env.NODE_ENV || 'development'
export const LOG_STATE: boolean = (process.env.REACT_APP_LOG_STATE || '').toLowerCase() === 'true'
export const LOG: boolean =
(process.env.REACT_APP_LOG || '').toLowerCase() === 'true' && process.env.NODE_ENV !== 'production'
export const TUTORIAL_LIST_URL: string = process.env.REACT_APP_TUTORIAL_LIST_URL || ''
export const SENTRY_DSN: string | null = process.env.REACT_APP_SENTRY_DSN || null
2 changes: 1 addition & 1 deletion web-app/src/mock/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ if (!global.acquireVsCodeApi) {
// @ts-ignore
global.acquireVsCodeApi = () => ({
postMessage(event: string) {
console.log('postMessage', event)
console.log('VSCode did not load properly for CodeRoad extension', event)
},
})
}
14 changes: 14 additions & 0 deletions web-app/src/services/logger/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { LOG } from '../../environment'

const logger = (...messages: string[]) => {
if (!LOG) {
return
}
// Inside vscode, you console.log does not allow more than 1 param
// to get around it, we can log with multiple log statements
for (const message of messages) {
console.log(message)
}
}

export default logger
3 changes: 1 addition & 2 deletions web-app/src/services/sentry/init.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,5 @@ try {
})
}
} catch (error) {
console.log('Error in Sentry init')
console.log(error)
console.log(`Error in Sentry init: ${error.message}`)
}