Kale
Loading...
Searching...
No Matches
Logger.cpp
Go to the documentation of this file.
1/*
2 Copyright 2022 Rishi Challa
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15*/
16
17#include "Logger.hpp"
18
20
21#include <filesystem>
22
23// Apple-clang doesn't support C++20's std::format properly
24#if defined(KALE_OSX) || defined(KALE_IOS)
25
26#include <date/date.h>
27#include <date/tz.h>
28
29#else
30
31#include <format>
32#include <chrono>
33
34#endif
35
36using namespace Kale;
37
42#ifdef KALE_DEBUG
43 std::cout.setf(std::ios::fixed, std::ios::floatfield);
44 std::cout.setf(std::ios::showpoint);
45#endif
46}
47
52void Logger::load(const std::string& applicationName) {
53
54 // Create the folder for this application if it doesn't already exist
55 if (!std::filesystem::exists("." + applicationName))
56 std::filesystem::create_directory("." + applicationName);
57 if (!std::filesystem::exists("." + applicationName + "/logs"))
58 std::filesystem::create_directory("." + applicationName + "/logs");
59
60 // Create/open the log file in the correct folder
61 #ifdef KALE_OSX
62 logFile.open("." + applicationName + "/logs/" + date::format("%F--%H-%M", std::chrono::system_clock::now()) + ".log");
63 #else
64 auto timestamp = std::chrono::time_point_cast<std::chrono::seconds>(std::chrono::system_clock::now());
65 logFile.open("." + applicationName + "/logs/" + std::format("{:%F--%H-%M}", std::chrono::zoned_time{std::chrono::current_zone(), timestamp}) + ".log");
66 #endif
67
68 #ifdef KALE_WINDOWS
69 HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
70 if (hOut == INVALID_HANDLE_VALUE) {
71 return;
72 }
73
74 DWORD dwMode = 0;
75 if (!GetConsoleMode(hOut, &dwMode)) {
76 return;
77 }
78
79 dwMode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING;
80 if (!SetConsoleMode(hOut, dwMode)) {
81 return;
82 }
83 #endif
84}
85
90std::string Logger::getTimePrefix() {
91 #ifdef KALE_OSX
92 // OSX Doesn't support C++ 20's std::format and std::chrono::zoned_time
93 return date::format("%I:%M %p", date::make_zoned(date::current_zone(), std::chrono::system_clock::now()));
94 #else
95 auto timestamp = std::chrono::time_point_cast<std::chrono::seconds>(std::chrono::system_clock::now());
96 return std::format("{:%I:%M %p}", std::chrono::zoned_time{std::chrono::current_zone(), timestamp});
97 #endif
98}
std::ofstream logFile
Definition Logger.hpp:96
std::string getTimePrefix()
Definition Logger.cpp:90
void load(const std::string &applicationName)
Definition Logger.cpp:52