Skip to content

Commit

Permalink
feat(logging): improve logging, especially for errors (#56)
Browse files Browse the repository at this point in the history
  • Loading branch information
Kent C. Dodds authored May 18, 2017
1 parent 9029593 commit d0345e1
Show file tree
Hide file tree
Showing 8 changed files with 224 additions and 10 deletions.
46 changes: 46 additions & 0 deletions .github/ISSUE_TEMPLATE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
<!--
Thanks for your interest in the project. I appreciate bugs filed and PRs submitted!
Please make sure that you are familiar with and follow the Code of Conduct for
this project (found in the CODE_OF_CONDUCT.md file).
Please fill out this template with all the relevant information so we can
understand what's going on and fix the issue.
I'll probably ask you to submit the fix (after giving some direction). If you've
never done that before, that's great! Check this free short video tutorial to
learn how: http://kcd.im/pull-request
-->

- `prettier-eslint-cli` version:
- `prettier` version:
- `eslint` version:

Relevant code/config.

```javascript

```

What you did:



What happened:

<!-- Please provide the full error message/screenshots/anything -->

Reproduction:

<!--
Please reproduce your issue by forking this repository:
https://github.com/kentcdodds/prettier-eslint-cli-repro
with as minimal amount of code possible. Then paste a link below:
-->

-- paste your link here --

Problem description:



Suggested solution:
27 changes: 27 additions & 0 deletions .github/PULL_REQUEST_TEMPLATE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<!--
Thanks for your interest in the project. I appreciate bugs filed and PRs submitted!
Please make sure that you are familiar with and follow the Code of Conduct for
this project (found in the CODE_OF_CONDUCT.md file).
Also, please make sure you're familiar with and follow the instructions in the
contributing guidelines (found in the CONTRIBUTING.md file).
If you're new to contributing to open source projects, you might find this free
video course helpful: http://kcd.im/pull-request
Please fill out the information below to expedite the review and (hopefully)
merge of your pull request!
-->

<!-- What changes are being made? (What feature/bug is being fixed here?) -->
**What**:

<!-- Why are these changes necessary? -->
**Why**:

<!-- How were these changes implemented? -->
**How**:


<!-- feel free to add additional comments -->
17 changes: 17 additions & 0 deletions src/__snapshots__/uncaught-exception-handler.test.js.snap
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`logs a check for trace 1`] = `
"There has been an unknown error when running the prettier-eslint CLI. If it's unclear to you what went wrong, then try this:
✅ Run the script again with the LOG_LEVEL environment variable set to \\"trace\\"
2. Search existing issues on GitHub: https://github.com/prettier/prettier-eslint-cli/issues?utf8=%E2%9C%93&q=my%20error
3. Make a minimal reproduction in a totally separate repository. You can fork this one: https://github.com/kentcdodds/prettier-eslint-cli-repro
4. Post an issue with a link to your reproduction to the issues on GitHub: https://github.com/prettier/prettier-eslint-cli/issues/new"
`;

exports[`logs all options 1`] = `
"There has been an unknown error when running the prettier-eslint CLI. If it's unclear to you what went wrong, then try this:
1. Run the script again with the LOG_LEVEL environment variable set to \\"trace\\"
2. Search existing issues on GitHub: https://github.com/prettier/prettier-eslint-cli/issues?utf8=%E2%9C%93&q=my%20error
3. Make a minimal reproduction in a totally separate repository. You can fork this one: https://github.com/kentcdodds/prettier-eslint-cli-repro
4. Post an issue with a link to your reproduction to the issues on GitHub: https://github.com/prettier/prettier-eslint-cli/issues/new"
`;
4 changes: 4 additions & 0 deletions src/add-exception-handler.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
/* istanbul ignore-next */
import onUncaughtException from './uncaught-exception-handler'

process.on('uncaughtException', onUncaughtException)
9 changes: 8 additions & 1 deletion src/index.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,15 @@
#!/usr/bin/env node

// eslint-disable-next-line import/no-unassigned-import
import './add-exception-handler' // want to do this first
import getLogger from 'loglevel-colored-level-prefix'
import parser from './parser'
import formatFiles from './format-files'

const argv = parser.parse(process.argv.slice(2))
const logger = getLogger({prefix: 'prettier-eslint-cli'})
const args = process.argv.slice(2)

logger.trace('Parsing args: ', args)
const argv = parser.parse(args)

formatFiles(argv)
31 changes: 22 additions & 9 deletions src/parser.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import path from 'path'
import getLogger from 'loglevel-colored-level-prefix'
import findUp from 'find-up'
import yargs from 'yargs'
import {oneLine} from 'common-tags'
Expand All @@ -7,6 +8,8 @@ import camelcaseKeys from 'camelcase-keys'
import chalk from 'chalk'
import boolify from 'boolify'

const logger = getLogger({prefix: 'prettier-eslint-cli'})

