import { Writable } from "node:stream";
import { multistream, pino } from "pino";
import { build as pinoPretty } from "pino-pretty";
import { emitToOtel } from "./telemetry/pino_otel_transport.js";
const LOGGER_KEY = Symbol.for("@livekit/agents:logger");
const LOGGER_OPTIONS_KEY = Symbol.for("@livekit/agents:loggerOptions");
const OTEL_ENABLED_KEY = Symbol.for("@livekit/agents:otelEnabled");
const globals = globalThis;
const loggerOptions = () => globals[LOGGER_OPTIONS_KEY];
const log = () => {
  const logger = globals[LOGGER_KEY];
  if (!logger) {
    throw new TypeError("logger not initialized. did you forget to run initializeLogger()?");
  }
  return logger;
};
const createLogger = ({ pretty, level }) => {
  const logLevel = level || "info";
  const streams = [
    { stream: pretty ? pinoPretty({ colorize: true }) : process.stdout, level: logLevel },
    { stream: new OtelDestination(), level: "debug" }
  ];
  return pino(
    { level: logLevel, serializers: { error: pino.stdSerializers.err } },
    multistream(streams)
  );
};
const initializeLogger = ({ pretty, level }) => {
  globals[LOGGER_OPTIONS_KEY] = { pretty, level };
  globals[LOGGER_KEY] = createLogger({ pretty, level });
};
class OtelDestination extends Writable {
  _write(chunk, _encoding, callback) {
    try {
      if (!globals[OTEL_ENABLED_KEY]) {
        callback();
        return;
      }
      const line = chunk.toString().trim();
      if (line) {
        const logObj = JSON.parse(line);
        emitToOtel(logObj);
      }
    } catch {
    }
    callback();
  }
}
const enableOtelLogging = () => {
  if (globals[OTEL_ENABLED_KEY] || !globals[LOGGER_KEY]) {
    console.warn("OTEL logging already enabled or logger not initialized");
    return;
  }
  globals[OTEL_ENABLED_KEY] = true;
};
export {
  enableOtelLogging,
  initializeLogger,
  log,
  loggerOptions
};
//# sourceMappingURL=log.js.map