added logs list

This commit is contained in:
Nalvazhuthi
2025-05-02 17:14:36 +05:30
parent 66d8196537
commit 4b7a868d1a
15 changed files with 604 additions and 51 deletions

View File

@@ -0,0 +1,77 @@
import React, { createContext, useContext, useState, useCallback } from "react";
export type LogType = "log" | "info" | "warning" | "error";
export interface LogEntry {
id: string;
type: LogType;
message: string;
timestamp: Date;
}
interface LoggerContextValue {
logs: LogEntry[];
setLogs: React.Dispatch<React.SetStateAction<LogEntry[]>>;
isLogListVisible: boolean;
setIsLogListVisible: React.Dispatch<React.SetStateAction<boolean>>;
log: (message: string) => void;
info: (message: string) => void;
warn: (message: string) => void;
error: (message: string) => void;
clear: () => void;
}
const LoggerContext = createContext<LoggerContextValue | undefined>(undefined);
export const LoggerProvider: React.FC<{ children: React.ReactNode }> = ({
children,
}) => {
const [logs, setLogs] = useState<LogEntry[]>([]);
const [isLogListVisible, setIsLogListVisible] = useState<boolean>(false);
const generateId = useCallback(
() => Math.random().toString(36).substring(2, 9),
[]
);
const addLog = useCallback(
(type: LogType, message: string) => {
const newLog: LogEntry = {
id: generateId(),
type,
message,
timestamp: new Date(),
};
setLogs((prevLogs) => [...prevLogs, newLog]);
},
[generateId]
);
const loggerMethods: LoggerContextValue = {
logs,
setLogs,
isLogListVisible,
setIsLogListVisible,
log: (message: string) => addLog("log", message),
info: (message: string) => addLog("info", message),
warn: (message: string) => addLog("warning", message),
error: (message: string) => addLog("error", message),
clear: () => {
setLogs([]);
},
};
return (
<LoggerContext.Provider value={loggerMethods}>
{children}
</LoggerContext.Provider>
);
};
export const useLogger = () => {
const context = useContext(LoggerContext);
if (!context) {
throw new Error("useLogger must be used within a LoggerProvider");
}
return context;
};