contextual library
A structured logging library with support for formatting, context, and multiple outputs.
The library supports two logging patterns:
- Sink-based logging with multiple drivers (default):
final logger = Logger()
..addChannel('console', ConsoleLogDriver())
..addChannel('file', DailyFileLogDriver('app.log'));
- Listener-based logging similar to the
logging
package:
final logger = Logger();
logger.setListener((level, message, time) {
print('[$time] $level: $message');
});
The listener pattern is simpler but doesn't support multiple outputs or middleware. Use the sink-based pattern for more advanced features.
Features:
- Multiple standard log levels (debug through emergency)
- Built-in message formatters:
- PlainTextLogFormatter for simple text output
- JsonLogFormatter for machine-readable JSON
- PrettyLogFormatter for colored terminal output
RawLogFormamter
for colored terminal output- Custom formatters through LogMessageFormatter
- Rich context support through Context
- Multiple output destinations:
- Console logging
- Daily rotating files
- Webhook endpoints (e.g., Slack)
- In-memory buffers
- Middleware for transforming logs
- Type-specific formatters for custom objects
- Asynchronous batch processing
Getting started:
import 'package:contextual/contextual.dart';
void main() {
final logger = Logger()
..environment('development')
..formatter(PrettyLogFormatter())
..withContext({'app': 'MyApp'});
// Basic logging
logger.info('Server started');
// With additional context
logger.error('Database error',
Context({'code': 500, 'db': 'users'}));
// Type-specific formatting
logger.debug(MyCustomObject()); // Uses registered formatter
}
Key classes:
- Logger - The main entry point for logging
- Context - Holds contextual data for log entries
- LogMessageFormatter - Base class for message formatting
- LogTypeFormatter - For type-specific message formatting
- LogDriver - Interface for log output destinations
For detailed examples and configuration options, see the project's README.
Classes
- ChannelConfig
- Represents the configuration for a single logging channel.
- ConsoleLogDriver
- A LogDriver implementation that logs messages to the console.
- Context
- A context object that stores and manages data for an application.
- DailyFileLogDriver
- A LogDriver that writes log messages to daily rotating log files.
- DriverMiddleware
- Interface for log entry middlewares.
- DriverMiddlewareResult
- Represents the result of a log entry middleware operation. This class provides different constructors to indicate whether the middleware should proceed, stop, or modify the log entry.
- ErrorLogFormatter
- Formats Error objects with their stack traces for debugging.
- FormatterSettings
- A class that holds configuration settings for log formatters.
- JsonLogFormatter
- Formats log messages as structured JSON data.
- LogConfig
- Represents the configuration for the logging system.
- LogDriver
- Defines an interface for a log driver that can be used to log messages.
- LogDriverFactory
- Provides a factory for creating instances of LogDriver based on configuration.
- LogEntry
- Represents a complete log entry with both raw data and formatted output.
- Logger
- A configurable logging system with support for multiple output channels.
- LogMessageFormatter
- Base interface for log message formatters.
- LogRecord
- Represents a log record containing all relevant data for a logging event.
- LogSink
- A sink for handling log messages with batching and automatic flushing capabilities.
- LogSinkConfig
- A class that represents the configuration for a LogSink.
-
LogTypeFormatter<
T> - Interface for type-specific log message formatting.
- PlainTextLogFormatter
- A formatter that outputs log messages in a simple, unformatted text format.
- PrettyLogFormatter
- A formatter that outputs log messages with ANSI colors for terminal display.
- RawLogFormatter
- A formatter that returns log messages exactly as provided, without any formatting.
- SamplingLogDriver
- A log driver that samples log messages based on configured sampling rates.
- StackLogDriver
- A log driver that combines multiple drivers into a single logging pipeline.
- WebhookLogDriver
- A log driver that sends log messages to a webhook endpoint.
Enums
- DriverMiddlewareAction
- Represents the possible actions that a DriverMiddleware can take when handling a log entry.
- Level
- Defines the severity levels for log messages in descending order.
Extensions
- LevelExtension on Level
- Extension methods for working with log levels.
-
MapExtension
on Map<
String, dynamic>
Functions
-
interpolateMessage(
String message, Context context) → String - Interpolates context values into a message string, supporting dot notation.
Typedefs
-
ContextMiddleware
= Map<
String, dynamic> Function() - A typedef for a function that returns a Map<String, dynamic>. This type is commonly used as a middleware function in a context-based application architecture, where the middleware function is responsible for providing the necessary context data for the current request or operation.
-
LogCallback
= Future<
void> Function(LogEntry entry) - LogListener = void Function(LogEntry entry)
- A function type representing a log listener callback.
Exceptions / Errors
- StackDriverException
- Exception thrown when one or more drivers in a stack fail to log a message.