Skip to content

Instantly share code, notes, and snippets.

@hanipcode
Last active February 7, 2025 06:40
Show Gist options
  • Save hanipcode/ed2a4267c14c5be761b9e7b889bcaec3 to your computer and use it in GitHub Desktop.
Save hanipcode/ed2a4267c14c5be761b9e7b889bcaec3 to your computer and use it in GitHub Desktop.
import { $Values } from "utility-types";
const LEVEL = {
info: "info",
debug: "debug",
warning: "warning",
error: "error",
} as const;
type LEVEL_TYPE = $Values<typeof LEVEL>;
interface ILogOutput {
level: LEVEL_TYPE;
timestamp: Date;
message: string;
platform: "server" | "web";
metadata: unknown;
context: unknown;
stack?: unknown;
}
const LogFn = {
info: console.info,
debug: console.log,
warning: console.warn,
error: console.error,
} as const satisfies Record<LEVEL_TYPE, typeof console.log>;
const LogContext = {} as Record<string, unknown>;
const getPlatform = () => {
let platform: "server" | "web" = "server";
if (typeof window !== "undefined") {
platform = "web";
}
return platform;
};
const createLogger =
(level: LEVEL_TYPE) =>
(message: string, metadata: unknown = {}) => {
// if platform web, and production, don't output anything
const platform = getPlatform();
if (platform === "web") {
if (
!window.location.href.includes("localhost")
) {
return;
}
console.group(`[LOG][${level}] ${message}`);
console.log("time", new Date());
console.log("platform", platform);
console.log("level", level);
console.log("message", message);
console.log("metadata", metadata);
console.log("context", LogContext);
console.groupEnd();
return;
}
LogFn[level](
JSON.stringify({
message,
metadata,
level,
platform,
timestamp: new Date(),
context: LogContext,
} satisfies ILogOutput),
);
};
const createErrorLogger =
() =>
(error: Error, metadata: Record<string, unknown> = {}) => {
// if platform web, and production, don't output anything
const platform = getPlatform();
if (platform === "web") {
if (
!window.location.href.includes("localhost")
) {
return;
}
console.error(error);
console.group(`[LOG][error] ${error.message}`);
console.log("time", new Date());
console.log("platform", platform);
console.log("level", "error");
console.log("message", error.message);
console.log("stack", error.stack);
console.log("metadata", metadata);
console.log("context", LogContext);
console.groupEnd();
return;
}
console.error(
JSON.stringify({
message: error.message,
context: LogContext,
metadata,
stack: error.stack,
platform,
level: "error",
timestamp: new Date(),
} satisfies ILogOutput),
);
};
const addContext = (key: string, value: unknown) => {
LogContext[key] = value;
};
const Logger = {
info: createLogger(LEVEL.info),
debug: createLogger(LEVEL.debug),
warning: createLogger(LEVEL.warning),
error: createErrorLogger(),
addContext,
} as const;
export { Logger };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment