Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: setup logging #234

Merged
merged 8 commits into from
Jul 29, 2022
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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@
externals/
downloads/
test*
.log
2 changes: 2 additions & 0 deletions deps.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,5 @@ export {
toFileUrl,
} from "https://deno.land/[email protected]/path/mod.ts";
export * from "https://deno.land/x/[email protected]/mod.ts";
export * as log from "https://deno.land/[email protected]/log/mod.ts";
export { getLevelByName } from "https://deno.land/[email protected]/log/levels.ts";
11 changes: 6 additions & 5 deletions env.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { cleanEnv, config, makeValidator, num, str } from "./deps.ts";
import { cleanEnv, config, log, makeValidator, num, str } from "./deps.ts";

await config({ export: true });

Expand All @@ -9,18 +9,19 @@ const cmdPrefix = makeValidator((input) => {
if (PREFIX_REGEX.test(input)) {
return input;
}
console.warn(
"Falling back to '\\' for COMMAND_PREFIX, a single symbol excluding @, #, $ was expected",
log.warning(
"falling back to '\\' for COMMAND_PREFIX: a single symbol excluding @, # and $ was expected",
);
Deno.exit();
return "\\";
});

const inputPrefix = makeValidator((input) => {
if (PREFIX_REGEX.test(input) && input !== Deno.env.get("COMMAND_PREFIX")) {
return input;
}
console.warn(
"Falling back to '>' for INPUT_PREFIX, a single symbol excluding @, #, $ and COMMAND_PREFIX was expected",
log.warning(
"falling back to '>' for INPUT_PREFIX: a single symbol excluding @, #, $ and COMMAND_PREFIX was expected",
);
return "\\";
});
Expand Down
22 changes: 2 additions & 20 deletions helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,29 +3,11 @@ import { CustomFile, NewMessageEvent, SendMessageParams } from "$grm";
import { Buffer } from "$grm-deps";
import { fmt, pre, type Stringable } from "./deps.ts";

export async function wrap(
event: NewMessageEvent,
func: () => Promise<void>,
) {
try {
await func();
} catch (err) {
console.error(err);
try {
let message = String(err);
message = message.length <= 1000 ? message : "An error occurred.";
await event.message.reply({ message });
} catch (_err) {
//
}
}
}

export async function updateMessage(
export function updateMessage(
event: NewMessageEvent,
text: Stringable,
) {
return await event.message.edit(
return event.message.edit(
fmt`${event.message.text}\n${text}`.edit,
);
}
Expand Down
1 change: 1 addition & 0 deletions main.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { NewMessage, StringSession, TelegramClient } from "$grm";
import "./setup_log.ts";
import env from "./env.ts";
import modules from "./modules/mod.ts";
import { managerModule, ModuleManager } from "./module_manager.ts";
Expand Down
27 changes: 18 additions & 9 deletions module_manager.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Api, NewMessageEvent, TelegramClient } from "$grm";
import { bold, fmt, join, resolve, toFileUrl } from "./deps.ts";
import { bold, fmt, join, log, resolve, toFileUrl } from "./deps.ts";
import { CommandHandler, End } from "./handlers/mod.ts";
import { updateMessage } from "./helpers.ts";
import { getHelp, isModule, Module } from "./module.ts";
Expand Down Expand Up @@ -198,15 +198,15 @@ export class ModuleManager {
if (disableable && this.disabled.has(name)) {
return;
}
for (const handler of handlers) {
for (const [index, handler] of Object.entries(handlers)) {
if (await handler.check({ client: this.client, event })) {
try {
const result = await handler.handle({ client: this.client, event });
if (typeof result === "symbol" && result == End) {
break;
}
} catch (err) {
console.error(err);
log.error(`handler #${index} of ${name} failed: ${err}`);
try {
let message = String(err);
message = message.length <= 1000 ? message : "An error occurred.";
Expand Down Expand Up @@ -262,15 +262,24 @@ export class ModuleManager {

static async directory(path: string) {
const modules = new Array<Module>();
for await (let { name: file } of Deno.readDir(path)) {
if (file.startsWith(".")) {
let all = 0;
let loaded = 0;
for await (let { name, isFile, isDirectory } of Deno.readDir(path)) {
if ((!isFile && !isDirectory) || name.startsWith(".")) {
continue;
}
file = file.endsWith(".ts") ? file : `${file}/mod.ts`;
const spec = join(path, file);
const mod = await this.file(spec);
modules.push(mod);
all++;
name = name.endsWith(".ts") ? name : `${name}/mod.ts`;
const spec = join(path, name);
try {
const mod = await this.file(spec);
modules.push(mod);
loaded++;
} catch (err) {
log.warning(`failed to load ${spec} from ${path}: ${err}`);
}
}
log.info(`loaded ${loaded} out of ${all} modules from ${path}`);
return modules;
}
}
31 changes: 31 additions & 0 deletions setup_log.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { getLevelByName, log } from "./deps.ts";

const level = (() => {
let toReturn = "INFO";
try {
const level = Deno.env.get("LOG_LEVEL");
if (level) {
// deno-lint-ignore no-explicit-any
getLevelByName(level as any);
toReturn = level;
}
} catch (_err) {
//
}
return toReturn as log.LevelName;
})();

await log.setup({
handlers: {
console: new log.handlers.ConsoleHandler(level),
file: new log.handlers.FileHandler(level, {
filename: ".log",
mode: "a",
}),
},
loggers: {
default: {
handlers: ["console", "file"],
},
},
});