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.

69 lines
1.5KB

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