1 /** 2 Central logging facility for vibe. 3 4 Copyright: © 2012 rejectedsoftware e.K. 5 License: Subject to the terms of the MIT license, as written in the included LICENSE.txt file. 6 Authors: Sönke Ludwig 7 */ 8 module dub.internal.vibecompat.core.log; 9 10 import std.array; 11 import std.datetime; 12 import std.format; 13 import std.stdio; 14 import core.thread; 15 16 private { 17 shared LogLevel s_minLevel = LogLevel.info; 18 shared LogLevel s_logFileLevel; 19 } 20 21 /// Sets the minimum log level to be printed. 22 void setLogLevel(LogLevel level) nothrow 23 { 24 s_minLevel = level; 25 } 26 27 LogLevel getLogLevel() 28 { 29 return s_minLevel; 30 } 31 32 /** 33 Logs a message. 34 35 Params: 36 level = The log level for the logged message 37 fmt = See http://dlang.org/phobos/std_format.html#format-string 38 */ 39 void logDebug(T...)(string fmt, lazy T args) nothrow { log(LogLevel.debug_, fmt, args); } 40 /// ditto 41 void logDiagnostic(T...)(string fmt, lazy T args) nothrow { log(LogLevel.diagnostic, fmt, args); } 42 /// ditto 43 void logInfo(T...)(string fmt, lazy T args) nothrow { log(LogLevel.info, fmt, args); } 44 /// ditto 45 void logWarn(T...)(string fmt, lazy T args) nothrow { log(LogLevel.warn, fmt, args); } 46 /// ditto 47 void logError(T...)(string fmt, lazy T args) nothrow { log(LogLevel.error, fmt, args); } 48 49 /// ditto 50 void log(T...)(LogLevel level, string fmt, lazy T args) 51 nothrow { 52 if( level < s_minLevel ) return; 53 string pref; 54 final switch( level ){ 55 case LogLevel.debug_: pref = "trc"; break; 56 case LogLevel.diagnostic: pref = "dbg"; break; 57 case LogLevel.info: pref = "INF"; break; 58 case LogLevel.warn: pref = "WRN"; break; 59 case LogLevel.error: pref = "ERR"; break; 60 case LogLevel.fatal: pref = "FATAL"; break; 61 case LogLevel.none: assert(false); 62 } 63 64 try { 65 auto txt = appender!string(); 66 txt.reserve(256); 67 formattedWrite(txt, fmt, args); 68 69 auto threadid = cast(ulong)cast(void*)Thread.getThis(); 70 auto fiberid = cast(ulong)cast(void*)Fiber.getThis(); 71 threadid ^= threadid >> 32; 72 fiberid ^= fiberid >> 32; 73 74 if( level >= s_minLevel ){ 75 if (level == LogLevel.info) { 76 stdout.writeln(txt.data); 77 stdout.flush(); 78 } else { 79 stderr.writeln(txt.data); 80 stderr.flush(); 81 } 82 } 83 } catch( Exception e ){ 84 // this is bad but what can we do.. 85 debug assert(false, e.msg); 86 } 87 } 88 89 /// Specifies the log level for a particular log message. 90 enum LogLevel { 91 debug_, 92 diagnostic, 93 info, 94 warn, 95 error, 96 fatal, 97 none 98 } 99