diff --git a/README.md b/README.md index d513171..595cf17 100644 --- a/README.md +++ b/README.md @@ -58,6 +58,8 @@ This package provides the following implementations: A logger that writes to the console using the appropriate console API semantics. - [PrefixedLogger](src/prefixedLogger.ts) A logger that prepends a prefix to all log messages. +- [InMemoryLogger](src/inMemoryLogger.ts) + A logger that stores all log messages in memory. ## Utilities diff --git a/src/inMemoryLogger.ts b/src/inMemoryLogger.ts new file mode 100644 index 0000000..01579a5 --- /dev/null +++ b/src/inMemoryLogger.ts @@ -0,0 +1,22 @@ +import {Log, Logger} from './logger'; + +/** + * A logger that stores all logs in memory. + */ +export class InMemoryLogger implements Logger { + /** + * The received logs. + */ + private readonly logs: T[] = []; + + public log(log: T): void { + this.logs.push(log); + } + + /** + * Returns all received logs. + */ + public getLogs(): readonly T[] { + return this.logs; + } +} diff --git a/src/index.ts b/src/index.ts index e950db8..020a1eb 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,4 +1,5 @@ export * from './logger'; export * from './suppressedLogger'; export * from './consoleLogger'; +export * from './inMemoryLogger'; export * from './utilities'; diff --git a/test/inMemoryLogger.test.ts b/test/inMemoryLogger.test.ts new file mode 100644 index 0000000..d058a6c --- /dev/null +++ b/test/inMemoryLogger.test.ts @@ -0,0 +1,44 @@ +import {InMemoryLogger, Log, LogLevel} from '../src'; + +describe('An in-memory logger', () => { + it('should log messages', () => { + const logger = new InMemoryLogger(); + + const logs: Log[] = [ + { + level: LogLevel.DEBUG, + message: 'A debug message', + details: { + id: 1, + }, + }, + { + level: LogLevel.INFO, + message: 'An info message', + details: { + id: 2, + }, + }, + { + level: LogLevel.WARNING, + message: 'A warning message', + details: { + id: 3, + }, + }, + { + level: LogLevel.ERROR, + message: 'An error message', + details: { + id: 4, + }, + }, + ]; + + for (const log of logs) { + logger.log(log); + } + + expect(logger.getLogs()).toEqual(logs); + }); +});