Use nicer logger to prefix console logs
This commit is contained in:
		
							parent
							
								
									5b042a77e2
								
							
						
					
					
						commit
						5677fb180f
					
				| @ -28,7 +28,6 @@ const InsertedLabel = ({ label }: InsertedLabelProps) => ( | |||||||
| export const OrderableList = ({ onChange, items, insertLabels }: Props): JSX.Element => { | export const OrderableList = ({ onChange, items, insertLabels }: Props): JSX.Element => { | ||||||
|   const updateOrder = useCallback( |   const updateOrder = useCallback( | ||||||
|     (sourceIndex: number, targetIndex: number) => { |     (sourceIndex: number, targetIndex: number) => { | ||||||
|       console.log("updateOrder"); |  | ||||||
|       onChange?.(arrayMove(items, sourceIndex, targetIndex)); |       onChange?.(arrayMove(items, sourceIndex, targetIndex)); | ||||||
|     }, |     }, | ||||||
|     [items, onChange] |     [items, onChange] | ||||||
|  | |||||||
| @ -11,8 +11,10 @@ import { | |||||||
| import { LocalDataFile } from "graphql/fetchLocalData"; | import { LocalDataFile } from "graphql/fetchLocalData"; | ||||||
| import { internalAtoms } from "contexts/atoms"; | import { internalAtoms } from "contexts/atoms"; | ||||||
| import { processLanguages, processCurrencies, processLangui } from "helpers/localData"; | import { processLanguages, processCurrencies, processLangui } from "helpers/localData"; | ||||||
|  | import { getLogger } from "helpers/logger"; | ||||||
| 
 | 
 | ||||||
| const getFileName = (name: LocalDataFile): string => `/local-data/${name}.json`; | const getFileName = (name: LocalDataFile): string => `/local-data/${name}.json`; | ||||||
|  | const logger = getLogger("💽 [Local Data]"); | ||||||
| 
 | 
 | ||||||
| export const useLocalData = (): void => { | export const useLocalData = (): void => { | ||||||
|   const setLanguages = useAtomSetter(internalAtoms.localData.languages); |   const setLanguages = useAtomSetter(internalAtoms.localData.languages); | ||||||
| @ -28,22 +30,22 @@ export const useLocalData = (): void => { | |||||||
|   ); |   ); | ||||||
| 
 | 
 | ||||||
|   useEffect(() => { |   useEffect(() => { | ||||||
|     console.log("[useLocalData] Refresh languages"); |     logger.log("Refresh languages"); | ||||||
|     setLanguages(processLanguages(rawLanguages)); |     setLanguages(processLanguages(rawLanguages)); | ||||||
|   }, [rawLanguages, setLanguages]); |   }, [rawLanguages, setLanguages]); | ||||||
| 
 | 
 | ||||||
|   useEffect(() => { |   useEffect(() => { | ||||||
|     console.log("[useLocalData] Refresh currencies"); |     logger.log("Refresh currencies"); | ||||||
|     setCurrencies(processCurrencies(rawCurrencies)); |     setCurrencies(processCurrencies(rawCurrencies)); | ||||||
|   }, [rawCurrencies, setCurrencies]); |   }, [rawCurrencies, setCurrencies]); | ||||||
| 
 | 
 | ||||||
|   useEffect(() => { |   useEffect(() => { | ||||||
|     console.log("[useLocalData] Refresh langui"); |     logger.log("Refresh langui"); | ||||||
|     setLangui(processLangui(rawLangui, locale)); |     setLangui(processLangui(rawLangui, locale)); | ||||||
|   }, [locale, rawLangui, setLangui]); |   }, [locale, rawLangui, setLangui]); | ||||||
| 
 | 
 | ||||||
|   useEffect(() => { |   useEffect(() => { | ||||||
|     console.log("[useLocalData] Refresh fallback langui"); |     logger.log("Refresh fallback langui"); | ||||||
|     setFallbackLangui(processLangui(rawLangui, "en")); |     setFallbackLangui(processLangui(rawLangui, "en")); | ||||||
|   }, [rawLangui, setFallbackLangui]); |   }, [rawLangui, setFallbackLangui]); | ||||||
| }; | }; | ||||||
|  | |||||||
| @ -84,7 +84,6 @@ export const useSettings = (): void => { | |||||||
|   useEffect(() => { |   useEffect(() => { | ||||||
|     if (preferredLanguages.length === 0) { |     if (preferredLanguages.length === 0) { | ||||||
|       if (isDefinedAndNotEmpty(router.locale) && router.locales) { |       if (isDefinedAndNotEmpty(router.locale) && router.locales) { | ||||||
|         console.log(router.locale, getDefaultPreferredLanguages(router.locale, router.locales)); |  | ||||||
|         setPreferredLanguages(getDefaultPreferredLanguages(router.locale, router.locales)); |         setPreferredLanguages(getDefaultPreferredLanguages(router.locale, router.locales)); | ||||||
|       } |       } | ||||||
|     } else if (router.locale !== preferredLanguages[0]) { |     } else if (router.locale !== preferredLanguages[0]) { | ||||||
|  | |||||||
| @ -5,15 +5,17 @@ import { config } from "dotenv"; | |||||||
| import { getReadySdk } from "./sdk"; | import { getReadySdk } from "./sdk"; | ||||||
| import { LocalDataGetWebsiteInterfacesQuery } from "./generated"; | import { LocalDataGetWebsiteInterfacesQuery } from "./generated"; | ||||||
| import { processLangui, Langui } from "helpers/localData"; | import { processLangui, Langui } from "helpers/localData"; | ||||||
|  | import { getLogger } from "helpers/logger"; | ||||||
| 
 | 
 | ||||||
| config({ path: resolve(process.cwd(), ".env.local") }); | config({ path: resolve(process.cwd(), ".env.local") }); | ||||||
| 
 | 
 | ||||||
| const LOCAL_DATA_FOLDER = `${process.cwd()}/public/local-data`; | const LOCAL_DATA_FOLDER = `${process.cwd()}/public/local-data`; | ||||||
|  | const logger = getLogger("💽 [Local Data]"); | ||||||
| 
 | 
 | ||||||
| const writeLocalData = (name: LocalDataFile, localData: unknown) => { | const writeLocalData = (name: LocalDataFile, localData: unknown) => { | ||||||
|   const path = `${LOCAL_DATA_FOLDER}/${name}.json`; |   const path = `${LOCAL_DATA_FOLDER}/${name}.json`; | ||||||
|   writeFileSync(path, JSON.stringify(localData), { encoding: "utf-8" }); |   writeFileSync(path, JSON.stringify(localData), { encoding: "utf-8" }); | ||||||
|   console.log(`${path} has been written!`); |   logger.log(`${name}.json has been written`); | ||||||
| }; | }; | ||||||
| 
 | 
 | ||||||
| const readLocalData = <T>(name: LocalDataFile): T => { | const readLocalData = <T>(name: LocalDataFile): T => { | ||||||
|  | |||||||
| @ -3,8 +3,10 @@ import { createWriteStream } from "fs"; | |||||||
| import { parse, TYPE } from "@formatjs/icu-messageformat-parser"; | import { parse, TYPE } from "@formatjs/icu-messageformat-parser"; | ||||||
| import { getLangui } from "./fetchLocalData"; | import { getLangui } from "./fetchLocalData"; | ||||||
| import { filterDefined } from "helpers/asserts"; | import { filterDefined } from "helpers/asserts"; | ||||||
|  | import { getLogger } from "helpers/logger"; | ||||||
| 
 | 
 | ||||||
| const OUTPUT_FOLDER = `${process.cwd()}/src/graphql`; | const OUTPUT_FOLDER = `${process.cwd()}/src/graphql`; | ||||||
|  | const logger = getLogger("💽 [ICU to TS]"); | ||||||
| 
 | 
 | ||||||
| const icuToTypescript = () => { | const icuToTypescript = () => { | ||||||
|   // eslint-disable-next-line @typescript-eslint/no-unused-vars
 |   // eslint-disable-next-line @typescript-eslint/no-unused-vars
 | ||||||
| @ -45,7 +47,7 @@ const icuToTypescript = () => { | |||||||
| 
 | 
 | ||||||
|   output.write("}\n"); |   output.write("}\n"); | ||||||
| 
 | 
 | ||||||
|   console.log(`${OUTPUT_FOLDER}/icu-params.ts has been written!`); |   logger.log(`icu-params.ts has been written!`); | ||||||
| }; | }; | ||||||
| 
 | 
 | ||||||
| if (process.argv[2] === "--icu") { | if (process.argv[2] === "--icu") { | ||||||
|  | |||||||
| @ -1,10 +1,14 @@ | |||||||
|  | import { getLogger } from "helpers/logger"; | ||||||
|  | 
 | ||||||
|  | const logger = getLogger("📊 [Analytics]"); | ||||||
|  | 
 | ||||||
| export const sendAnalytics = (category: string, event: string): void => { | export const sendAnalytics = (category: string, event: string): void => { | ||||||
|   const eventName = `[${category}] ${event}`; |   const eventName = `[${category}] ${event}`; | ||||||
|   console.log(`Event: ${eventName}`); |   logger.log(eventName); | ||||||
|   try { |   try { | ||||||
|     umami(eventName); |     umami(eventName); | ||||||
|   } catch (error) { |   } catch (error) { | ||||||
|     if (error instanceof ReferenceError) return; |     if (error instanceof ReferenceError) return; | ||||||
|     console.log(error); |     logger.error(error); | ||||||
|   } |   } | ||||||
| }; | }; | ||||||
|  | |||||||
| @ -5,9 +5,7 @@ import { isDefined, isDefinedAndNotEmpty } from "helpers/asserts"; | |||||||
| import { getLangui } from "graphql/fetchLocalData"; | import { getLangui } from "graphql/fetchLocalData"; | ||||||
| 
 | 
 | ||||||
| type WordingKey = keyof ICUParams; | type WordingKey = keyof ICUParams; | ||||||
| 
 |  | ||||||
| type LibraryItemType = Exclude<LibraryItemMetadataDynamicZone["__typename"], undefined>; | type LibraryItemType = Exclude<LibraryItemMetadataDynamicZone["__typename"], undefined>; | ||||||
| 
 |  | ||||||
| type ContentStatus = "Done" | "Draft" | "Incomplete" | "Review"; | type ContentStatus = "Done" | "Draft" | "Incomplete" | "Review"; | ||||||
| 
 | 
 | ||||||
| const componentMetadataToWording: Record<LibraryItemType, WordingKey> = { | const componentMetadataToWording: Record<LibraryItemType, WordingKey> = { | ||||||
| @ -58,7 +56,13 @@ export const getFormat = ( | |||||||
|     if (isDefinedAndNotEmpty(result)) { |     if (isDefinedAndNotEmpty(result)) { | ||||||
|       return result; |       return result; | ||||||
|     } |     } | ||||||
|     return new IntlMessageFormat(fallbackLangui[key] ?? "").format(processedValues).toString(); |     const fallback = new IntlMessageFormat(fallbackLangui[key] ?? "") | ||||||
|  |       .format(processedValues) | ||||||
|  |       .toString(); | ||||||
|  |     if (isDefinedAndNotEmpty(fallback)) { | ||||||
|  |       return fallback; | ||||||
|  |     } | ||||||
|  |     return key; | ||||||
|   }; |   }; | ||||||
| 
 | 
 | ||||||
|   const formatLibraryItemType = (metadata: { __typename: LibraryItemType }): string => |   const formatLibraryItemType = (metadata: { __typename: LibraryItemType }): string => | ||||||
|  | |||||||
							
								
								
									
										13
									
								
								src/helpers/logger.ts
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										13
									
								
								src/helpers/logger.ts
									
									
									
									
									
										Normal file
									
								
							| @ -0,0 +1,13 @@ | |||||||
|  | // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
 | ||||||
|  | export const getLogger = (prefix: string) => ({ | ||||||
|  |   error: (message?: unknown, ...optionalParams: unknown[]) => | ||||||
|  |     console.error(prefix, message, ...optionalParams), | ||||||
|  |   warn: (message?: unknown, ...optionalParams: unknown[]) => | ||||||
|  |     console.warn(prefix, message, ...optionalParams), | ||||||
|  |   log: (message?: unknown, ...optionalParams: unknown[]) => | ||||||
|  |     console.log(prefix, message, ...optionalParams), | ||||||
|  |   info: (message?: unknown, ...optionalParams: unknown[]) => | ||||||
|  |     console.info(prefix, message, ...optionalParams), | ||||||
|  |   debug: (message?: unknown, ...optionalParams: unknown[]) => | ||||||
|  |     console.debug(prefix, message, ...optionalParams), | ||||||
|  | }); | ||||||
| @ -5,11 +5,12 @@ import { useAtomGetter } from "helpers/atoms"; | |||||||
| import { LibraryItemMetadataDynamicZone } from "graphql/generated"; | import { LibraryItemMetadataDynamicZone } from "graphql/generated"; | ||||||
| import { ICUParams } from "graphql/icuParams"; | import { ICUParams } from "graphql/icuParams"; | ||||||
| import { isDefined, isDefinedAndNotEmpty } from "helpers/asserts"; | import { isDefined, isDefinedAndNotEmpty } from "helpers/asserts"; | ||||||
|  | import { getLogger } from "helpers/logger"; | ||||||
|  | 
 | ||||||
|  | const logger = getLogger("🗺️ [I18n]"); | ||||||
| 
 | 
 | ||||||
| type WordingKey = keyof ICUParams; | type WordingKey = keyof ICUParams; | ||||||
| 
 |  | ||||||
| type LibraryItemType = Exclude<LibraryItemMetadataDynamicZone["__typename"], undefined>; | type LibraryItemType = Exclude<LibraryItemMetadataDynamicZone["__typename"], undefined>; | ||||||
| 
 |  | ||||||
| export type ContentStatus = "Done" | "Draft" | "Incomplete" | "Review"; | export type ContentStatus = "Done" | "Draft" | "Incomplete" | "Review"; | ||||||
| 
 | 
 | ||||||
| const componentMetadataToWording: Record<LibraryItemType, WordingKey> = { | const componentMetadataToWording: Record<LibraryItemType, WordingKey> = { | ||||||
| @ -59,12 +60,17 @@ export const useFormat = (): { | |||||||
|       if (isDefinedAndNotEmpty(result)) { |       if (isDefinedAndNotEmpty(result)) { | ||||||
|         return result; |         return result; | ||||||
|       } |       } | ||||||
|  |       logger.warn( | ||||||
|  |         `Missing ${langui.ui_language?.data?.attributes?.code} translation for ${key}. \ | ||||||
|  | Falling back to en translation.` | ||||||
|  |       ); | ||||||
|       const fallback = new IntlMessageFormat(fallbackLangui[key] ?? "") |       const fallback = new IntlMessageFormat(fallbackLangui[key] ?? "") | ||||||
|         .format(processedValues) |         .format(processedValues) | ||||||
|         .toString(); |         .toString(); | ||||||
|       if (isDefinedAndNotEmpty(fallback)) { |       if (isDefinedAndNotEmpty(fallback)) { | ||||||
|         return fallback; |         return fallback; | ||||||
|       } |       } | ||||||
|  |       logger.warn(`Missing fallback translation for ${key}. The key seems unvalid`); | ||||||
|       return key; |       return key; | ||||||
|     }, |     }, | ||||||
|     [langui, fallbackLangui] |     [langui, fallbackLangui] | ||||||
|  | |||||||
| @ -4,6 +4,9 @@ import { useIsClient } from "usehooks-ts"; | |||||||
| import { useOnScroll } from "./useOnScroll"; | import { useOnScroll } from "./useOnScroll"; | ||||||
| import { isDefined, isUndefined } from "helpers/asserts"; | import { isDefined, isUndefined } from "helpers/asserts"; | ||||||
| import { Ids } from "types/ids"; | import { Ids } from "types/ids"; | ||||||
|  | import { getLogger } from "helpers/logger"; | ||||||
|  | 
 | ||||||
|  | const logger = getLogger("⛒ [Intersection List]"); | ||||||
| 
 | 
 | ||||||
| export const useIntersectionList = (ids: string[]): number => { | export const useIntersectionList = (ids: string[]): number => { | ||||||
|   const [currentIntersection, setCurrentIntersection] = useState(-1); |   const [currentIntersection, setCurrentIntersection] = useState(-1); | ||||||
| @ -14,7 +17,7 @@ export const useIntersectionList = (ids: string[]): number => { | |||||||
| 
 | 
 | ||||||
|   const refreshCurrentIntersection = useCallback( |   const refreshCurrentIntersection = useCallback( | ||||||
|     (scroll: number) => { |     (scroll: number) => { | ||||||
|       console.log("useIntersectionList"); |       logger.debug("Recalculating intersection"); | ||||||
| 
 | 
 | ||||||
|       if (isUndefined(contentPanel)) { |       if (isUndefined(contentPanel)) { | ||||||
|         setCurrentIntersection(-1); |         setCurrentIntersection(-1); | ||||||
|  | |||||||
| @ -1,6 +1,9 @@ | |||||||
| import { useEffect } from "react"; | import { useEffect } from "react"; | ||||||
| import { useIsClient } from "usehooks-ts"; | import { useIsClient } from "usehooks-ts"; | ||||||
| import { isDefined } from "helpers/asserts"; | import { isDefined } from "helpers/asserts"; | ||||||
|  | import { getLogger } from "helpers/logger"; | ||||||
|  | 
 | ||||||
|  | const logger = getLogger("📏 [Resize Observer]"); | ||||||
| 
 | 
 | ||||||
| export const useOnResize = ( | export const useOnResize = ( | ||||||
|   id: string, |   id: string, | ||||||
| @ -9,7 +12,7 @@ export const useOnResize = ( | |||||||
|   const isClient = useIsClient(); |   const isClient = useIsClient(); | ||||||
| 
 | 
 | ||||||
|   useEffect(() => { |   useEffect(() => { | ||||||
|     console.log("[useOnResize]", id); |     logger.log(`Creating observer for ${id}`); | ||||||
|     const elem = isClient ? document.querySelector(`#${id}`) : null; |     const elem = isClient ? document.querySelector(`#${id}`) : null; | ||||||
|     const ro = new ResizeObserver((resizeObserverEntry) => { |     const ro = new ResizeObserver((resizeObserverEntry) => { | ||||||
|       const entry = resizeObserverEntry[0]; |       const entry = resizeObserverEntry[0]; | ||||||
|  | |||||||
| @ -2,8 +2,11 @@ import { useRouter } from "next/router"; | |||||||
| import { useEffect, useState } from "react"; | import { useEffect, useState } from "react"; | ||||||
| import { useCounter } from "usehooks-ts"; | import { useCounter } from "usehooks-ts"; | ||||||
| import { isDefined } from "helpers/asserts"; | import { isDefined } from "helpers/asserts"; | ||||||
|  | import { getLogger } from "helpers/logger"; | ||||||
| 
 | 
 | ||||||
| const NUM_RETRIES = 10; | const NUM_RETRIES = 10; | ||||||
|  | const DELAY_BETWEEN_RETRY = 200; | ||||||
|  | const logger = getLogger("↕️ [Scroll Into View]"); | ||||||
| 
 | 
 | ||||||
| export const useScrollIntoView = (): void => { | export const useScrollIntoView = (): void => { | ||||||
|   const router = useRouter(); |   const router = useRouter(); | ||||||
| @ -18,14 +21,14 @@ export const useScrollIntoView = (): void => { | |||||||
|           if (hash !== "") { |           if (hash !== "") { | ||||||
|             const element = document.getElementById(hash); |             const element = document.getElementById(hash); | ||||||
|             if (isDefined(element)) { |             if (isDefined(element)) { | ||||||
|               console.log(`[useScrollIntoView] ${hash} found`); |               logger.log(`#${hash} found`); | ||||||
|               element.scrollIntoView(); |               element.scrollIntoView(); | ||||||
|               setHasReachedElem(true); |               setHasReachedElem(true); | ||||||
|             } else { |             } else { | ||||||
|               console.log(`[useScrollIntoView] ${hash} not found`); |               logger.warn(`#${hash} not found, retrying in ${DELAY_BETWEEN_RETRY} ms`); | ||||||
|               setTimeout(() => { |               setTimeout(() => { | ||||||
|                 increment(); |                 increment(); | ||||||
|               }, 200); |               }, DELAY_BETWEEN_RETRY); | ||||||
|             } |             } | ||||||
|           } |           } | ||||||
|         } |         } | ||||||
|  | |||||||
| @ -1,10 +1,16 @@ | |||||||
| import { DependencyList, useEffect } from "react"; | import { DependencyList, useEffect } from "react"; | ||||||
|  | import { getLogger } from "helpers/logger"; | ||||||
| import { Ids } from "types/ids"; | import { Ids } from "types/ids"; | ||||||
| 
 | 
 | ||||||
|  | const logger = getLogger("⬆️ [Scroll Top On Change]"); | ||||||
|  | 
 | ||||||
| // Scroll to top of element "id" when "deps" update.
 | // Scroll to top of element "id" when "deps" update.
 | ||||||
| export const useScrollTopOnChange = (id: Ids, deps: DependencyList, enabled = true): void => { | export const useScrollTopOnChange = (id: Ids, deps: DependencyList, enabled = true): void => { | ||||||
|   useEffect(() => { |   useEffect(() => { | ||||||
|     if (enabled) document.querySelector(`#${id}`)?.scrollTo({ top: 0, behavior: "smooth" }); |     if (enabled) { | ||||||
|  |       logger.log("Change detected. Scrolling to top"); | ||||||
|  |       document.querySelector(`#${id}`)?.scrollTo({ top: 0, behavior: "smooth" }); | ||||||
|  |     } | ||||||
|     // eslint-disable-next-line react-hooks/exhaustive-deps
 |     // eslint-disable-next-line react-hooks/exhaustive-deps
 | ||||||
|   }, [id, ...deps, enabled]); |   }, [id, ...deps, enabled]); | ||||||
| }; | }; | ||||||
|  | |||||||
		Loading…
	
	
			
			x
			
			
		
	
		Reference in New Issue
	
	Block a user
	 DrMint
						DrMint