Skip to content

Commit

Permalink
chore: normalize log api and move to dependency injection (openwallet…
Browse files Browse the repository at this point in the history
…-foundation#1138)

Signed-off-by: Jason C. Leach <[email protected]>
  • Loading branch information
jleach authored May 9, 2024
1 parent 8975556 commit e96a7c3
Show file tree
Hide file tree
Showing 11 changed files with 97 additions and 147 deletions.
1 change: 1 addition & 0 deletions packages/legacy/app/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@
"react-native-gifted-chat": "*",
"react-native-keychain": "^8.1.1",
"react-native-localize": "^2.2.4",
"react-native-logs": "^5.1.0",
"react-native-orientation-locker": "^1.6.0",
"react-native-permissions": "^4.0.1",
"react-native-qrcode-svg": "^6.2.0",
Expand Down
49 changes: 23 additions & 26 deletions packages/legacy/core/App/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ import { proofRequestTourSteps } from './components/tour/ProofRequestTourSteps'
import { Container, ContainerProvider } from './container-api'
import { AnimatedComponentsProvider } from './contexts/animated-components'
import { AuthProvider } from './contexts/auth'
import { CommonUtilProvider } from './contexts/commons'
import { ConfigurationProvider } from './contexts/configuration'
import { NetworkProvider } from './contexts/network'
import { StoreProvider } from './contexts/store'
Expand Down Expand Up @@ -49,31 +48,29 @@ function App(sytem: Container) {
<ThemeProvider value={theme}>
<AnimatedComponentsProvider value={animatedComponents}>
<ConfigurationProvider value={defaultConfiguration}>
<CommonUtilProvider>
<AuthProvider>
<NetworkProvider>
<StatusBar
hidden={false}
barStyle="light-content"
backgroundColor={theme.ColorPallet.brand.primary}
translucent={false}
/>
<NetInfo />
<ErrorModal />
<TourProvider
homeTourSteps={homeTourSteps}
credentialsTourSteps={credentialsTourSteps}
credentialOfferTourSteps={credentialOfferTourSteps}
proofRequestTourSteps={proofRequestTourSteps}
overlayColor={'gray'}
overlayOpacity={0.7}
>
<RootStack />
</TourProvider>
<Toast topOffset={15} config={toastConfig} />
</NetworkProvider>
</AuthProvider>
</CommonUtilProvider>
<AuthProvider>
<NetworkProvider>
<StatusBar
hidden={false}
barStyle="light-content"
backgroundColor={theme.ColorPallet.brand.primary}
translucent={false}
/>
<NetInfo />
<ErrorModal />
<TourProvider
homeTourSteps={homeTourSteps}
credentialsTourSteps={credentialsTourSteps}
credentialOfferTourSteps={credentialOfferTourSteps}
proofRequestTourSteps={proofRequestTourSteps}
overlayColor={'gray'}
overlayOpacity={0.7}
>
<RootStack />
</TourProvider>
<Toast topOffset={15} config={toastConfig} />
</NetworkProvider>
</AuthProvider>
</ConfigurationProvider>
</AnimatedComponentsProvider>
</ThemeProvider>
Expand Down
8 changes: 8 additions & 0 deletions packages/legacy/core/App/container-api.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { BaseLogger } from '@credo-ts/core'
import { StackNavigationProp } from '@react-navigation/stack'
import React, { createContext, useContext } from 'react'
import { DependencyContainer } from 'tsyringe'
Expand All @@ -11,6 +12,7 @@ import { AuthenticateStackParams, ScreenOptionsType } from './types/navigators'
export enum PROOF_TOKENS {
GROUP_BY_REFERENT = 'proof.groupByReferant',
}

export enum SCREEN_TOKENS {
SCREEN_PREFACE = 'screen.preface',
SCREEN_TERMS = 'screen.terms',
Expand Down Expand Up @@ -41,6 +43,10 @@ export enum OBJECT_TOKENS {
OBJECT_ONBOARDINGCONFIG = 'object.onboarding-config',
}

export enum UTILITY_TOKENS {
UTIL_LOGGER = 'utility.logger',
}

export const TOKENS = {
...PROOF_TOKENS,
...SCREEN_TOKENS,
Expand All @@ -50,6 +56,7 @@ export const TOKENS = {
...COMP_TOKENS,
...LOAD_STATE_TOKENS,
...OBJECT_TOKENS,
...UTILITY_TOKENS,
}

export type FN_ONBOARDING_DONE = (
Expand All @@ -70,6 +77,7 @@ export interface TokenMapping {
[TOKENS.LOAD_STATE]: FN_LOADSTATE
[TOKENS.COMP_BUTTON]: Button
[TOKENS.OBJECT_ONBOARDINGCONFIG]: ScreenOptionsType
[TOKENS.UTIL_LOGGER]: BaseLogger
}

export interface Container {
Expand Down
5 changes: 3 additions & 2 deletions packages/legacy/core/App/container-impl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import Onboarding from './screens/Onboarding'
import Preface from './screens/Preface'
import ScreenTerms, { TermsVersion } from './screens/Terms'
import { loadLoginAttempt } from './services/keychain'
import { ConsoleLogger } from './services/logger'
import { AuthenticateStackParams, Screens } from './types/navigators'
import {
Migration as MigrationState,
Expand All @@ -23,7 +24,6 @@ import {
Onboarding as StoreOnboardingState,
Tours as ToursState,
} from './types/state'

export class MainContainer implements Container {
public static readonly TOKENS = TOKENS
private container: DependencyContainer
Expand All @@ -39,8 +39,9 @@ export class MainContainer implements Container {
this.container.registerInstance(TOKENS.SCREEN_ONBOARDING, Onboarding)
this.container.registerInstance(TOKENS.STACK_ONBOARDING, OnboardingStack)
this.container.registerInstance(TOKENS.COMP_BUTTON, Button)
this.container.registerInstance(TOKENS.OBJECT_ONBOARDINGCONFIG, DefaultScreenOptionsDictionary)
this.container.registerInstance(TOKENS.GROUP_BY_REFERENT, false)
this.container.registerInstance(TOKENS.OBJECT_ONBOARDINGCONFIG, DefaultScreenOptionsDictionary)
this.container.registerInstance(TOKENS.UTIL_LOGGER, new ConsoleLogger())

this.container.registerInstance(
TOKENS.FN_ONBOARDING_DONE,
Expand Down
35 changes: 0 additions & 35 deletions packages/legacy/core/App/contexts/commons.tsx

This file was deleted.

2 changes: 0 additions & 2 deletions packages/legacy/core/App/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@ import HomeFooterView from './components/views/HomeFooterView'
import indyLedgers from './configs/ledgers/indy'
import * as contexts from './contexts'
import { AuthProvider } from './contexts/auth'
import { CommonUtilProvider } from './contexts/commons'
import { NetworkProvider } from './contexts/network'
import { useTour } from './contexts/tour/tour-context'
import { TourProvider } from './contexts/tour/tour-provider'
Expand Down Expand Up @@ -107,7 +106,6 @@ export {
App,
indyLedgers,
Agent,
CommonUtilProvider,
AgentProvider,
AuthProvider,
NetworkProvider,
Expand Down
5 changes: 3 additions & 2 deletions packages/legacy/core/App/screens/Splash.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Agent, ConsoleLogger, HttpOutboundTransport, LogLevel, WsOutboundTransport } from '@credo-ts/core'
import { Agent, HttpOutboundTransport, WsOutboundTransport } from '@credo-ts/core'
import { useAgent } from '@credo-ts/react-hooks'
import { agentDependencies } from '@credo-ts/react-native'
import { useNavigation } from '@react-navigation/core'
Expand Down Expand Up @@ -96,6 +96,7 @@ const Splash: React.FC = () => {
const container = useContainer()
const [mounted, setMounted] = useState(false)
const { version: TermsVersion } = container.resolve(TOKENS.SCREEN_TERMS)
const logger = container.resolve(TOKENS.UTIL_LOGGER)
const styles = StyleSheet.create({
container: {
flex: 1,
Expand Down Expand Up @@ -220,7 +221,7 @@ const Splash: React.FC = () => {
id: credentials.id,
key: credentials.key,
},
logger: new ConsoleLogger(LogLevel.trace),
logger,
autoUpdateStorageOnStartup: true,
},
dependencies: agentDependencies,
Expand Down
118 changes: 47 additions & 71 deletions packages/legacy/core/App/services/logger.ts
Original file line number Diff line number Diff line change
@@ -1,86 +1,62 @@
/* eslint-disable no-console,@typescript-eslint/no-explicit-any */

export enum LogLevel {
test = 0,
trace = 1,
debug = 2,
info = 3,
warn = 4,
error = 5,
fatal = 6,
off = 7,
}
import { BaseLogger } from '@credo-ts/core'
import { consoleTransport, logger } from 'react-native-logs'

export class ConsoleLogger extends BaseLogger {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private log: any
private config = {
levels: {
test: 0,
trace: 0,
debug: 0,
info: 1,
warn: 2,
error: 3,
fatal: 4,
},
severity: 'debug',
async: true,
dateFormat: 'time',
printDate: false,
}

export interface Logger {
logLevel: LogLevel
public constructor() {
super()

test(message: string, data?: Record<string, any>): void
trace(message: string, data?: Record<string, any>): void
debug(message: string, data?: Record<string, any>): void
info(message: string, data?: Record<string, any>): void
warn(message: string, data?: Record<string, any>): void
error(message: string, data?: Record<string, any>): void
fatal(message: string, data?: Record<string, any>): void
}
const transport = [consoleTransport]
const config = {
...this.config,
transport,
}

const replaceError = (_: unknown, value: unknown) => {
if (value instanceof Error) {
const newValue = Object.getOwnPropertyNames(value).reduce(
(obj, propName) => {
obj[propName] = (value as unknown as Record<string, unknown>)[propName]
return obj
},
{ name: value.name } as Record<string, unknown>
)
return newValue
this.log = logger.createLogger<'test' | 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'fatal'>(config)
}

return value
}

export class AppConsoleLogger {
public logLevel: LogLevel

// Map our log levels to console levels
private consoleLogMap = {
[LogLevel.test]: 'log',
[LogLevel.trace]: 'log',
[LogLevel.debug]: 'debug',
[LogLevel.info]: 'info',
[LogLevel.warn]: 'warn',
[LogLevel.error]: 'error',
[LogLevel.fatal]: 'error',
} as const
public test(message: string, data?: object | undefined): void {
this.log?.test(message, data)
}

public constructor(logLevel: LogLevel = LogLevel.off) {
this.logLevel = logLevel
public trace(message: string, data?: object | undefined): void {
this.log?.trace(message, data)
}

public log(level: Exclude<LogLevel, LogLevel.off>, message: string, data?: Record<string, any>): void {
// Get console method from mapping
const consoleLevel = this.consoleLogMap[level]
public debug(message: string, data?: object | undefined): void {
this.log?.debug(message, data)
}

// Get logger prefix from log level names in enum
const prefix = LogLevel[level].toUpperCase()
public info(message: string, data?: object | undefined): void {
this.log?.info(message, data)
}

// Return early if logging is not enabled for this level
if (!this.isEnabled(level)) {
console.log('logger disabled')
return
}
public warn(message: string, data?: object | undefined): void {
this.log?.warn(message, data)
}

// Log, with or without data
if (data) {
console[consoleLevel](
`${prefix}: ${new Date().toISOString()} - ${message}`,
JSON.stringify(data, replaceError, 2)
)
} else {
console[consoleLevel](`${prefix}: ${new Date().toISOString()} - ${message}`)
}
public error(message: string, data?: object | undefined): void {
this.log?.error(message, data)
}

private isEnabled(logLevel: LogLevel) {
return logLevel >= this.logLevel
public fatal(message: string, data?: object | undefined): void {
this.log?.fatal(message, data)
}
}
1 change: 1 addition & 0 deletions packages/legacy/core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,7 @@
"react-native-gifted-chat": "*",
"react-native-keychain": "^8.1.1",
"react-native-localize": "^2.2.4",
"react-native-logs": "^5.1.0",
"react-native-orientation-locker": "*",
"react-native-permissions": "^4.0.1",
"react-native-qrcode-svg": "^6.2.0",
Expand Down
6 changes: 3 additions & 3 deletions packages/remote-logs/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@
"eslint-import-resolver-typescript": "^2.5.0",
"react": "18.2.0",
"react-native": "0.72.5",
"react-native-logs": "^5.0.1",
"react-native-logs": "^5.1.0",
"rimraf": "^5.0.0",
"typescript": "^5.0.4"
},
Expand All @@ -50,6 +50,6 @@
"buffer": "^6.0.3",
"react": "^18.2.0",
"react-native": "^0.72.5",
"react-native-logs": "^5.0.1"
"react-native-logs": "^5.1.0"
}
}
}
Loading

0 comments on commit e96a7c3

Please sign in to comment.