1 /* 2 Copyright © 2020, Luna Nielsen 3 Distributed under the 2-Clause BSD License, see LICENSE file. 4 5 Authors: Luna Nielsen 6 */ 7 module engine.core.log; 8 import std.stdio; 9 import std.file; 10 import std.format; 11 import core.stdc.stdlib : exit; 12 13 __gshared Logger AppLog; 14 15 /** 16 A logger 17 */ 18 class Logger { 19 private: 20 bool logFileOpened = false; 21 File logFile; 22 string logFileName; 23 24 void writeLogToFile(string text) { 25 26 // Open log file if need be 27 if (!logFileOpened) this.openLogFile(); 28 29 // Write to log 30 logFile.writeln(text); 31 logFile.flush(); 32 } 33 34 void openLogFile() { 35 this.logFile = File(this.logFileName, "a"); 36 } 37 38 public: 39 /** 40 Whether to write logs to file 41 42 TODO: implement 43 */ 44 bool logToFile; 45 46 /** 47 Creates a new logger 48 */ 49 this(bool logToFile = false, string logFile = "applog.log") { 50 this.logToFile = logToFile; 51 this.logFileName = logFile; 52 53 if (logToFile) { 54 this.openLogFile(); 55 } 56 } 57 58 /** 59 Closes the logger and its attachment to the log file 60 */ 61 ~this() { 62 if (logFileOpened) logFile.close(); 63 } 64 65 /** 66 Write info log to stdout 67 */ 68 void info(T...)(string sender, string text, T fmt) { 69 string logText = "[%s] info: %s".format(sender, text.format(fmt)); 70 writeln(logText); 71 72 if (logToFile) { 73 this.writeLogToFile(logText); 74 } 75 } 76 77 /** 78 Write warning log to stdout 79 */ 80 void warn(T...)(string sender, string text, T fmt) { 81 string logText = "[%s] warning: %s".format(sender, text.format(fmt)); 82 writeln(logText); 83 84 if (logToFile) { 85 this.writeLogToFile(logText); 86 } 87 } 88 89 /** 90 Writes error to stderr 91 */ 92 void error(T...)(string sender, string text, T fmt) { 93 string logText = "[%s] error: %s".format(sender, text.format(fmt)); 94 stderr.writeln(logText); 95 96 if (logToFile) { 97 this.writeLogToFile(logText); 98 } 99 } 100 101 /** 102 Writes a fatal error to stderr and quits the application with status -1 103 */ 104 void fatal(T...)(string sender, string text, T fmt) { 105 string logText = "[%s] fatal: %s".format(sender, text.format(fmt)); 106 stderr.writeln(logText); 107 108 if (logToFile) { 109 this.writeLogToFile(logText); 110 } 111 112 exit(-1); 113 } 114 }