Created
February 2, 2024 09:15
-
-
Save netgfx/3062c5b5fdd85ff0df03e83c3f4f9199 to your computer and use it in GitHub Desktop.
typescript logger
This file contains 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
/* modification of the logger https://github.com/mohitagrawal1305/nextjs-custom-logger/blob/main/helpers/logger.js */ | |
/* typescript and small fix for nextjs usage */ | |
/* use on your layout.tsx or high level provider | |
* declare global { | |
* interface Window { | |
* logger: any; | |
* } | |
* } | |
* useEffect(() => { | |
* window['logger'] = logger; | |
* }, []); | |
*/ | |
// actual logger code // | |
declare global { | |
var areLogsEnabled: boolean | undefined; | |
} | |
const logger = (() => { | |
const checkIfLogsEnabled = (): boolean => { | |
if (typeof window !== undefined) { | |
const search = global?.window?.location?.search; | |
const enabled = search && new URLSearchParams(search).get('debug') === 'true'; | |
global.areLogsEnabled = enabled || false; | |
return global.areLogsEnabled; | |
} | |
return false; | |
}; | |
const isDev = process.env.NODE_ENV !== 'production'; | |
const print = (type: string, ...messages: any[]) => { | |
if (typeof global.areLogsEnabled === 'undefined') { | |
checkIfLogsEnabled(); | |
} | |
if (global.areLogsEnabled || isDev) { | |
switch (type) { | |
case 'info': | |
console.info('%c Custom Log:', 'background: blue; color: white;', ...messages); | |
break; | |
case 'warn': | |
console.warn('%c Custom Log:', 'background: orange; color: white;', ...messages); | |
break; | |
case 'error': | |
console.error('%c Custom Log:', 'background: red; color: white;', ...messages); | |
break; | |
case 'trace': | |
console.trace('%c Custom Log:', 'background: grey; color: black;', ...messages); | |
break; | |
case 'debug': | |
default: | |
console.log('%c Custom Log:', 'background: green; color: white;', ...messages); | |
} | |
} | |
}; | |
return { | |
debug: print.bind(null, 'debug'), | |
info: print.bind(null, 'info'), | |
warn: print.bind(null, 'warn'), | |
error: print.bind(null, 'error'), | |
trace: print.bind(null, 'trace'), | |
}; | |
})(); | |
export default logger; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment