You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

73 lines
1.5KB

  1. #include <common.hpp>
  2. #include <asset.hpp>
  3. #include <settings.hpp>
  4. #include <chrono>
  5. #include <mutex>
  6. namespace rack {
  7. namespace logger {
  8. static FILE *outputFile = NULL;
  9. static std::chrono::high_resolution_clock::time_point startTime;
  10. static std::mutex logMutex;
  11. void init() {
  12. startTime = std::chrono::high_resolution_clock::now();
  13. if (settings::devMode) {
  14. outputFile = stderr;
  15. }
  16. else {
  17. std::string logFilename = asset::user("log.txt");
  18. outputFile = fopen(logFilename.c_str(), "w");
  19. }
  20. }
  21. void destroy() {
  22. if (outputFile != stderr) {
  23. fclose(outputFile);
  24. }
  25. }
  26. static const char* const levelLabels[] = {
  27. "debug",
  28. "info",
  29. "warn",
  30. "fatal"
  31. };
  32. static const int levelColors[] = {
  33. 35,
  34. 34,
  35. 33,
  36. 31
  37. };
  38. static void logVa(Level level, const char *filename, int line, const char *format, va_list args) {
  39. std::lock_guard<std::mutex> lock(logMutex);
  40. auto nowTime = std::chrono::high_resolution_clock::now();
  41. int duration = std::chrono::duration_cast<std::chrono::milliseconds>(nowTime - startTime).count();
  42. if (outputFile == stderr)
  43. fprintf(outputFile, "\x1B[%dm", levelColors[level]);
  44. fprintf(outputFile, "[%.03f %s %s:%d] ", duration / 1000.0, levelLabels[level], filename, line);
  45. if (outputFile == stderr)
  46. fprintf(outputFile, "\x1B[0m");
  47. vfprintf(outputFile, format, args);
  48. fprintf(outputFile, "\n");
  49. fflush(outputFile);
  50. }
  51. void log(Level level, const char *filename, int line, const char *format, ...) {
  52. va_list args;
  53. va_start(args, format);
  54. logVa(level, filename, line, format, args);
  55. va_end(args);
  56. }
  57. } // namespace logger
  58. } // namespace rack