Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use v6;
- unit module JK::Logging;
- role Handler is export {
- method handle(Str:D $entry) { ... }
- }
- class StdoutHandler does Handler is export {
- method handle(Str:D $entry) {
- say $entry;
- }
- }
- enum Severity <debug info warn error>;
- role LogEntry is export {
- has Str $.message;
- }
- role Formatter[::LogEntryType] is export {
- method format(Severity $severity, LogEntryType:D $entry) returns Str { ... }
- }
- class DefaultFormatter does Formatter[LogEntry] is export {
- method format(Severity $severity, LogEntry:D $entry) returns Str {
- return "$severity.uc(): $entry";
- }
- }
- role Logger[::LogEntryType] is export {
- method debug(LogEntryType:D $entry) { ... }
- method info(LogEntryType:D $entry) { ... }
- method warn(LogEntryType:D $entry) { ... }
- method err(LogEntryType:D $entry) { ... }
- }
- role DefaultLogger[LogEntry:U ::LogEntryType] does Logger[LogEntryType] is export {
- has Formatter[LogEntryType] $.formatter is rw;
- has Handler @handlers = StdoutHandler.new();
- submethod do-log(Severity $severity, LogEntryType:D $entry) {
- say $!formatter;
- my Str $formatted-entry = $!formatter.format($severity, $entry);
- for @handlers {
- $_.handle($formatted-entry);
- }
- }
- method debug(LogEntryType:D $entry) {
- self.do-log(Severity::debug, $entry);
- }
- method info(LogEntryType:D $entry) {
- self.do-log(Severity::info, $entry);
- }
- method warn(LogEntryType:D $entry) {
- self.do-log(Severity::warn, $entry);
- }
- method err(LogEntryType:D $entry) {
- self.do-log(Severity::error, $entry);
- }
- }
- my Logger %logger-registry{LogEntry};
- %logger-registry{LogEntry} = DefaultLogger[LogEntry].new(:formatter(DefaultFormatter.new()));
- sub registerLogger(LogEntry:U ::LogEntryType $logEntryType, Logger[LogEntryType] $logger) is export {
- unless %logger-registry{$logEntryType}:exists {
- %logger-registry{$logEntryType} = $logger;
- }
- }
- sub getLogger(Str $name, LogEntry:U $logEntryType=LogEntry) returns Logger[$logEntryType] is export {
- given %logger-registry{$logEntryType} {
- when $_ { $_.new(); }
- default { die "Cannot get logger for unknown LogEntry type $logEntryType" }
- }
- }
- my $logger = getLogger('anything');
- my $entry = LogEntry.new(message => 'hello, logger');
- $logger.info($entry);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement