-
Notifications
You must be signed in to change notification settings - Fork 157
feat(logger): Add log buffer and flush method #3617
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
Merged
dreamorosi
merged 9 commits into
aws-powertools:main
from
ConnorKirk:3590-add-basic-buffering-logic
Feb 19, 2025
Merged
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
fb896e8
feat(logger): Add log buffer and flush method
ConnorKirk 90568f4
Add SonarCube feedback
ConnorKirk d18049f
Rename trace_id to traceId
ConnorKirk 1b64fbd
Use error instead of e
ConnorKirk ce13177
Update test feedback
ConnorKirk a897111
Improve jsdoc comments
ConnorKirk cc55e01
Remove beforeEach block
ConnorKirk 8e99d44
Merge branch 'aws-powertools:main' into 3590-add-basic-buffering-logic
ConnorKirk 33ff87f
Pass error as extra input
ConnorKirk File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,146 +1,110 @@ | ||
import { describe, expect, it, vi } from 'vitest'; | ||
import { CircularMap, SizedItem, SizedSet } from '../../src/logBuffer.js'; | ||
import { beforeEach, describe, expect, it, vi } from 'vitest'; | ||
import { Logger } from '../../src/Logger.js'; | ||
import { LogLevelThreshold } from '../../src/constants.js'; | ||
|
||
class TestLogger extends Logger { | ||
public enableBuffering() { | ||
this.isBufferEnabled = true; | ||
} | ||
public disableBuffering() { | ||
this.isBufferEnabled = false; | ||
} | ||
|
||
public flushBufferWrapper(): void { | ||
this.flushBuffer(); | ||
} | ||
|
||
public overrideBufferLogItem(): void { | ||
this.bufferLogItem = vi.fn().mockImplementation(() => { | ||
throw new Error('bufferLogItem error'); | ||
}); | ||
} | ||
|
||
public setbufferLevelThreshold(level: number): void { | ||
this.bufferLogThreshold = level; | ||
} | ||
} | ||
|
||
describe('SizedItem', () => { | ||
it('calculates the byteSize based on string value', () => { | ||
describe('bufferLog', () => { | ||
it('outputs a warning when there is an error buffering the log', () => { | ||
// Prepare | ||
const logEntry = 'hello world'; | ||
process.env.POWERTOOLS_DEV = 'true'; | ||
const logger = new TestLogger(); | ||
dreamorosi marked this conversation as resolved.
Show resolved
Hide resolved
|
||
logger.enableBuffering(); | ||
logger.overrideBufferLogItem(); | ||
|
||
// Act | ||
const item = new SizedItem(logEntry, 1); | ||
logger.debug('This is a debug'); | ||
|
||
// Assess | ||
const expectedByteSize = Buffer.byteLength(logEntry); | ||
expect(item.byteSize).toBe(expectedByteSize); | ||
}); | ||
|
||
it('throws an error if value is not a string', () => { | ||
// Prepare | ||
const invalidValue = { message: 'not a string' }; | ||
|
||
// Act & Assess | ||
expect( | ||
() => new SizedItem(invalidValue as unknown as string, 1) | ||
).toThrowError('Value should be a string'); | ||
expect(console.debug).toBeCalledTimes(1); | ||
expect(console.warn).toBeCalledTimes(1); | ||
}); | ||
}); | ||
|
||
describe('SizedSet', () => { | ||
it('adds an item and updates currentBytesSize correctly', () => { | ||
// Prepare | ||
const set = new SizedSet<string>(); | ||
const item = new SizedItem('value', 1); | ||
|
||
// Act | ||
set.add(item); | ||
describe('flushBuffer', () => { | ||
const ENVIRONMENT_VARIABLES = process.env; | ||
|
||
// Assess | ||
expect(set.currentBytesSize).toBe(item.byteSize); | ||
expect(set.has(item)).toBe(true); | ||
beforeEach(() => { | ||
process.env = { | ||
...ENVIRONMENT_VARIABLES, | ||
POWERTOOLS_LOGGER_LOG_EVENT: 'true', | ||
POWERTOOLS_DEV: 'true', | ||
}; | ||
vi.clearAllMocks(); | ||
}); | ||
|
||
it('deletes an item and updates currentBytesSize correctly', () => { | ||
it('outputs buffered logs', () => { | ||
// Prepare | ||
const set = new SizedSet<string>(); | ||
const item = new SizedItem('value', 1); | ||
set.add(item); | ||
const initialSize = set.currentBytesSize; | ||
const logger = new TestLogger({ logLevel: 'SILENT' }); | ||
logger.enableBuffering(); | ||
logger.setbufferLevelThreshold(LogLevelThreshold.CRITICAL); | ||
|
||
// Act | ||
const result = set.delete(item); | ||
logger.debug('This is a debug'); | ||
logger.warn('This is a warning'); | ||
logger.critical('this is a critical'); | ||
|
||
// Assess | ||
expect(result).toBe(true); | ||
expect(set.currentBytesSize).toBe(initialSize - item.byteSize); | ||
expect(set.has(item)).toBe(false); | ||
}); | ||
|
||
it('clears all items and resets currentBytesSize to 0', () => { | ||
// Prepare | ||
const set = new SizedSet<string>(); | ||
set.add(new SizedItem('b', 1)); | ||
set.add(new SizedItem('d', 1)); | ||
expect(console.warn).toHaveBeenCalledTimes(0); | ||
expect(console.error).toHaveBeenCalledTimes(0); | ||
|
||
// Act | ||
set.clear(); | ||
logger.flushBufferWrapper(); | ||
|
||
// Assess | ||
expect(set.currentBytesSize).toBe(0); | ||
expect(set.size).toBe(0); | ||
expect(console.warn).toHaveBeenCalledTimes(1); | ||
expect(console.error).toHaveBeenCalledTimes(1); | ||
}); | ||
|
||
it('removes the first inserted item with shift', () => { | ||
it('handles an empty buffer', () => { | ||
// Prepare | ||
const set = new SizedSet<string>(); | ||
const item1 = new SizedItem('first', 1); | ||
const item2 = new SizedItem('second', 1); | ||
set.add(item1); | ||
set.add(item2); | ||
const logger = new TestLogger(); | ||
logger.enableBuffering(); | ||
|
||
// Act | ||
const shiftedItem = set.shift(); | ||
|
||
// Assess | ||
expect(shiftedItem).toEqual(item1); | ||
expect(set.has(item1)).toBe(false); | ||
expect(set.currentBytesSize).toBe(item2.byteSize); | ||
logger.flushBufferWrapper(); | ||
}); | ||
}); | ||
|
||
describe('CircularMap', () => { | ||
it('adds items to a new buffer for a given key', () => { | ||
it('does not output buffered logs when trace id is not set', () => { | ||
// Prepare | ||
const maxBytes = 200; | ||
const circularMap = new CircularMap<string>({ | ||
maxBytesSize: maxBytes, | ||
}); | ||
process.env._X_AMZN_TRACE_ID = undefined; | ||
const logger = new TestLogger({}); | ||
logger.enableBuffering(); | ||
|
||
// Act | ||
circularMap.setItem('trace-1', 'first log', 1); | ||
logger.debug('This is a debug'); | ||
logger.warn('this is a warning'); | ||
|
||
// Assess | ||
const buffer = circularMap.get('trace-1'); | ||
expect(buffer).toBeDefined(); | ||
if (buffer) { | ||
expect(buffer.currentBytesSize).toBeGreaterThan(0); | ||
expect(buffer.size).toBe(1); | ||
} | ||
}); | ||
|
||
it('throws an error when an item exceeds maxBytesSize', () => { | ||
// Prepare | ||
const maxBytes = 10; | ||
const circularMap = new CircularMap<string>({ | ||
maxBytesSize: maxBytes, | ||
}); | ||
|
||
// Act & Assess | ||
expect(() => { | ||
circularMap.setItem('trace-1', 'a very long message', 1); | ||
}).toThrowError('Item too big'); | ||
}); | ||
|
||
it('evicts items when the buffer overflows and call the overflow callback', () => { | ||
// Prepare | ||
const options = { | ||
maxBytesSize: 15, | ||
onBufferOverflow: vi.fn(), | ||
}; | ||
const circularMap = new CircularMap<string>(options); | ||
const smallEntry = '12345'; | ||
|
||
const entryByteSize = Buffer.byteLength(smallEntry); | ||
const entriesCount = Math.ceil(options.maxBytesSize / entryByteSize); | ||
expect(console.debug).toHaveBeenCalledTimes(0); | ||
expect(console.warn).toHaveBeenCalledTimes(1); | ||
|
||
// Act | ||
for (let i = 0; i < entriesCount; i++) { | ||
circularMap.setItem('trace-1', smallEntry, 1); | ||
} | ||
logger.flushBufferWrapper(); | ||
|
||
// Assess | ||
expect(options.onBufferOverflow).toHaveBeenCalledTimes(1); | ||
expect(circularMap.get('trace-1')?.currentBytesSize).toBeLessThan( | ||
options.maxBytesSize | ||
); | ||
expect(console.debug).toHaveBeenCalledTimes(0); | ||
expect(console.warn).toHaveBeenCalledTimes(1); | ||
}); | ||
}); |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.