Skip to content
Merged
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
70 changes: 37 additions & 33 deletions src/api/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,42 +7,46 @@ import { env } from "#env";
import { logger } from "#src/utils/logger";

export async function startApi() {
const port = env.API_PORT;
const port = env.API_PORT;

await RSA.loadKeys();
await RSA.loadKeys();

new Elysia().onError(({ error }) => {
const err = new Response(error.toString());
logger.error(error.toString());
new Elysia().onError(({ error }) => {
const err = new Response(error.toString());
logger.error(error.toString());

return err;
}).use(cors({
origin: /.*\.yuuko\.dev$/,
methods: ["POST", "GET"]
})).use(openapi({
documentation: {
info: {
title: "Yuuko API",
version: "1.0.0",
description: "API documentation for Yuuko services",
},
tags: [
{ name: "Public", description: "Unauthenticated public endpoints" },
{ name: "Protected / Info", description: "Internal status and management endpoints" }
],
components: {
securitySchemes: {
"BearerAuth": {
type: "apiKey",
in: "header",
name: "authorization",
description: "Trusted User Token"
}
return err;
}).use(cors({
origin: [
/.*\.yuuko\.dev$/,
/^http:\/\/localhost(:\d+)?$/,
/^http:\/\/127\.0\.0\.1(:\d+)?$/
],
methods: ["POST", "GET"]
})).use(openapi({
documentation: {
info: {
title: "Yuuko API",
version: "1.0.0",
description: "API documentation for Yuuko services",
},
tags: [
{ name: "Public", description: "Unauthenticated public endpoints" },
{ name: "Protected / Info", description: "Internal status and management endpoints" }
],
components: {
securitySchemes: {
"BearerAuth": {
type: "apiKey",
in: "header",
name: "authorization",
description: "Trusted User Token"
}
}
}
}
}
}
})).use(api).listen(port)
})).use(api).listen(port)

logger.info(`API is open on port ${port}`);
logger.info(`OpenAPI UI available at http://localhost:${port}/openapi`);
logger.info(`API is open on port ${port}`, { type: "startup" });
logger.info(`OpenAPI UI available at http://localhost:${port}/openapi`, { type: "startup" });
}
2 changes: 1 addition & 1 deletion src/caching/redis.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ redis.on("error", (err) => {
});

redis.on("connect", handleAsync(async () => {
logger.info(`Connected to ${host}!`);
logger.info(`Connected to ${host}!`, { type: "startup" });
await redis.set("test", "test");
}));

Expand Down
2 changes: 1 addition & 1 deletion src/checks/run.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ export async function runChecks() {
}
}

logger.info("Checks passed!");
logger.info("Checks passed!", { type: "startup" });
}

function serializeError(e: unknown): string {
Expand Down
91 changes: 59 additions & 32 deletions src/utils/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,21 @@ export const StartupMetaSchema = t.Object(
{ title: "Startup Meta" }
);

export const ErrorMetaSchema = t.Intersect(
[
t.Object(
{
type: t.Literal("error", { title: "Error Type" }),
errorName: t.Optional(t.String()),
stack: t.Optional(t.String()),
errors: t.Optional(t.Array(t.String())),
},
{ title: "Error Meta" }
),
t.Record(t.String(), t.Unknown()),
]
);

export const LogMetaSchema = t.Union([
GenericMetaSchema,
CommandMetaSchema,
Expand All @@ -97,38 +112,43 @@ export const LogMetaSchema = t.Union([
GraphQLMetaSchema,
CheckMetaSchema,
StartupMetaSchema,
ErrorMetaSchema,
]);

export const LogEntrySchema = t.Intersect([
t.Object({
timestamp: t.Optional(t.String({ description: "ISO Timestamp generated by Winston" })),
level: t.Union([
t.Literal("error", { title: "Error" }),
t.Literal("warn", { title: "Warn" }),
t.Literal("info", { title: "Info" }),
t.Literal("http", { title: "HTTP" }),
t.Literal("verbose", { title: "Verbose" }),
t.Literal("debug", { title: "Debug" }),
t.Literal("silly", { title: "Silly" }),
]),
message: t.String(),
}),
t.Partial(LogMetaSchema),
]);


export type CommandMeta = Static<typeof CommandMetaSchema>;
export type GenericMeta = Static<typeof GenericMetaSchema>;
export type CommandDebugMeta = Static<typeof CommandDebugMetaSchema>;
export type EventMeta = Static<typeof EventMetaSchema>;
export type GraphQLMeta = Static<typeof GraphQLMetaSchema>;
export type CheckMeta = Static<typeof CheckMetaSchema>;
export type StartupMeta = Static<typeof StartupMetaSchema>;
export const LogEntrySchema = t.Object({
timestamp: t.Optional(t.String({ description: "ISO Timestamp generated by Winston" })),
level: t.Union([
t.Literal("error", { title: "Error" }),
t.Literal("warn", { title: "Warn" }),
t.Literal("info", { title: "Info" }),
t.Literal("http", { title: "HTTP" }),
t.Literal("verbose", { title: "Verbose" }),
t.Literal("debug", { title: "Debug" }),
t.Literal("silly", { title: "Silly" }),
]),
message: t.String(),
meta: t.Optional(LogMetaSchema),
});

export type LogMeta = Static<typeof LogMetaSchema>;

export type LogEntry = Static<typeof LogEntrySchema>;

const nestMetaFormat = winston.format((info) => {
const { timestamp, level, message, meta, ...rest } = info;
const mergedMeta = meta ? { ...meta, ...rest } : rest;

if (Object.keys(mergedMeta).length > 0) {
return {
timestamp,
level,
message,
meta: mergedMeta,
};
}

return { timestamp, level, message };
});

class Logger {
public logger: winston.Logger;

Expand All @@ -138,7 +158,11 @@ class Logger {
transports: [
new winston.transports.File({
filename,
format: winston.format.combine(winston.format.timestamp(), winston.format.json()),
format: winston.format.combine(
winston.format.timestamp(),
nestMetaFormat(),
winston.format.json()
),
}),
],
});
Expand All @@ -149,14 +173,15 @@ class Logger {
format: winston.format.combine(
winston.format.colorize(),
winston.format.timestamp({ format: "YYYY-MM-DD HH:mm:ss" }),
winston.format.printf(({ timestamp, level, message, ...meta }) => {
const metaStr = Object.keys(meta).length ? JSON.stringify(meta) : "";
winston.format.printf(({ timestamp, level, message, meta, ...rest }) => {
const combinedMeta = meta ?? rest;
const metaStr = Object.keys(combinedMeta).length ? JSON.stringify(combinedMeta) : "";

const timeStr = String(timestamp);
const levelStr = String(level);
const msgStr = String(message);

return `${timeStr} | [${levelStr}]: ${msgStr} ${metaStr}`;
return `${timeStr} | [${levelStr}]: ${msgStr} ${metaStr}`.trim();
}),
),
}),
Expand All @@ -174,9 +199,10 @@ class Logger {
error(message: string | Error | unknown, meta?: LogMeta) {
if (message instanceof Error) {
const errMeta: Record<string, unknown> = {
...meta,
type: "error",
errorName: message.name,
stack: message.stack,
...meta,
};

if (message instanceof AggregateError) {
Expand All @@ -188,7 +214,8 @@ class Logger {
}

const logMessage = typeof message === "string" ? message : String(message);
this.logger.error(logMessage, meta);
const finalMeta = meta ? { ...meta, type: "error" } : { type: "error" };
this.logger.error(logMessage, finalMeta);
}

debug(message: string, meta?: LogMeta) {
Expand Down
Loading