log_helper.cpp 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. #include "log_helper.h"
  2. #include <share.h>
  3. #include <stdarg.h>
  4. #include <stdio.h>
  5. #include <mutex>
  6. #define AMLOCK(A) std::lock_guard<std::mutex> lock(A)
  7. #define LOG_ROLL_SIZE (1024 * 1024)
  8. AMLog* AMLog::_log = NULL;
  9. std::mutex _lock;
  10. AMLog::AMLog(FILE* handle)
  11. : _handle(handle)
  12. {
  13. _log = this;
  14. }
  15. AMLog::~AMLog()
  16. {
  17. AMLOCK(_lock);
  18. if (_log && _handle) {
  19. fclose(_handle);
  20. _log = NULL;
  21. }
  22. }
  23. AMLog* AMLog::get(const char* path)
  24. {
  25. if (_log || !path) {
  26. return _log;
  27. }
  28. DWORD size = 0;
  29. HANDLE file = CreateFile(path, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  30. if (file != INVALID_HANDLE_VALUE) {
  31. size = GetFileSize(file, NULL);
  32. CloseHandle(file);
  33. }
  34. if (size != INVALID_FILE_SIZE && size > LOG_ROLL_SIZE) {
  35. if (DeleteFileA(path) == FALSE) {
  36. TCHAR roll_path[MAX_PATH];
  37. sprintf_s(roll_path, MAX_PATH, "%s.1", path);
  38. if (!MoveFileEx(path, roll_path, MOVEFILE_REPLACE_EXISTING)) {
  39. return NULL;
  40. }
  41. }
  42. }
  43. FILE* handle = _fsopen(path, "a+", _SH_DENYNO);
  44. if (!handle) {
  45. return NULL;
  46. }
  47. _log = new AMLog(handle);
  48. return _log;
  49. }
  50. void AMLog::printf(const char* format, ...)
  51. {
  52. AMLOCK(_lock);
  53. va_list args;
  54. va_start(args, format);
  55. vfprintf(_handle, format, args);
  56. va_end(args);
  57. fflush(_handle);
  58. }