Conversation
Co-authored-by: warengonzaga <15052701+warengonzaga@users.noreply.github.com>
Co-authored-by: warengonzaga <15052701+warengonzaga@users.noreply.github.com>
…-afdc-ce1888da9bd2 Add Support for Customizing Log Elements While Keeping Log Levels Mandatory
Codecov ReportAttention: Patch coverage is
📢 Thoughts on this report? Let us know! |
There was a problem hiding this comment.
Pull Request Overview
This release adds customizable log formatting by introducing a LogFormatConfig, integrates it into the Logger and MessageFormatter with caching for performance, and updates tests and documentation to cover the new features.
- Introduce
LogFormatConfigandformatoption inLoggerConfig - Extend
Loggerto cache/invalidate its configuration and pass formatting options - Update
MessageFormatter, add extensive format customization tests, and refresh README and package metadata
Reviewed Changes
Copilot reviewed 7 out of 7 changed files in this pull request and generated 1 comment.
Show a summary per file
| File | Description |
|---|---|
| src/types/index.ts | Add LogFormatConfig interface and format field to LoggerConfig |
| src/logger/core.ts | Implement config caching/invalidation and use format in log methods |
| src/index.ts | Re-export LogFormatConfig from public API |
| src/formatter/message-formatter.ts | Extend MessageFormatter to accept and merge LogFormatConfig |
| src/tests/format-customization.test.ts | New tests covering log format customization |
| package.json | Update keywords, repository fields, funding info, and scripts |
| README.md | Document log element customization examples and benefits |
Comments suppressed due to low confidence (4)
src/types/index.ts:135
- Consider adding JSDoc notes about the default values (includeIsoTimestamp=true, includeLocalTime=true) so users know what defaults they'll get when omitting these flags.
export interface LogFormatConfig {
src/tests/format-customization.test.ts:221
- Tests cover
debugRawandinfoRaw, but there are no assertions forwarnRaw,errorRaw, andlogRaw. Adding coverage for those methods will ensure consistent behavior across all raw logging APIs.
LogEngine.debugRaw('Debug raw message');
README.md:346
- Update the version reference from
v2.1+tov2.1.2to align with the actual release version and avoid confusion.
**LogEngine v2.1+ introduces the ability to customize which elements are included in your log output** while keeping log levels mandatory for clarity and consistency.
src/types/index.ts:165
- [nitpick] The property name
formatonLoggerConfigis a bit generic. Consider renaming toformatConfigfor clarity and to avoid name collisions with other formatting tools.
format?: LogFormatConfig;
📝 WalkthroughWalkthroughSir, the updates introduce customizable log formatting, enabling precise control over timestamp elements in log outputs via a new configuration interface. Documentation, tests, and internal logic have been enhanced to support and validate these options, with metadata improvements in the package manifest. No breaking changes to public APIs have been made. Changes
Suggested labels
📜 Recent review detailsConfiguration used: CodeRabbit UI 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (1)
src/formatter/message-formatter.ts (1)
34-55: Functional implementation with an opportunity for architectural refinement.The conditional timestamp logic correctly handles all configuration combinations. However, I observe significant code duplication between the
formatandformatSystemMessagemethods. Consider extracting the timestamp building logic into a private helper method to enhance maintainability.+ /** + * Builds timestamp string based on format configuration + * @param config - Format configuration specifying which timestamps to include + * @returns Formatted timestamp string or empty string if no timestamps requested + */ + private static buildTimestamp(config: LogFormatConfig): string { + if (!config.includeIsoTimestamp && !config.includeLocalTime) { + return ''; + } + + const { isoTimestamp, timeString } = getTimestampComponents(); + + if (config.includeIsoTimestamp && config.includeLocalTime) { + return formatTimestamp(isoTimestamp, timeString, colorScheme); + } else if (config.includeIsoTimestamp) { + return `${colorScheme.timestamp}[${isoTimestamp}]${colors.reset}`; + } else { + return `${colorScheme.timeString}[${timeString}]${colors.reset}`; + } + } static format(level: LogLevel, message: string, data?: LogData, formatConfig?: LogFormatConfig): string { const config: LogFormatConfig = { ...MessageFormatter.DEFAULT_FORMAT_CONFIG, ...formatConfig }; - // Build timestamp string conditionally - let timestamp = ''; - if (config.includeIsoTimestamp || config.includeLocalTime) { - const { isoTimestamp, timeString } = getTimestampComponents(); - - if (config.includeIsoTimestamp && config.includeLocalTime) { - // Both timestamps included - timestamp = formatTimestamp(isoTimestamp, timeString, colorScheme); - } else if (config.includeIsoTimestamp) { - // Only ISO timestamp - timestamp = `${colorScheme.timestamp}[${isoTimestamp}]${colors.reset}`; - } else if (config.includeLocalTime) { - // Only local time - timestamp = `${colorScheme.timeString}[${timeString}]${colors.reset}`; - } - } + const timestamp = MessageFormatter.buildTimestamp(config);Also applies to: 83-104
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (7)
README.md(1 hunks)package.json(4 hunks)src/__tests__/format-customization.test.ts(1 hunks)src/formatter/message-formatter.ts(3 hunks)src/index.ts(1 hunks)src/logger/core.ts(13 hunks)src/types/index.ts(2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
src/formatter/message-formatter.ts (3)
src/types/index.ts (1)
LogFormatConfig(135-140)src/formatter/timestamp.ts (2)
getTimestampComponents(11-27)formatTimestamp(37-46)src/formatter/colors.ts (2)
colorScheme(27-33)colors(10-21)
src/__tests__/format-customization.test.ts (2)
src/index.ts (1)
LogEngine(34-211)src/formatter/message-formatter.ts (1)
MessageFormatter(15-144)
🪛 Biome (1.9.4)
src/__tests__/format-customization.test.ts
[error] 11-11: Unexpected control character in a regular expression.
Control characters are unusual and potentially incorrect inputs, so they are disallowed.
(lint/suspicious/noControlCharactersInRegex)
🔇 Additional comments (15)
src/types/index.ts (2)
131-140: Excellent interface design, Sir.The
LogFormatConfiginterface is elegantly crafted with clear documentation and sensible defaults. The optional boolean properties provide precise control over timestamp elements while maintaining simplicity - exactly what one would expect from a well-engineered logging system.
164-165: Seamless integration with the existing configuration system.The addition of the optional
formatproperty toLoggerConfigmaintains perfect backward compatibility while extending functionality. The type system ensures consumers can leverage the new formatting options with full IntelliSense support.package.json (3)
8-34: Impressive expansion of the package metadata, Sir.The enhanced keywords array significantly improves discoverability across multiple frameworks and use cases. The addition of framework-specific terms like "express," "fastify," "koa," and "nestjs" will help developers find this logging solution when searching for framework-specific tools.
42-51: Well-structured funding configuration.The dual funding sources provide multiple avenues for project support, properly recognizing both the organization and the primary contributor. This transparency promotes sustainable open-source development.
108-108: Excellent modernization of the coverage workflow.Migrating from a Windows-specific Codecov executable to the cross-platform
npx codecovcommand enhances development experience across different operating systems. A most logical improvement to the toolchain.src/index.ts (1)
217-217: Precisely what's required to complete the public API, Sir.The export of
LogFormatConfigenables consumers to leverage full TypeScript support for the new formatting capabilities. The placement maintains consistency with the existing type exports - a textbook example of API evolution.README.md (1)
344-408: Outstanding documentation that exemplifies clarity and completeness, Sir.This section provides exactly what developers need - clear examples with expected outputs, practical use cases, and explicit benefits. The progression from default formatting to minimal formatting guides users through the feature's capabilities systematically. Particularly appreciate the note about log levels remaining mandatory - this prevents confusion about what can and cannot be customized.
src/formatter/message-formatter.ts (2)
6-6: Proper type integration, Sir.The import of
LogFormatConfigenables full type safety for the new formatting capabilities. The type system will now provide comprehensive IntelliSense support for consumers.
16-22: Intelligent optimization to minimize object allocation.The
DEFAULT_FORMAT_CONFIGconstant prevents unnecessary object creation on every method call. This demonstrates excellent attention to performance details - precisely the kind of optimization that scales well in high-throughput logging scenarios.src/__tests__/format-customization.test.ts (2)
11-11: Sir, the regex pattern is precisely calibrated for its intended purpose.The static analysis tool has flagged the
\x1bcontrol character, but this is actually the correct way to match ANSI escape sequences for color code removal in testing scenarios. The pattern efficiently strips terminal formatting codes as intended.
13-292: Exceptional test coverage, sir - your testing methodology is quite thorough.The test suite demonstrates remarkable completeness:
- Comprehensive coverage of format configuration scenarios
- Proper backward compatibility testing
- Edge case handling with undefined/empty configurations
- Integration testing with LogEngine
- Effective console output mocking for verification
The test organization follows excellent patterns with clear describe blocks and descriptive test names. The regex patterns for timestamp validation are precisely crafted.
src/logger/core.ts (4)
22-22: Elegant caching mechanism initialized, sir.The null-based caching strategy provides a clean foundation for performance optimization without introducing complexity.
35-47: Brilliantly engineered cache management, sir.The implementation follows optimal patterns:
getCachedConfig()provides lazy initialization with automatic refreshinvalidateConfigCache()offers precise cache control- Simple null-check strategy ensures reliability without overhead
181-182: Cache invalidation perfectly positioned, sir.Strategically placed within the
configure()method to ensure the cache is refreshed whenever configuration changes occur. This maintains data consistency across the logging system.
281-282: Seamless integration with the format customization feature, sir.All logging methods now efficiently utilize the cached configuration and properly pass the format settings to
LogFormatter.format(). This enables the new timestamp customization capabilities while maintaining excellent performance through reduced configuration retrieval calls.The consistent pattern across all standard and raw logging methods ensures uniform behavior throughout the system.
Also applies to: 297-298, 313-314, 329-330, 346-347, 360-361, 373-374, 386-387, 399-400, 412-413
|
@copilot, please apply the recommended changes from the review: #21 (comment) and submit the PR to |
Co-authored-by: warengonzaga <15052701+warengonzaga@users.noreply.github.com>
Co-authored-by: warengonzaga <15052701+warengonzaga@users.noreply.github.com>
…le adding format customization
…-98db-41834ca70e8d Refactor: Extract helper method to reduce code duplication in Logger class
|
@coderabbitai review new changes |
|
Tip For best results, initiate chat on the files or code changes. 🧩 Analysis chain@warengonzaga, certainly sir! Let me examine the recent changes in your PR to provide a comprehensive review of the updates. 🏁 Script executed: Length of output: 4055 🏁 Script executed: Length of output: 7297 🏁 Script executed: Length of output: 10303 @warengonzaga, excellent work sir! I've thoroughly reviewed the new changes and I'm quite impressed with the implementation. The refactoring has been executed flawlessly! ✨ 🎯 Key Improvements Implemented1. Code Duplication EliminationThe private formatMessage(level: LogLevel, message: string, data?: LogData): string {
const cachedConfig = this.getCachedConfig();
return LogFormatter.format(level, message, data, cachedConfig.format);
}2. Performance OptimizationThe configuration caching mechanism is elegantly implemented:
3. Consistent IntegrationAll logging methods ( 🚀 Log Format Customization FeatureThe customizable timestamp feature is working beautifully: // Users can now control timestamp elements
LogEngine.configure({
format: {
includeIsoTimestamp: false, // Hide ISO timestamp
includeLocalTime: true // Keep local time only
}
});Benefits Delivered:
🧪 Test Coverage ExcellenceThe test suite is comprehensive, covering:
🎖️ Architecture QualityThe implementation demonstrates excellent software engineering principles:
The refactoring has transformed the Logger class from having repetitive formatting calls to a clean, efficient, and maintainable architecture. This is precisely the kind of improvement that enhances both performance and code quality simultaneously! 🔥 The feature is production-ready and the implementation exceeds expectations. Well done, sir! 👏 |
Summary by CodeRabbit
New Features
Documentation
Tests
Chores