log_helper.cpp 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. #include "log_helper.h"
  2. #include <stdio.h>
  3. #include <stdarg.h>
  4. #include <share.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,
  30. NULL);
  31. if (file != INVALID_HANDLE_VALUE) {
  32. size = GetFileSize(file, NULL);
  33. CloseHandle(file);
  34. }
  35. if (size != INVALID_FILE_SIZE && size > LOG_ROLL_SIZE) {
  36. if (DeleteFileA(path) == FALSE) {
  37. TCHAR roll_path[MAX_PATH];
  38. sprintf_s(roll_path, MAX_PATH, "%s.1", path);
  39. if (!MoveFileEx(path, roll_path, MOVEFILE_REPLACE_EXISTING)) {
  40. return NULL;
  41. }
  42. }
  43. }
  44. FILE* handle = _fsopen(path, "a+", _SH_DENYNO);
  45. if (!handle) {
  46. return NULL;
  47. }
  48. _log = new AMLog(handle);
  49. return _log;
  50. }
  51. void AMLog::printf(const char* format, ...)
  52. {
  53. AMLOCK(_lock);
  54. va_list args;
  55. va_start(args, format);
  56. vfprintf(_handle, format, args);
  57. va_end(args);
  58. fflush(_handle);
  59. }