Skip to content

Commit

Permalink
feat: added new Logger apis
Browse files Browse the repository at this point in the history
  • Loading branch information
Vali-98 committed Nov 30, 2024
1 parent 802f72c commit 62863fc
Showing 1 changed file with 85 additions and 1 deletion.
86 changes: 85 additions & 1 deletion constants/Logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,29 @@ import { AppSettings, Global } from './GlobalValues'
import { mmkv } from './MMKV'

export namespace Logger {
const maxloglength = 100
const toastTime = 2000

export enum LogLevel {
INFO,
WARN,
ERROR,
DEBUG,
}

const LevelName: Record<LogLevel, string> = {
[LogLevel.INFO]: '[INFO]',
[LogLevel.WARN]: '[WARN]',
[LogLevel.ERROR]: '[ERROR]',
[LogLevel.DEBUG]: '[DEBUG]',
}

type Log = {
timestamp: string
message: string
level: LogLevel
}

const maxloglength = 300

const getLogs = () => {
return JSON.parse(mmkv.getString(Global.Logs) ?? '[]')
Expand Down Expand Up @@ -34,4 +56,66 @@ export namespace Logger {
export const flushLogs = () => {
mmkv.set(Global.Logs, '[]')
}

// new api

const insertLogs = (data: Log) => {
const logs = getLogs()
logs.push(data)
if (logs.length > maxloglength) logs.shift()
mmkv.set(Global.Logs, JSON.stringify(logs))
}

const createLog = (data: string, level: LogLevel): Log => {
const timestamp = `[${new Date().toTimeString().substring(0, 8)}]`
return { timestamp: timestamp, message: data, level: level }
}

const printLog = (log: Log) => {
console.log(`${LevelName[log.level]}${log.timestamp}: ${log.message}`)
}

export const info = (data: string) => {
const logItem = createLog(data, LogLevel.INFO)
printLog(logItem)
insertLogs(logItem)
}

export const infoToast = (data: string) => {
info(data)
Toast.show(data, toastTime)
}

export const warn = (data: string) => {
const logItem = createLog(data, LogLevel.WARN)
printLog(logItem)
insertLogs(logItem)
}

export const warnToast = (data: string) => {
warn(data)
Toast.show(data, toastTime)
}

export const error = (data: string) => {
const logItem = createLog(data, LogLevel.ERROR)
printLog(logItem)
insertLogs(logItem)
}

export const errorToast = (data: string) => {
error(data)
Toast.show(data, toastTime)
}

export const newDebug = (data: string) => {
const logItem = createLog(data, LogLevel.DEBUG)
printLog(logItem)
insertLogs(logItem)
}

export const debugToast = (data: string) => {
error(data)
Toast.show(data, toastTime)
}
}

0 comments on commit 62863fc

Please sign in to comment.