Skip to content

Commit b0378e5

Browse files
committed
Add file output
1 parent 4be547b commit b0378e5

File tree

3 files changed

+20
-0
lines changed

3 files changed

+20
-0
lines changed

include/Logger.hpp

+3
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,15 @@
22

33
#include "Format.hpp"
44
#include "Log.hpp"
5+
#include <fstream>
56
#include <iostream>
67
#include <sstream>
78

89
namespace SSBL {
910
class Logger {
1011
public:
1112
Logger &Log(Level level = Level::Info);
13+
Logger &LogToFile(const std::string &filePath, Level level = Level::Info);
1214

1315
template<typename T>
1416
Logger &operator<<(const T &stream) {
@@ -34,6 +36,7 @@ class Logger {
3436
private:
3537
std::ostream *m_msgOutStream = &std::cout;
3638
std::ostream *m_errOutStream = &std::cerr;
39+
std::optional<std::ofstream> m_fileOutStream;
3740

3841
std::ostringstream m_stream;
3942
size_t insertCount = 0;

src/Logger.cpp

+13
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
#include "Logger.hpp"
22
#include "Log.hpp"
3+
#include <fstream>
34

45
#if _WIN32
56

@@ -10,7 +11,12 @@
1011
namespace SSBL {
1112

1213
Logger &Logger::Log(const Level level) {
14+
m_level = level;
15+
return *this;
16+
}
17+
Logger &Logger::LogToFile(const std::string &filePath, Level level) {
1318
m_level = level;
19+
m_fileOutStream = std::ofstream(filePath);
1420
return *this;
1521
}
1622

@@ -32,6 +38,13 @@ bool Logger::IsLevelIncluded(const Level level) const {
3238
}
3339

3440
void Logger::Send(const std::string &string) {
41+
if (m_fileOutStream.has_value()) {
42+
m_fileOutStream.value() << ToLog(string, m_level, m_config);
43+
m_fileOutStream.value().close();
44+
m_fileOutStream.reset();
45+
return;
46+
}
47+
3548
if (static_cast<bool>(m_config & Config::Color))
3649
SetColor();
3750

src/example/example.cpp

+4
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,12 @@ int main() {
1111
logger.Log(Level::Warning) << "Hello, Warning!\n";
1212
logger.Log(Level::Error) << "Hello, Error!\n";
1313
// logger.Log(Level::Fatal) << "Hello, Fatal!\n";
14+
// ^ Try and uncomment this
1415

1516
// Formatted output
1617
logger.Log(Level::Info) << "My name is {}, and I am {} years old." << "John" << 35 << '\n';
1718
logger.Log(Level::Info) << "{2}, {1}!" << "World" << "Hello" << '\n';
19+
20+
// File output
21+
logger.LogToFile("Example.log") << "Hello, File!\n";
1822
}

0 commit comments

Comments
 (0)