AuroraRuntime/Source/Logging/Sinks/FileSink.cpp
2024-04-10 11:05:00 +01:00

106 lines
2.4 KiB
C++

/***
Copyright (C) 2022 J Reece Wilson (a/k/a "Reece"). All rights reserved.
File: FileSink.cpp
Date: 2022-1-24
Author: Reece
***/
#include <Source/RuntimeInternal.hpp>
#include "FileSink.hpp"
namespace Aurora::Logging::Sinks
{
FIOSink::FIOSink(const AuString &path, bool bBinary) :
path_(path),
bBinary_(bBinary)
{
}
bool FIOSink::Init()
{
this->file_ = AuFS::OpenWriteUnique(this->path_, AuFS::EFileAdvisoryLockLevel::eBlockWrite);
return static_cast<bool>(this->file_);
}
void FIOSink::OnMessageBlocking(AuUInt8 uLevel, const ConsoleMessage &msg)
{
AU_LOCK_GUARD(this->logMutex_);
auto str = this->FormatMessageHelper(uLevel, msg, false, true, false);
auto startOffset = this->logBuffer_.GetWriteOffset();
if (this->bBinary_)
{
msg.Write(this->logBuffer_);
}
else
{
this->logBuffer_.reserve(this->logBuffer_.size() + str.size() + 2);
this->logBuffer_.Write(str.data(), str.size());
#if defined(AURORA_IS_MODERNNT_DERIVED)
this->logBuffer_.Write("\r\n", 2);
#else
this->logBuffer_.Write("\n", 1);
#endif
}
if (!this->logBuffer_)
{
this->logBuffer_.writePtr = this->logBuffer_.base + startOffset;
}
}
bool FIOSink::OnMessageNonblocking(AuUInt8 uLevel,
const ConsoleMessage &msg)
{
return true;
}
void FIOSink::OnFlush()
{
if (!this->logMutex_)
{
return;
}
AU_LOCK_GUARD(this->logMutex_);
if (!this->logBuffer_.RemainingBytes())
{
return;
}
this->file_->Write(AuMemoryViewStreamRead(this->logBuffer_));
this->logBuffer_.ResetPositions();
}
IFormattedSink *NewFileSinkNew(const AuString &str, bool bBinary)
{
try
{
auto pLogger = _new FIOSink(str, bBinary);
if (!pLogger)
{
return nullptr;
}
if (!pLogger->Init())
{
return nullptr;
}
return pLogger;
}
catch (...)
{
return {};
}
}
void NewFileSinkRelease(IFormattedSink *pLogger)
{
AuSafeDelete<FIOSink *>(pLogger);
}
}