Skip to content

Instantly share code, notes, and snippets.

@ChristianOellers
Created July 26, 2023 10:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ChristianOellers/84c514565876a51113b4d4ce384514af to your computer and use it in GitHub Desktop.
Save ChristianOellers/84c514565876a51113b4d4ce384514af to your computer and use it in GitHub Desktop.
Minimal console logger wrapper. TypeScript, Node, Jest, Angular. Architectural demo with interface, config, TDD. IoC optional.
// require('dotenv').config();
/**
* Global environment config.
* Set custom values in '.env' file in project root.
*/
export const globalConfig: {
readonly LOGGING?: boolean;
readonly PORT?: number;
} = {
LOGGING: process.env.LOGGING === "true",
PORT: process.env.PORT ? parseInt(process.env.PORT, 10) : undefined,
};
export interface ILogger {
log(...args: any[]): void;
info(): void;
error(): void;
enable(): void;
disable(): void;
}
import { globalConfig } from "../config";
import { Logger } from "./Logger";
describe("Logger", () => {
let args: any[];
let logger: Logger;
beforeEach(() => {
Object.defineProperty(globalConfig, "LOGGING", { value: true });
args = [1];
logger = new Logger();
});
describe("log()", () => {
it("logs output if logging is enabled", () => {
spyOn(console, "log");
logger.log(args);
expect(console.log).toHaveBeenCalled();
});
it("does not log output if logging is disabled", () => {
spyOn(console, "log");
logger.disable();
logger.log(args);
expect(console.log).toHaveBeenCalledTimes(0);
});
it("should log info", () => {
spyOn(console, "info");
logger.info(args);
expect(console.info).toHaveBeenCalled();
});
it("should log error", () => {
spyOn(console, "error");
logger.error(args);
expect(console.error).toHaveBeenCalled();
});
});
});
// import { injectable } from "inversify";
import { globalConfig } from "../config";
import { ILogger } from "./ILogger";
/**
* CLI logger.
*/
// @injectable()
export class Logger implements ILogger {
private _enabled: boolean = false;
/**
* Constructor sets if logging is enabled.
*/
constructor() {
if (globalConfig.LOGGING) {
this.enable();
}
}
/**
* Output log if enabled.
*/
public log(...args: any[]): void {
if (this._enabled) {
for (const arg of args) {
console.log(arg);
}
}
}
/**
* Output info if enabled.
*/
public info(...args: any[]): void {
if (this._enabled) {
for (const arg of args) {
console.info(arg);
}
}
}
/**
* Output error if enabled.
*/
public error(...args: any[]): void {
if (this._enabled) {
for (const arg of args) {
console.error(arg);
}
}
}
/**
* Enable logging.
*/
public enable(): void {
this._enabled = true;
}
/**
* Disable logging.
*/
public disable(): void {
this._enabled = false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment