Skip to content

Commit

Permalink
Implement in-memory logger (#16)
Browse files Browse the repository at this point in the history
  • Loading branch information
Fryuni authored Apr 4, 2022
1 parent 3a4e57d commit 8d22b99
Show file tree
Hide file tree
Showing 4 changed files with 69 additions and 0 deletions.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
22 changes: 22 additions & 0 deletions src/inMemoryLogger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import {Log, Logger} from './logger';

/**
* A logger that stores all logs in memory.
*/
export class InMemoryLogger<T extends Log = Log> implements Logger<T> {
/**
* 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;
}
}
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
export * from './logger';
export * from './suppressedLogger';
export * from './consoleLogger';
export * from './inMemoryLogger';
export * from './utilities';
44 changes: 44 additions & 0 deletions test/inMemoryLogger.test.ts
Original file line number Diff line number Diff line change
@@ -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);
});
});

0 comments on commit 8d22b99

Please sign in to comment.