Skip to content

Commit

Permalink
feat(browser): fancier logs
Browse files Browse the repository at this point in the history
  • Loading branch information
pooya parsa committed May 26, 2019
1 parent 630b8f1 commit b64f337
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 17 deletions.
4 changes: 2 additions & 2 deletions examples/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
</head>
<body>
Open developer tools to see the magic!
<script src="../dist/consola.browser.js"></script>
<script>
<script type="module">
import consola from '../src/browser.js'
consola.level = 5

consola.wrapAll()
Expand Down
4 changes: 2 additions & 2 deletions examples/index.module.html → examples/index.legacy.html
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
</head>
<body>
Open developer tools to see the magic!
<script type="module">
import consola from '../src/browser.js'
<script src="../dist/consola.browser.js"></script>
<script>
consola.level = 5

consola.wrapAll()
Expand Down
36 changes: 23 additions & 13 deletions src/reporters/browser.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,16 @@
import { TYPE_COLOR_MAP, LEVEL_COLOR_MAP } from '../utils/fancy.js'

export default class BrowserReporter {
constructor (options) {
this.options = Object.assign({}, options)

this.defaultColor = '#7f8c8d' // Gray
this.levelColorMap = {
0: '#c0392b', // Red
1: '#f39c12', // Yellow
3: '#00BCD4' // Cyan
}
this.typeColorMap = {
success: '#2ecc71' // Green
}
}

log (logObj) {
Expand All @@ -13,24 +21,26 @@ export default class BrowserReporter {
: logObj.level === 1 && console.warn ? (console.__warn || console.warn) : (console.__log || console.log)

// Type
const type = logObj.type !== 'log' ? `[${logObj.type.toUpperCase()}]` : ''
const type = logObj.type !== 'log' ? logObj.type.toLowerCase() : ''

// Tag
const tag = logObj.tag ? `[${logObj.tag.toUpperCase()}]` : ''

// Date
const date = `[${new Date(logObj.date).toLocaleTimeString()}]`
const tag = logObj.tag ? logObj.tag.toLowerCase() : ''

// Styles
const color = TYPE_COLOR_MAP[logObj.type] || LEVEL_COLOR_MAP[logObj.level]
const styleColor = `color: ${color}; background-color: inherit;`
const styleGrey = `color: ${logObj.additionalColor || 'grey'}; background-color: inherit;`

const color = this.typeColorMap[logObj.type] || this.levelColorMap[logObj.level] || this.defaultColor
const style = `
background: ${color};
border-radius: 0.5em;
color: white;
font-weight: bold;
padding: 2px 0.5em;
`

// Log to the console
consoleLogFn(
'%c' + date + tag + '%c' + type,
styleGrey,
styleColor,
'%c' + tag + (tag ? ':' : '') + type,
style,
...logObj.args
)
}
Expand Down

0 comments on commit b64f337

Please sign in to comment.