const parser = yargs
.usage('Usage: $0 <globs>... [--option-1 option-1-value --option-2]')
.help('h')
Expand Down Expand Up @@ -40,10 +43,10 @@ const parser = yargs
},
ignore: {
describe: oneLine`
pattern(s) you wish to ignore
(can be used multiple times
and includes **/node_modules/** automatically)
`,
pattern(s) you wish to ignore
(can be used multiple times
and includes **/node_modules/** automatically)
`,
coerce: arrify,
},
'log-level': {
Expand All @@ -59,9 +62,10 @@ const parser = yargs
},
prettier: {
describe: oneLine`
Prettier configuration options
to be passed to prettier-eslint
using dot-notation`,
Prettier configuration options
to be passed to prettier-eslint
using dot-notation
`,
},
// TODO: if we allow people to to specify a config path,
// we need to read that somehow. These can come invarious
Expand All @@ -78,8 +82,10 @@ const parser = yargs
} else {
throw Error(
chalk.red(
oneLine`You should use dot-notation with
the --prettier flag, for example, --prettier.singleQuote`,
oneLine`
You should use dot-notation with
the --prettier flag, for example, --prettier.singleQuote
`,
),
)
}
Expand All @@ -89,11 +95,18 @@ const parser = yargs
export default parser

function getPathInHostNodeModules(module) {
logger.debug(`Looking for a local installation of the module "${module}"`)
const modulePath = findUp.sync(`node_modules/${module}`)

if (modulePath) {
return modulePath
}
logger.debug(
oneLine`
Local installation of "${module}" not found,
looking again starting in "${__dirname}"
`,
)

return findUp.sync(`node_modules/${module}`, {cwd: __dirname})
}
Expand Down
42 changes: 42 additions & 0 deletions src/uncaught-exception-handler.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import {oneLine, oneLineTrim} from 'common-tags'
import getLogger from 'loglevel-colored-level-prefix'

const logger = getLogger({prefix: 'prettier-eslint-cli'})

export default onUncaughtException

function onUncaughtException(err) {
const level = logger.getLevel()
const isTrace = level === 0
const traceResolution = oneLine`
Run the script again with the LOG_LEVEL
environment variable set to "trace"
`
const resolutionSteps = [
`${isTrace ? '✅ ' : '1.'} ${traceResolution}`,
oneLine`
2. Search existing issues on GitHub:
${oneLineTrim`
https://github.com/prettier/prettier-eslint-cli/issues
?utf8=%E2%9C%93&q=${encodeURIComponent(err.message)}
`}
`,
oneLine`
3. Make a minimal reproduction in a totally separate repository.
You can fork this one:
https://github.com/kentcdodds/prettier-eslint-cli-repro
`,
oneLine`
4. Post an issue with a link to your reproduction to the issues
on GitHub: https://github.com/prettier/prettier-eslint-cli/issues/new
`,
].join('\n ')
logger.error(
oneLine`
There has been an unknown error when running the prettier-eslint CLI.
If it's unclear to you what went wrong, then try this:
`,
`\n ${resolutionSteps}`,
)
throw err
}
58 changes: 58 additions & 0 deletions src/uncaught-exception-handler.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import getLoggerMock from 'loglevel-colored-level-prefix'
import onUncaughtException from './uncaught-exception-handler'

jest.mock('loglevel-colored-level-prefix', () => {
const logger = {}
const __mock__ = {logger, level: 4, resetAll}
const getLogger = jest.fn(() => resetAll())
getLogger.__mock__ = __mock__
return getLogger

function resetAll() {
getLogger.mockClear()
Object.assign(logger, {
getLevel: jest.fn(() => getLogger.__mock__.level),
trace: jest.fn(),
debug: jest.fn(),
info: jest.fn(),
warn: jest.fn(),
error: jest.fn(),
})
return logger
}
})

beforeEach(() => {
getLoggerMock.__mock__.resetAll()
})

test('logs all options', () => {
const logger = getLoggerMock()
runWithCatch(new Error('my error'))
expect(logger.error).toHaveBeenCalledTimes(1)
const errorLog = logger.error.mock.calls[0].join(' ')
expect(errorLog).toMatchSnapshot()
})

test('logs a check for trace', () => {
getLoggerMock.__mock__.level = 0
const logger = getLoggerMock()
runWithCatch(new Error('my error'))
expect(logger.error).toHaveBeenCalledTimes(1)
const errorLog = logger.error.mock.calls[0].join(' ')
expect(errorLog).toContain('✅')
expect(errorLog).toMatchSnapshot()
})

test('re-throws the given error', () => {
const myError = new Error('my error')
expect(() => onUncaughtException(myError)).toThrow(myError)
})

function runWithCatch(...args) {
try {
onUncaughtException(...args)
} catch (e) {
// ignore
}
}

0 comments on commit d0345e1

Please sign in to comment.