Skip to content

Commit

Permalink
feat: logger inside context
Browse files Browse the repository at this point in the history
  • Loading branch information
whilefoo committed Nov 20, 2023
1 parent df8bc59 commit 4713afa
Show file tree
Hide file tree
Showing 53 changed files with 314 additions and 436 deletions.
6 changes: 4 additions & 2 deletions src/adapters/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@ import { Wallet } from "./supabase/helpers/tables/wallet";
import { Database } from "./supabase/types";
import { env } from "../bindings/env";

const supabaseClient = createClient<Database>(env.SUPABASE_URL, env.SUPABASE_KEY, { auth: { persistSession: false } });
export const supabaseClient = createClient<Database>(env.SUPABASE_URL, env.SUPABASE_KEY, {
auth: { persistSession: false },
});

export function createAdapters() {
return {
Expand All @@ -21,7 +23,7 @@ export function createAdapters() {
debit: new Settlement(supabaseClient),
settlement: new Settlement(supabaseClient),
label: new Label(supabaseClient),
logs: new Logs(supabaseClient, env.LOG_ENVIRONMENT, env.LOG_RETRY_LIMIT, env.LOG_LEVEL),
logs: new Logs(supabaseClient, null, env.LOG_ENVIRONMENT, env.LOG_RETRY_LIMIT, env.LOG_LEVEL),
locations: new Locations(supabaseClient),
super: new Super(supabaseClient),
},
Expand Down
4 changes: 2 additions & 2 deletions src/adapters/supabase/helpers/tables/access.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ export class Access extends Super {
const { data, error } = await this.supabase.from("access").select("*, users(*)").filter("id", "eq", id);

if (error) {
this.runtime.logger.error(null, error.message, error);
this.runtime.logger.error(error.message, error);
throw new Error(error.message);
}
return data;
Expand All @@ -35,7 +35,7 @@ export class Access extends Super {
public async getAccess(id: number): Promise<AccessRow | null> {
const userWithAccess = await this._getUserWithAccess(id);
if (userWithAccess[0]?.access === undefined) {
this.runtime.logger.debug(null, "Access is undefined");
this.runtime.logger.debug("Access is undefined");
return null;
}
if (userWithAccess[0]?.access === null) throw new Error("Access is null");
Expand Down
2 changes: 1 addition & 1 deletion src/adapters/supabase/helpers/tables/label.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ export class Label extends Super {

if (locationError) throw new Error(locationError.message);
if (!locationData) {
runtime.logger.warn(null, "Repository location ID not found in database.");
runtime.logger.warn("Repository location ID not found in database.");
return null;
}

Expand Down
2 changes: 1 addition & 1 deletion src/adapters/supabase/helpers/tables/locations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ export class Locations extends Super {
.select("id")
.eq("repository_id", repositoryId);

if (error) throw this.runtime.logger.error(null, "Error getting location data", new Error(error.message));
if (error) throw this.runtime.logger.error("Error getting location data", new Error(error.message));
return locationData;
}

Expand Down
66 changes: 32 additions & 34 deletions src/adapters/supabase/helpers/tables/logs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,10 @@ import Runtime from "../../../../bindings/bot-runtime";
import { LogLevel } from "../../../../types/logs";
import { Database } from "../../types";
import { prettyLogs } from "../pretty-logs";
import { Super } from "./super";

type LogFunction = (message: string, metadata?: any) => void;
type LogInsert = Database["public"]["Tables"]["logs"]["Insert"];
type _LogParams = {
context: ProbotContext | null;
level: LogLevel;
consoleLog: LogFunction;
logMessage: string;
Expand All @@ -40,7 +38,10 @@ type PublicMethods<T> = Exclude<FunctionPropertyNames<T>, "constructor" | keyof

export type LogMessage = { raw: string; diff: string; level: LogLevel; type: PublicMethods<Logs> };

export class Logs extends Super {
export class Logs {
private supabase: SupabaseClient;
private context: ProbotContext | null = null;

private maxLevel = -1;
private environment = "development";
private queue: LogInsert[] = []; // Your log queue
Expand All @@ -49,7 +50,7 @@ export class Logs extends Super {
private throttleCount = 0;
private retryLimit = 0; // Retries disabled by default

private _log({ context, level, consoleLog, logMessage, metadata, postComment, type }: _LogParams): LogReturn | null {
private _log({ level, consoleLog, logMessage, metadata, postComment, type }: _LogParams): LogReturn | null {
if (this._getNumericLevel(level) > this.maxLevel) return null; // filter out more verbose logs according to maxLevel set in config

// needs to generate three versions of the information.
Expand All @@ -60,13 +61,10 @@ export class Logs extends Super {

consoleLog(logMessage, metadata || undefined);

if (context && postComment) {
if (this.context && postComment) {
const colorizedCommentMessage = this._diffColorCommentMessage(type, logMessage);
const commentMetaData = metadata ? Logs._commentMetaData(metadata, level) : null;
this._postComment(
context,
metadata ? [colorizedCommentMessage, commentMetaData].join("\n") : colorizedCommentMessage
);
this._postComment(metadata ? [colorizedCommentMessage, commentMetaData].join("\n") : colorizedCommentMessage);
}

const toSupabase = { log: logMessage, level, metadata } as LogInsert;
Expand Down Expand Up @@ -112,10 +110,10 @@ export class Logs extends Super {

return metadata;
}
public ok(context: ProbotContext | null, log: string, metadata?: any, postComment?: boolean): LogReturn | null {

public ok(log: string, metadata?: any, postComment?: boolean): LogReturn | null {
metadata = this._addDiagnosticInformation(metadata);
return this._log({
context,
level: LogLevel.VERBOSE,
consoleLog: prettyLogs.ok,
logMessage: log,
Expand All @@ -125,10 +123,9 @@ export class Logs extends Super {
});
}

public info(context: ProbotContext | null, log: string, metadata?: any, postComment?: boolean): LogReturn | null {
public info(log: string, metadata?: any, postComment?: boolean): LogReturn | null {
metadata = this._addDiagnosticInformation(metadata);
return this._log({
context,
level: LogLevel.INFO,
consoleLog: prettyLogs.info,
logMessage: log,
Expand All @@ -138,10 +135,9 @@ export class Logs extends Super {
});
}

public warn(context: ProbotContext | null, log: string, metadata?: any, postComment?: boolean): LogReturn | null {
public warn(log: string, metadata?: any, postComment?: boolean): LogReturn | null {
metadata = this._addDiagnosticInformation(metadata);
return this._log({
context,
level: LogLevel.WARN,
consoleLog: prettyLogs.warn,
logMessage: log,
Expand All @@ -151,10 +147,9 @@ export class Logs extends Super {
});
}

public debug(context: ProbotContext | null, log: string, metadata?: any, postComment?: boolean): LogReturn | null {
public debug(log: string, metadata?: any, postComment?: boolean): LogReturn | null {
metadata = this._addDiagnosticInformation(metadata);
return this._log({
context,
level: LogLevel.DEBUG,
consoleLog: prettyLogs.debug,
logMessage: log,
Expand All @@ -164,7 +159,7 @@ export class Logs extends Super {
});
}

public error(context: ProbotContext | null, log: string, metadata?: any, postComment?: boolean): LogReturn | null {
public error(log: string, metadata?: any, postComment?: boolean): LogReturn | null {
if (!metadata) {
metadata = Logs.convertErrorsIntoObjects(new Error(log));
const stack = metadata.stack as string[];
Expand All @@ -180,7 +175,6 @@ export class Logs extends Super {

metadata = this._addDiagnosticInformation(metadata);
return this._log({
context,
level: LogLevel.ERROR,
consoleLog: prettyLogs.error,
logMessage: log,
Expand All @@ -190,10 +184,9 @@ export class Logs extends Super {
});
}

http(context: ProbotContext | null, log: string, metadata?: any, postComment?: boolean): LogReturn | null {
http(log: string, metadata?: any, postComment?: boolean): LogReturn | null {
metadata = this._addDiagnosticInformation(metadata);
return this._log({
context,
level: LogLevel.HTTP,
consoleLog: prettyLogs.http,
logMessage: log,
Expand All @@ -203,10 +196,9 @@ export class Logs extends Super {
});
}

verbose(context: ProbotContext | null, log: string, metadata?: any, postComment?: boolean): LogReturn | null {
verbose(log: string, metadata?: any, postComment?: boolean): LogReturn | null {
metadata = this._addDiagnosticInformation(metadata);
return this._log({
context,
level: LogLevel.VERBOSE,
consoleLog: prettyLogs.verbose,
logMessage: log,
Expand All @@ -216,10 +208,9 @@ export class Logs extends Super {
});
}

silly(context: ProbotContext | null, log: string, metadata?: any, postComment?: boolean): LogReturn | null {
silly(log: string, metadata?: any, postComment?: boolean): LogReturn | null {
metadata = this._addDiagnosticInformation(metadata);
return this._log({
context,
level: LogLevel.SILLY,
consoleLog: prettyLogs.silly,
logMessage: log,
Expand All @@ -229,9 +220,15 @@ export class Logs extends Super {
});
}

constructor(supabase: SupabaseClient, environment: string, retryLimit: number, logLevel: LogLevel) {
super(supabase);

constructor(
supabase: SupabaseClient,
context: ProbotContext | null,
environment: string,
retryLimit: number,
logLevel: LogLevel
) {
this.supabase = supabase;
this.context = context;
this.environment = environment;
this.retryLimit = retryLimit;
this.maxLevel = this._getNumericLevel(logLevel);
Expand Down Expand Up @@ -311,7 +308,7 @@ export class Logs extends Super {
}

static _commentMetaData(metadata: any, level: LogLevel) {
Runtime.getState().logger.debug(null, "the main place that metadata is being serialized as an html comment");
Runtime.getState().logger.debug("the main place that metadata is being serialized as an html comment");
const prettySerialized = JSON.stringify(metadata, null, 2);
// first check if metadata is an error, then post it as a json comment
// otherwise post it as an html comment
Expand Down Expand Up @@ -366,13 +363,14 @@ export class Logs extends Super {
return [diffHeader, message, diffFooter].join("\n");
}

private _postComment(context: ProbotContext, message: string) {
private _postComment(message: string) {
// post on issue
context.octokit.issues
if (!this.context) return;
this.context.octokit.issues
.createComment({
owner: context.issue().owner,
repo: context.issue().repo,
issue_number: context.issue().issue_number,
owner: this.context.issue().owner,
repo: this.context.issue().repo,
issue_number: this.context.issue().issue_number,
body: message,
})
// .then((x) => console.trace(x))
Expand Down
2 changes: 1 addition & 1 deletion src/adapters/supabase/helpers/tables/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ export class User extends Super {
.eq("user_id", userId)
.order("id", { ascending: false }) // get the latest one
.maybeSingle();
if (accessError) throw this.runtime.logger.error(null, "Error getting access data", accessError);
if (accessError) throw this.runtime.logger.error("Error getting access data", accessError);
return accessData;
}
}
2 changes: 1 addition & 1 deletion src/adapters/supabase/helpers/tables/wallet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,7 @@ export class Wallet extends Super {
private async _enrichLocationMetaData(walletData: WalletRow, locationMetaData: LocationMetaData) {
const runtime = Runtime.getState();
const logger = runtime.logger;
logger.ok(null, "Enriching wallet location metadata", locationMetaData);
logger.ok("Enriching wallet location metadata", locationMetaData);
return await this.supabase.from("locations").update(locationMetaData).eq("id", walletData.location_id);
}
}
Expand Down
Loading

0 comments on commit 4713afa

Please sign in to comment.