Skip to content

Commit

Permalink
Add context to log
Browse files Browse the repository at this point in the history
  • Loading branch information
ekzyis committed Nov 5, 2024
1 parent bef63a7 commit f444308
Show file tree
Hide file tree
Showing 10 changed files with 58 additions and 25 deletions.
13 changes: 7 additions & 6 deletions api/resolvers/wallet.js
Original file line number Diff line number Diff line change
Expand Up @@ -668,14 +668,15 @@ export default injectResolvers(resolvers)

export const walletLogger = ({ wallet, models }) => {
// server implementation of wallet logger interface on client
const log = (level) => async message => {
const log = (level) => async (message, context = {}) => {
try {
await models.walletLog.create({
data: {
userId: wallet.userId,
wallet: wallet.type,
level,
message
message,
context
}
})
} catch (err) {
Expand All @@ -684,10 +685,10 @@ export const walletLogger = ({ wallet, models }) => {
}

return {
ok: (...message) => log('SUCCESS')(message.join(' ')),
info: (...message) => log('INFO')(message.join(' ')),
error: (...message) => log('ERROR')(message.join(' ')),
warn: (...message) => log('WARN')(message.join(' '))
ok: (message, context) => log('SUCCESS')(message, context),
info: (message, context) => log('INFO')(message, context),
error: (message, context) => log('ERROR')(message, context),
warn: (message, context) => log('WARN')(message, context)
}
}

Expand Down
1 change: 1 addition & 0 deletions api/typeDefs/wallet.js
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,7 @@ const typeDefs = `
wallet: ID!
level: String!
message: String!
context: JSONObject
}
`

Expand Down
35 changes: 28 additions & 7 deletions components/log-message.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
import { timeSince } from '@/lib/time'
import styles from './log-message.module.css'
import { Fragment, useState } from 'react'

export default function LogMessage ({ showWallet, wallet, level, message, context, ts }) {
const [show, setShow] = useState(false)

export default function LogMessage ({ showWallet, wallet, level, message, ts }) {
let className
switch (level.toLowerCase()) {
case 'ok':
Expand All @@ -15,12 +18,30 @@ export default function LogMessage ({ showWallet, wallet, level, message, ts })
default:
className = 'text-info'
}

const hasContext = Object.keys(context).length > 0

const handleClick = () => {
if (hasContext) { setShow(show => !show) }
}

const style = hasContext ? { cursor: 'pointer' } : { cursor: 'inherit' }
const indicator = hasContext ? (show ? '-' : '+') : <></>

return (
<tr className={styles.line}>
<td className={styles.timestamp}>{timeSince(new Date(ts))}</td>
{showWallet ? <td className={styles.wallet}>[{wallet}]</td> : <td className='mx-1' />}
<td className={`${styles.level} ${className}`}>{level}</td>
<td>{message}</td>
</tr>
<>
<tr className={styles.line} onClick={handleClick} style={style}>
<td className={styles.timestamp}>{timeSince(new Date(ts))}</td>
{showWallet ? <td className={styles.wallet}>[{wallet}]</td> : <td className='mx-1' />}
<td className={`${styles.level} ${className}`}>{level}</td>
<td>{indicator} {message}</td>
</tr>
{show && hasContext && Object.entries(context).map(([key, value], i) => (
<tr className={styles.line} key={i}>
<td colspan='3'>{key}</td>
<td className='text-break'>{value}</td>
</tr>
))}
</>
)
}
14 changes: 7 additions & 7 deletions components/wallet-logger.js
Original file line number Diff line number Diff line change
Expand Up @@ -104,8 +104,8 @@ function useWalletLogDB () {
export function useWalletLogger (wallet, setLogs) {
const { add, clear, notSupported } = useWalletLogDB()

const appendLog = useCallback(async (wallet, level, message) => {
const log = { wallet: tag(wallet), level, message, ts: +new Date() }
const appendLog = useCallback(async (wallet, level, message, context) => {
const log = { wallet: tag(wallet), level, message, ts: +new Date(), context }
try {
if (notSupported) {
console.log('cannot persist wallet log: indexeddb not supported')
Expand Down Expand Up @@ -150,20 +150,20 @@ export function useWalletLogger (wallet, setLogs) {
}
}, [clear, deleteServerWalletLogs, setLogs, notSupported])

const log = useCallback(level => message => {
const log = useCallback(level => (message, context) => {
if (!wallet) {
// console.error('cannot log: no wallet set')
return
}

appendLog(wallet, level, message)
appendLog(wallet, level, message, context)
console[level !== 'error' ? 'info' : 'error'](`[${tag(wallet)}]`, message)
}, [appendLog, wallet])

const logger = useMemo(() => ({
ok: (...message) => log('ok')(message.join(' ')),
info: (...message) => log('info')(message.join(' ')),
error: (...message) => log('error')(message.join(' '))
ok: (message, context) => log('ok')(message, context),
info: (message, context) => log('info')(message, context),
error: (message, context) => log('error')(message, context)
}), [log])

return { logger, deleteLogs }
Expand Down
1 change: 1 addition & 0 deletions fragments/wallet.js
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,7 @@ export const WALLET_LOGS = gql`
wallet
level
message
context
}
}
}
Expand Down
2 changes: 2 additions & 0 deletions prisma/migrations/20241105021205_log_context/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "WalletLog" ADD COLUMN "context" JSONB;
1 change: 1 addition & 0 deletions prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -245,6 +245,7 @@ model WalletLog {
wallet WalletType
level LogLevel
message String
context Json? @db.JsonB
@@index([userId, createdAt])
}
Expand Down
6 changes: 3 additions & 3 deletions wallets/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -222,13 +222,13 @@ export function useWallet (name) {

const sendPayment = useCallback(async (bolt11) => {
const hash = bolt11Tags(bolt11).payment_hash
logger.info('sending payment:', `payment_hash=${hash}`)
logger.info(`sending payment: payment_hash=${hash}`)
try {
const preimage = await wallet.def.sendPayment(bolt11, wallet.config, { logger })
logger.ok('payment successful:', `payment_hash=${hash}`, `preimage=${preimage}`)
logger.ok(`payment successful: payment_hash=${hash} preimage=${preimage}`)
} catch (err) {
const message = err.message || err.toString?.()
logger.error('payment failed:', `payment_hash=${hash}`, message)
logger.error(`payment failed: payment_hash=${hash} ${message}`)
throw err
}
}, [wallet, logger])
Expand Down
2 changes: 1 addition & 1 deletion wallets/lnc/client.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ async function disconnect (lnc, logger) {
}, 50)
logger.info('disconnected')
} catch (err) {
logger.error('failed to disconnect from lnc', err)
logger.error('failed to disconnect from lnc: ' + err)
}
}
}
Expand Down
8 changes: 7 additions & 1 deletion wallets/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,13 @@ export async function createInvoice (userId, { msats, description, descriptionHa

const bolt11 = await parsePaymentRequest({ request: invoice })

await logger.info(`created invoice for ${formatMsats(bolt11.mtokens)}`)
await logger.info(`created invoice for ${formatMsats(bolt11.mtokens)}`, {
bolt11: invoice,
payment_hash: bolt11.id,
description: bolt11.description,
created_at: bolt11.created_at,
expires_at: bolt11.expires_at
})

if (BigInt(bolt11.mtokens) !== BigInt(msats)) {
if (BigInt(bolt11.mtokens) > BigInt(msats)) {
Expand Down

0 comments on commit f444308

Please sign in to comment.