file.cpp 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. #include "file.h"
  2. #include "record.h"
  3. #include <util/system/file.h>
  4. #include <util/system/rwlock.h>
  5. #include <util/generic/string.h>
  6. /*
  7. * file log
  8. */
  9. class TFileLogBackend::TImpl {
  10. public:
  11. inline TImpl(const TString& path)
  12. : File_(OpenFile(path))
  13. {
  14. }
  15. inline void WriteData(const TLogRecord& rec) {
  16. //many writes are thread-safe
  17. TReadGuard guard(Lock_);
  18. File_.Write(rec.Data, rec.Len);
  19. }
  20. inline void ReopenLog() {
  21. //but log rotate not thread-safe
  22. TWriteGuard guard(Lock_);
  23. File_.LinkTo(OpenFile(File_.GetName()));
  24. }
  25. private:
  26. static inline TFile OpenFile(const TString& path) {
  27. return TFile(path, OpenAlways | WrOnly | ForAppend | Seq | NoReuse);
  28. }
  29. private:
  30. TRWMutex Lock_;
  31. TFile File_;
  32. };
  33. TFileLogBackend::TFileLogBackend(const TString& path)
  34. : Impl_(new TImpl(path))
  35. {
  36. }
  37. TFileLogBackend::~TFileLogBackend() {
  38. }
  39. void TFileLogBackend::WriteData(const TLogRecord& rec) {
  40. Impl_->WriteData(rec);
  41. }
  42. void TFileLogBackend::ReopenLog() {
  43. TAtomicSharedPtr<TImpl> copy = Impl_;
  44. if (copy) {
  45. copy->ReopenLog();
  46. }
  47. }