AppInstallerFileLogger.h (1728B)
1 // Copyright (c) Microsoft Corporation. 2 // Licensed under the MIT License. 3 #pragma once 4 #include <AppInstallerLogging.h> 5 6 #include <filesystem> 7 #include <fstream> 8 #include <string> 9 #include <string_view> 10 11 namespace AppInstaller::Logging 12 { 13 // Logs to a file. 14 struct FileLogger : public ILogger 15 { 16 FileLogger(); 17 explicit FileLogger(const std::filesystem::path& filePath); 18 explicit FileLogger(const std::string_view fileNamePrefix); 19 20 ~FileLogger(); 21 22 FileLogger(const FileLogger&) = delete; 23 FileLogger& operator=(const FileLogger&) = delete; 24 25 FileLogger(FileLogger&&) = default; 26 FileLogger& operator=(FileLogger&&) = default; 27 28 static std::string GetNameForPath(const std::filesystem::path& filePath); 29 30 static std::string_view DefaultPrefix(); 31 static std::string_view DefaultExt(); 32 33 // ILogger 34 std::string GetName() const override; 35 36 void Write(Channel channel, Level level, std::string_view message) noexcept override; 37 38 void WriteDirect(Channel channel, Level level, std::string_view message) noexcept override; 39 40 // Adds a FileLogger to the current Log 41 static void Add(); 42 static void Add(const std::filesystem::path& filePath); 43 static void Add(std::string_view fileNamePrefix); 44 45 // Starts a background task to clean up old log files. 46 static void BeginCleanup(); 47 static void BeginCleanup(const std::filesystem::path& filePath); 48 49 private: 50 std::string m_name; 51 std::filesystem::path m_filePath; 52 std::ofstream m_stream; 53 54 void OpenFileLoggerStream(); 55 }; 56 }