Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -204,11 +204,11 @@ async function setupProject(projectPath: string) {
enabled: true,
},
vars: {
LOG_LEVEL: "DEBUG",
LOG_TARGET: "1",
LOG_TIMESTAMP: "1",
_RIVETKIT_ERROR_STACK: "1",
_RIVETKIT_LOG_MESSAGE: "1",
RIVETKIT_LOG_LEVEL: "DEBUG",
RIVETKIT_LOG_TARGET: "1",
RIVETKIT_LOG_TIMESTAMP: "1",
RIVETKIT_LOG_ERROR_STACK: "1",
RIVETKIT_LOG_MESSAGE: "1",
},
};
await fs.writeFile(
Expand Down
51 changes: 22 additions & 29 deletions rivetkit-typescript/packages/rivetkit/src/client/actor-conn.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,7 @@ import type { CloseEvent } from "ws";
import type { AnyActorDefinition } from "@/actor/definition";
import { inputDataToBuffer } from "@/actor/protocol/old";
import { type Encoding, jsonStringifyCompat } from "@/actor/protocol/serde";
import {
HEADER_CONN_PARAMS,
HEADER_ENCODING,
PATH_CONNECT,
} from "@/common/actor-router-consts";
import { importEventSource } from "@/common/eventsource";
import type {
UniversalErrorEvent,
UniversalEventSource,
UniversalMessageEvent,
} from "@/common/eventsource-interface";
import { PATH_CONNECT } from "@/common/actor-router-consts";
import { assertUnreachable, stringifyError } from "@/common/utils";
import type { UniversalWebSocket } from "@/common/websocket-interface";
import type { ManagerDriver } from "@/driver-helpers/mod";
Expand All @@ -32,17 +22,9 @@ import {
type ToServer as ToServerJson,
ToServerSchema,
} from "@/schemas/client-protocol-zod/mod";
import {
deserializeWithEncoding,
encodingIsBinary,
serializeWithEncoding,
} from "@/serde";
import {
bufferToArrayBuffer,
httpUserAgent,
promiseWithResolvers,
} from "@/utils";
import { getRivetkitLogMessage } from "@/utils/env-vars";
import { deserializeWithEncoding, serializeWithEncoding } from "@/serde";
import { bufferToArrayBuffer, promiseWithResolvers } from "@/utils";
import { getLogMessage } from "@/utils/env-vars";
import type { ActorDefinitionActions } from "./actor-common";
import { queryActor } from "./actor-query";
import { ACTOR_CONNS_SYMBOL, type ClientRaw } from "./client";
Expand All @@ -62,7 +44,11 @@ import {
* - `"connected"`: Connection is active
* - `"disconnected"`: Connection was lost, will auto-reconnect
*/
export type ActorConnStatus = "idle" | "connecting" | "connected" | "disconnected";
export type ActorConnStatus =
| "idle"
| "connecting"
| "connected"
| "disconnected";

interface ActionInFlight {
name: string;
Expand Down Expand Up @@ -298,8 +284,7 @@ enc

// Notify close handlers (only if transitioning from Connected to Disconnected or Idle)
if (
(status === "disconnected" ||
status === "idle") &&
(status === "disconnected" || status === "idle") &&
prevStatus === "connected"
) {
for (const handler of [...this.#closeHandlers]) {
Expand Down Expand Up @@ -425,7 +410,9 @@ enc
#handleOnOpen() {
// Connection was disposed before Init message arrived - close the websocket to avoid leak
if (this.#disposed) {
logger().debug({ msg: "handleOnOpen called after dispose, closing websocket" });
logger().debug({
msg: "handleOnOpen called after dispose, closing websocket",
});
if (this.#websocket) {
this.#websocket.close(1000, "Disposed");
this.#websocket = undefined;
Expand Down Expand Up @@ -479,7 +466,7 @@ enc

const response = await this.#parseMessage(data as ConnMessage);
logger().trace(
getRivetkitLogMessage()
getLogMessage()
? {
msg: "parsed message",
message:
Expand Down Expand Up @@ -611,7 +598,10 @@ enc

// Automatically reconnect if we were connected
if (wasConnected) {
logger().debug({ msg: "triggering reconnect", connId: this.#connId });
logger().debug({
msg: "triggering reconnect",
connId: this.#connId,
});
this.#connectWithRetry();
}
}
Expand Down Expand Up @@ -1097,7 +1087,10 @@ enc
// Close websocket (#handleOnClose will reject pending promises)
if (this.#websocket) {
const ws = this.#websocket;
if (ws.readyState !== 2 /* CLOSING */ && ws.readyState !== 3 /* CLOSED */) {
if (
ws.readyState !== 2 /* CLOSING */ &&
ws.readyState !== 3 /* CLOSED */
) {
const { promise, resolve } = promiseWithResolvers();
ws.addEventListener("close", () => resolve(undefined));
ws.close(1000, "Disposed");
Expand Down
14 changes: 3 additions & 11 deletions rivetkit-typescript/packages/rivetkit/src/common/log.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,9 +43,7 @@ export function getPinoLevel(logLevel?: LogLevel): LevelWithSilent {
return configuredLogLevel;
}

const raw = (getLogLevel() || "warn")
.toString()
.toLowerCase();
const raw = (getLogLevel() || "warn").toString().toLowerCase();

const parsed = LogLevelSchema.safeParse(raw);
if (parsed.success) {
Expand Down Expand Up @@ -129,10 +127,7 @@ export function configureDefaultLogger(logLevel?: LogLevel) {
return { level: number };
},
},
timestamp:
getLogTimestamp()
? stdTimeFunctions.epochTime
: false,
timestamp: getLogTimestamp() ? stdTimeFunctions.epochTime : false,
browser: {
write: {
fatal: customWrite.bind(null, "fatal"),
Expand All @@ -156,10 +151,7 @@ export function configureDefaultLogger(logLevel?: LogLevel) {
60: "fatal",
};
const levelName = levelMap[level] || "info";
const time =
getLogTimestamp()
? Date.now()
: undefined;
const time = getLogTimestamp() ? Date.now() : undefined;

// Get bindings from the logger instance (child logger fields)
const bindings = (this as any).bindings?.() || {};
Expand Down
4 changes: 2 additions & 2 deletions rivetkit-typescript/packages/rivetkit/src/common/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import {
} from "@/schemas/client-protocol-zod/mod";
import { encodingIsBinary, serializeWithEncoding } from "@/serde";
import { bufferToArrayBuffer, VERSION } from "@/utils";
import { getRivetLogHeaders } from "@/utils/env-vars";
import { getLogHeaders } from "@/utils/env-vars";
import { getLogger, type Logger } from "./log";
import { deconstructError, stringifyError } from "./utils";

Expand All @@ -46,7 +46,7 @@ export function loggerMiddleware(logger: Logger) {
reqSize: c.req.header("content-length"),
resSize: c.res.headers.get("content-length"),
userAgent: c.req.header("user-agent"),
...(getRivetLogHeaders()
...(getLogHeaders()
? { allHeaders: JSON.stringify(c.req.header()) }
: {}),
});
Expand Down
4 changes: 2 additions & 2 deletions rivetkit-typescript/packages/rivetkit/src/common/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import type { Next } from "hono";
import type { ContentfulStatusCode } from "hono/utils/http-status";
import * as errors from "@/actor/errors";
import { EXTRA_ERROR_LOG, VERSION } from "@/utils";
import { getRivetkitErrorStack } from "@/utils/env-vars";
import { getLogErrorStack } from "@/utils/env-vars";
import type { Logger } from "./log";

export function assertUnreachable(x: never): never {
Expand Down Expand Up @@ -301,7 +301,7 @@ export function stringifyError(error: unknown): string {
if (error instanceof Error) {
if (
typeof process !== "undefined" &&
getRivetkitErrorStack()
getLogErrorStack()
) {
return `${error.name}: ${error.message}${error.stack ? `\n${error.stack}` : ""}`;
} else {
Expand Down
20 changes: 10 additions & 10 deletions rivetkit-typescript/packages/rivetkit/src/utils/env-vars.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,24 +27,24 @@ export const getRivetRunnerKind = (): string | undefined =>
getEnvUniversal("RIVET_RUNNER_KIND");

// RivetKit configuration
export const getRivetkitLogMessage = (): boolean =>
!!getEnvUniversal("_RIVETKIT_LOG_MESSAGE");
export const getRivetkitInspectorToken = (): string | undefined =>
getEnvUniversal("RIVETKIT_INSPECTOR_TOKEN");
export const getRivetkitInspectorDisable = (): boolean =>
!!getEnvUniversal("RIVETKIT_INSPECTOR_DISABLE");
export const getRivetkitErrorStack = (): boolean =>
getEnvUniversal("_RIVETKIT_ERROR_STACK") === "1";
getEnvUniversal("RIVETKIT_INSPECTOR_DISABLE") === "1";

// Logging configuration
export const getLogLevel = (): string | undefined =>
getEnvUniversal("LOG_LEVEL");
getEnvUniversal("RIVETKIT_LOG_LEVEL");
export const getLogTarget = (): boolean =>
getEnvUniversal("LOG_TARGET") === "1";
getEnvUniversal("RIVETKIT_LOG_TARGET") === "1";
export const getLogTimestamp = (): boolean =>
getEnvUniversal("LOG_TIMESTAMP") === "1";
export const getRivetLogHeaders = (): boolean =>
!!getEnvUniversal("_RIVET_LOG_HEADERS");
getEnvUniversal("RIVETKIT_LOG_TIMESTAMP") === "1";
export const getLogMessage = (): boolean =>
getEnvUniversal("RIVETKIT_LOG_MESSAGE") === "1";
export const getLogErrorStack = (): boolean =>
getEnvUniversal("RIVETKIT_LOG_ERROR_STACK") === "1";
export const getLogHeaders = (): boolean =>
getEnvUniversal("RIVETKIT_LOG_HEADERS") === "1";

// Environment configuration
export const getNodeEnv = (): string | undefined => getEnvUniversal("NODE_ENV");
Expand Down
10 changes: 5 additions & 5 deletions vitest.base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,11 @@ export default {
},
env: {
// Enable logging
LOG_LEVEL: "DEBUG",
LOG_TARGET: "1",
LOG_TIMESTAMP: "1",
_RIVETKIT_ERROR_STACK: "1",
_RIVETKIT_LOG_MESSAGE: "1",
RIVETKIT_LOG_LEVEL: "DEBUG",
RIVETKIT_LOG_TARGET: "1",
RIVETKIT_LOG_TIMESTAMP: "1",
RIVETKIT_LOG_ERROR_STACK: "1",
RIVETKIT_LOG_MESSAGE: "1",
},
},
} satisfies ViteUserConfig;
2 changes: 1 addition & 1 deletion website/src/content/docs/general/architecture.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ actor definitions include the following generic parameters that you'll see frequ
- rivet uses pino for logging
- we expose a scoped child logger for each actor at `c.log` that automatically logs the actor id + key
- this allows you to search lgos easily by actor id without having to log the actor id frequently
- logs can be configured via the `LOG_LEVEL` env var
- logs can be configured via the `RIVETKIT_LOG_LEVEL` env var

### fault tolerance

Expand Down
11 changes: 7 additions & 4 deletions website/src/content/docs/general/logging.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -54,13 +54,16 @@ You can configure logging behavior using environment variables:

| Variable | Description | Values | Default |
| -------- | ----------- | ------ | ------- |
| `LOG_LEVEL` | Sets the minimum log level to display | `trace`, `debug`, `info`, `warn`, `error`, `fatal`, `silent` | `warn` |
| `LOG_TARGET` | Include the module name that logged the message | `1` to enable, `0` to disable | `0` |
| `LOG_TIMESTAMP` | Include timestamp in log output | `1` to enable, `0` to disable | `0` |
| `RIVETKIT_LOG_LEVEL` | Sets the minimum log level to display | `trace`, `debug`, `info`, `warn`, `error`, `fatal`, `silent` | `warn` |
| `RIVETKIT_LOG_TARGET` | Include the module name that logged the message | `1` to enable, `0` to disable | `0` |
| `RIVETKIT_LOG_TIMESTAMP` | Include timestamp in log output | `1` to enable, `0` to disable | `0` |
| `RIVETKIT_LOG_MESSAGE` | Enable detailed message logging for debugging | `1` to enable, `0` to disable | `0` |
| `RIVETKIT_LOG_ERROR_STACK` | Include stack traces in error output | `1` to enable, `0` to disable | `0` |
| `RIVETKIT_LOG_HEADERS` | Log HTTP headers in requests | `1` to enable, `0` to disable | `0` |

Example:
```bash
LOG_LEVEL=debug LOG_TARGET=1 LOG_TIMESTAMP=1 node server.js
RIVETKIT_LOG_LEVEL=debug RIVETKIT_LOG_TARGET=1 RIVETKIT_LOG_TIMESTAMP=1 node server.js
```

### Log Level
Expand Down
Loading