Skip to content

Commit

Permalink
feat: add stream logger
Browse files Browse the repository at this point in the history
  • Loading branch information
kitsonk committed Jul 19, 2024
1 parent 5616d15 commit ad4ce55
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 8 deletions.
38 changes: 31 additions & 7 deletions logger.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
// Copyright 2018-2024 the oak authors. All rights reserved.

import {
type BaseHandler,
BaseHandler,
type BaseHandlerOptions,
ConsoleHandler,
type FormatterFunction,
getLogger as gl,
Expand Down Expand Up @@ -82,6 +83,29 @@ const formatter: FormatterFunction = (
args.map((arg) => inspect(arg)).join(" ")
}`;

const encoder = new TextEncoder();

class StreamHandler extends BaseHandler {
#writer: WritableStreamDefaultWriter<Uint8Array>;

constructor(
levelName: LevelName,
stream: WritableStream<Uint8Array>,
options?: BaseHandlerOptions,
) {
super(levelName, options);
this.#writer = stream.getWriter();
}

log(msg: string): void {
this.#writer.write(encoder.encode(msg + "\n"));
}

override destroy(): void {
this.#writer.close();
}
}

const mods = [
"acorn.context",
"acorn.request_event_cfw",
Expand Down Expand Up @@ -130,12 +154,12 @@ export function configure(options?: LoggerOptions): void {
handlers.push("file");
}
if (options.stream) {
// sinks.stream = getStreamSink(options.stream.stream);
// loggers.push({
// category: ["acorn"],
// sinks: ["stream"],
// level: options.stream.level ?? "info",
// });
config.handlers.stream = new StreamHandler(
options.stream.level ?? "INFO",
options.stream.stream,
{ formatter },
);
handlers.push("stream");
}
} else {
config.handlers.console = new ConsoleHandler("WARN", { formatter });
Expand Down
7 changes: 6 additions & 1 deletion router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,11 @@ import type {
} from "./schema.ts";
import { NOT_ALLOWED } from "./constants.ts";

/**
* The description of a route which can be used when registering a route with
* the {@linkcode Router}, which incorporates the path, handler, and other
* route specific options.
*/
export interface RouteDescriptor<
Path extends string,
Env extends Record<string, string> = Record<string, string>,
Expand Down Expand Up @@ -1870,7 +1875,7 @@ export class Router<
secure,
onListen,
} = options;
this.#logger.debug(`listen options: ${options}`);
this.#logger.debug(`listen options:`, options);
const abortController = new AbortController();
signal?.addEventListener("abort", async () => {
this.#logger.debug(`closing server`);
Expand Down

0 comments on commit ad4ce55

Please sign in to comment.