Last active
December 5, 2020 22:11
-
-
Save hobroker/e6d248030a0226cf561989a0310e0c87 to your computer and use it in GitHub Desktop.
logs stuff prefixed with the path from where the function was called
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import debug from 'debug'; | |
import { | |
bind, | |
filter, | |
identity, | |
join, | |
memoizeWith, | |
nthArg, | |
pipe, | |
slice, | |
split, | |
unapply, | |
} from 'ramda'; | |
const BASE_PREFIX = 'app'; | |
const notIncluded = array => value => !array.includes(value); | |
const getErrorStack = () => { | |
const orig = Error.prepareStackTrace; | |
Error.prepareStackTrace = nthArg(1); | |
const error = new Error(); | |
Error.captureStackTrace(error, getErrorStack); | |
const errStack = error.stack; | |
Error.prepareStackTrace = orig; | |
return errStack; | |
}; | |
const shortenPathname = pipe( | |
slice(0, -3), | |
split('/'), | |
filter(notIncluded(['util'])), | |
slice(-2, Infinity), | |
filter(notIncluded(['index', 'src'])), | |
join(':'), | |
); | |
export const getCallerPathname = (idx = 2) => { | |
const pathname = getErrorStack()[idx].getFileName(); | |
return shortenPathname(pathname); | |
}; | |
const baseDebug = debug(BASE_PREFIX); | |
const extend = bind(baseDebug.extend, baseDebug); | |
const createDebug = ex => { | |
const logWithKey = memoizeWith(identity, key => ex(key)); | |
const log = key => args => { | |
const logKey = key || getCallerPathname(3); | |
logWithKey(logKey)(...args); | |
return args[0]; | |
}; | |
const fn = unapply(log()); | |
fn.lazy = (...args) => { | |
const sublog = log(getCallerPathname(2)); | |
return () => { | |
return sublog(args); | |
}; | |
}; | |
return fn; | |
}; | |
export const debugIt = createDebug(extend); | |
export default createDebug; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment