file.cpp 1.1 KB

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