Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

2.2 KB
Raw Blame
/* Copyright 2026 Marimo. All rights reserved. */
/* oxlint-disable no-console -- For console logging */

import { Functions } from "./functions";

declare global {
  interface Window {
    Logger?: ILogger;
  }
}

interface ILogger {
  debug: (typeof console)["debug"];
  log: (typeof console)["log"];
  warn: (typeof console)["warn"];
  error: (typeof console)["error"];
  trace: (typeof console)["trace"];
  get: (namespace: string) => ILogger;
  disabled: (disabled?: boolean) => ILogger;
}

const createNamespacedLogger = (
  namespace: string,
  baseLogger: ILogger,
): ILogger => {
  const prefix = `[${namespace}]`;
  return {
    debug: (...args) => console.debug(prefix, ...args),
    log: (...args) => baseLogger.log(prefix, ...args),
    warn: (...args) => baseLogger.warn(prefix, ...args),
    error: (...args) => baseLogger.error(prefix, ...args),
    trace: (...args) => baseLogger.trace(prefix, ...args),
    get: (subNamespace: string) =>
      createNamespacedLogger(`${namespace}:${subNamespace}`, baseLogger),
    disabled: (disabled = true) => {
      if (disabled) {
        return DisabledLogger;
      }
      return baseLogger;
    },
  };
};

/**
 * Wrapper around console.log that can be used to disable logging in production or add additional logging.
 */
const ConsoleLogger: ILogger = {
  debug: (...args) => {
    console.debug(...args);
  },
  log: (...args) => {
    console.log(...args);
  },
  warn: (...args) => {
    console.warn(...args);
  },
  error: (...args) => {
    console.error(...args);
  },
  trace: (...args) => {
    console.trace(...args);
  },
  get: (namespace: string) =>
    createNamespacedLogger(`marimo:${namespace}`, ConsoleLogger),
  disabled: (disabled = true) => {
    if (disabled) {
      return DisabledLogger;
    }
    return ConsoleLogger;
  },
};

const DisabledLogger: ILogger = {
  debug: () => Functions.NOOP,
  log: () => Functions.NOOP,
  warn: () => Functions.NOOP,
  error: () => Functions.NOOP,
  trace: () => Functions.NOOP,
  get: () => DisabledLogger,
  disabled: () => DisabledLogger,
};

function getLogger(): ILogger {
  if (typeof window !== "undefined") {
    return window.Logger || ConsoleLogger;
  }
  return ConsoleLogger;
}

export const Logger = getLogger();