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.

logger.cpp 1.6KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. return;
  16. }
  17. outputFile = fopen(asset::logPath.c_str(), "w");
  18. if (!outputFile) {
  19. fprintf(stderr, "Could not open log at %s\n", asset::logPath.c_str());
  20. }
  21. }
  22. void destroy() {
  23. if (outputFile != stderr) {
  24. fclose(outputFile);
  25. }
  26. }
  27. static const char* const levelLabels[] = {
  28. "debug",
  29. "info",
  30. "warn",
  31. "fatal"
  32. };
  33. static const int levelColors[] = {
  34. 35,
  35. 34,
  36. 33,
  37. 31
  38. };
  39. static void logVa(Level level, const char* filename, int line, const char* format, va_list args) {
  40. std::lock_guard<std::mutex> lock(logMutex);
  41. auto nowTime = std::chrono::high_resolution_clock::now();
  42. int duration = std::chrono::duration_cast<std::chrono::milliseconds>(nowTime - startTime).count();
  43. if (outputFile == stderr)
  44. fprintf(outputFile, "\x1B[%dm", levelColors[level]);
  45. fprintf(outputFile, "[%.03f %s %s:%d] ", duration / 1000.0, levelLabels[level], filename, line);
  46. if (outputFile == stderr)
  47. fprintf(outputFile, "\x1B[0m");
  48. vfprintf(outputFile, format, args);
  49. fprintf(outputFile, "\n");
  50. fflush(outputFile);
  51. }
  52. void log(Level level, const char* filename, int line, const char* format, ...) {
  53. va_list args;
  54. va_start(args, format);
  55. logVa(level, filename, line, format, args);
  56. va_end(args);
  57. }
  58. } // namespace logger
  59. } // namespace rack