1 module logdefer.common; 2 3 4 import std.array : Appender, front; 5 import std.string : format; 6 7 import logdefer.timer : Timer; 8 import logdefer.time.duration : Nanos; 9 10 import unixtime : UnixTimeHiRes; 11 12 13 alias Verbosity = immutable int; 14 alias Metadata = string[string]; 15 16 // Define the basic log levels 17 enum LogLevel { Error = 10, Warn = 20, Info = 30, Trace = 40 }; 18 19 // Represents a log entry 20 @safe 21 struct LogEntry 22 { 23 immutable Nanos endOffset; // duration from start 24 immutable Verbosity verbosity; // log level 25 immutable string msg; // log message 26 27 string toString() const 28 { 29 return "%s, %s, %s".format(endOffset, verbosity, msg); 30 } 31 } 32 33 // Represents the event that the logs entries pertain to 34 @safe 35 struct EventContext 36 { 37 UnixTimeHiRes realStartTime; // Time when event first started 38 UnixTimeHiRes monotonicStartTime; // Time when event first started in monotonic clock 39 Nanos endOffset; // Monotonic duration of the event 40 Metadata metadata; // Associated metadata with the event 41 Appender!(LogEntry[]) logs; // log entries 42 Appender!(Timer[]) timers; // user timers 43 44 this(immutable EventContext other) immutable 45 { 46 realStartTime = other.realStartTime; 47 monotonicStartTime = other.monotonicStartTime; 48 endOffset = other.endOffset; 49 metadata = other.metadata; 50 logs = other.logs; 51 timers = other.timers; 52 } 53 54 this(shared EventContext other) shared 55 { 56 realStartTime = other.realStartTime; 57 monotonicStartTime = other.monotonicStartTime; 58 endOffset = other.endOffset; 59 metadata = other.metadata; 60 logs = other.logs; 61 timers = other.timers; 62 } 63 64 string toString() const 65 { 66 return "%s, %s, %s, %(%s, %), ".format( 67 realStartTime, endOffset, metadata, logs.data 68 ); 69 } 70 } 71 72 @safe 73 alias DelegateWriter = void delegate(string msg); 74 75 // By default use system clock 76 @safe 77 static const DefaultTimeProvider = () { 78 return UnixTimeHiRes.now(); 79 };