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.

72 lines
1.5KB

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