Skip to content

Commit

Permalink
feat: proper logging (#5)
Browse files Browse the repository at this point in the history
j1nxie authored Mar 9, 2024
2 parents d083dc4 + 53d17f2 commit 339ad25
Showing 7 changed files with 197 additions and 13 deletions.
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -36,6 +36,7 @@
"jsdom": "^24.0.0",
"node-fetch": "^3.3.2",
"redis": "^4.6.13",
"semver": "^7.6.0"
"semver": "^7.6.0",
"winston": "^3.12.0"
}
}
151 changes: 146 additions & 5 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 4 additions & 3 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import logger from "./logger.js";
import eventRouter from "./routes/eventRoute.js";
import statusRouter from "./routes/statusRoute.js";
import cors from "@fastify/cors";
@@ -8,7 +9,6 @@ dotenv.config();

const app = fastify({
ignoreTrailingSlash: true,
logger: true,
});

void app.register(eventRouter, { prefix: "/api" });
@@ -22,9 +22,10 @@ async function start() {
await app.register(cors);
await app.listen({ port: Number(PORT), host: HOST });

app.log.info(`binding to ${HOST} at port ${PORT}.`);
logger.info(`binding to ${HOST} at port ${PORT}.`);
logger.info(`closure-api available on http://${HOST}:${PORT}.`);
} catch (err) {
app.log.error(err);
logger.error(`fatal error: ${err}`);
process.exit(1);
}
}
34 changes: 34 additions & 0 deletions src/logger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import winston from "winston";

export function init(appName: string) {
winston.loggers.add("default", {
level: "info",
levels: { fatal: 0, error: 1, warn: 2, info: 3, trace: 4, debug: 5 },
format: winston.format.combine(
winston.format.splat(),
winston.format.timestamp({ format: "YYYY-MM-DD hh:mm:ss A" }),
winston.format.simple(),
winston.format.printf((info) => `[${info.timestamp}] ${info.level}: ${info.message}`)
),
defaultMeta: { service: `${appName}+${process.env.NODE_ENV ?? "development"}` },
transports: [new winston.transports.Console()],
});

const logger = winston.loggers.get("default");

process.on("uncaughtException", (err) => {
// eslint-disable-next-line no-console
console.log("UncaughtException processing: %s", err);
});

// eslint-disable-next-line func-names
logger.child = function () {
return winston.loggers.get("default");
};

return logger;
}

const winstonLogger = init("closure-api");

export default winstonLogger;
4 changes: 2 additions & 2 deletions src/redis.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import logger from "./logger.js";
import * as dotenv from "dotenv";
import { createClient } from "redis";

@@ -7,8 +8,7 @@ const client = await createClient({
url: `redis://${process.env.REDIS_URL ?? "localhost"}:${process.env.REDIS_PORT ?? "6379"}`,
})
.on("error", (err) => {
// eslint-disable-next-line no-console
console.error("redis error:", err);
logger.error(`redis error: ${err}`);
})
.connect();

5 changes: 4 additions & 1 deletion src/routes/eventRoute.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import logger from "../logger.js";
import client from "../redis.js";
import { JSDOM } from "jsdom";
import fetch from "node-fetch";
@@ -6,13 +7,15 @@ import type { FastifyInstance } from "fastify";
/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable @typescript-eslint/no-unsafe-call */
function eventRouter(fastify: FastifyInstance, options: any, done: any) {
fastify.get("/event", async () => {
fastify.get("/event", async (req) => {
logger.info(`received request to path ${req.routeOptions.url}`);
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const data = JSON.parse((await client.get("cache")) ?? "null");
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
const timestamp = data === null ? null : data.timestamp;

if (Date.now() - timestamp >= 86400000 || timestamp === null) {
logger.info("cache out of date. fetching new data from gamepress.");
const response = await getEvent();

await client.set("cache", JSON.stringify(response));
6 changes: 5 additions & 1 deletion src/routes/statusRoute.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
import { VERSION_PRETTY } from "../constants/version.js";
import logger from "../logger.js";
import type { FastifyInstance } from "fastify";

/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable @typescript-eslint/no-unsafe-call */
function statusRouter(fastify: FastifyInstance, options: any, done: any) {
fastify.get("/status", getStatus);
fastify.get("/status", (req) => {
logger.info(`received request to path ${req.routeOptions.url}`);
getStatus();
});
done();
}

0 comments on commit 339ad25

Please sign in to comment.