|
| 1 | +// Credits: borrowed code from fcomb/redux-logger |
| 2 | + |
| 3 | +export default function createLogger ({ |
| 4 | + collapsed = true, |
| 5 | + transformer = state => state, |
| 6 | + mutationTransformer = mut => mut |
| 7 | +} = {}) { |
| 8 | + return store => { |
| 9 | + let prevState = JSON.parse(JSON.stringify(store.state)) |
| 10 | + |
| 11 | + store.subscribe((mutation, state) => { |
| 12 | + if (typeof console === 'undefined') { |
| 13 | + return |
| 14 | + } |
| 15 | + const nextState = JSON.parse(JSON.stringify(state)) |
| 16 | + const time = new Date() |
| 17 | + const formattedTime = ` @ ${pad(time.getHours(), 2)}:${pad(time.getMinutes(), 2)}:${pad(time.getSeconds(), 2)}.${pad(time.getMilliseconds(), 3)}` |
| 18 | + const formattedMutation = mutationTransformer(mutation) |
| 19 | + const message = `mutation ${mutation.type}${formattedTime}` |
| 20 | + const startMessage = collapsed |
| 21 | + ? console.groupCollapsed |
| 22 | + : console.group |
| 23 | + |
| 24 | + // render |
| 25 | + try { |
| 26 | + startMessage.call(console, message) |
| 27 | + } catch (e) { |
| 28 | + console.log(message) |
| 29 | + } |
| 30 | + |
| 31 | + console.log('%c prev state', 'color: #9E9E9E; font-weight: bold', prevState) |
| 32 | + console.log('%c mutation', 'color: #03A9F4; font-weight: bold', formattedMutation) |
| 33 | + console.log('%c next state', 'color: #4CAF50; font-weight: bold', nextState) |
| 34 | + |
| 35 | + try { |
| 36 | + console.groupEnd() |
| 37 | + } catch (e) { |
| 38 | + console.log('—— log end ——') |
| 39 | + } |
| 40 | + |
| 41 | + prevState = nextState |
| 42 | + }) |
| 43 | + } |
| 44 | +} |
| 45 | + |
| 46 | +function repeat (str, times) { |
| 47 | + return (new Array(times + 1)).join(str) |
| 48 | +} |
| 49 | + |
| 50 | +function pad (num, maxLength) { |
| 51 | + return repeat('0', maxLength - num.toString().length) + num |
| 52 | +} |
0 commit comments