DotNetDupe 4.0.6
C++17/20 Implementation of the .NET Base Class Library (BCL)
Loading...
Searching...
No Matches
LoggerConfiguration.cpp
Go to the documentation of this file.
1#include "pch.h"
3#include "System/IO/File.h"
8
9namespace {
10 using namespace DotNetDupe::System;
11 using namespace DotNetDupe::System::Text::Json;
12
13 bool TryGetPropertyCaseInsensitive(const JsonElement& element, const String& targetName, JsonElement& outProp) {
15 if (element.TryGetProperty(targetName, outProp)) {
16 return true;
17 }
18
20 auto normalize = [](const String& s) {
21 String lower = s.ToLower();
22 const char* raw = lower.GetRawString();
23 std::string cleaned;
24 if (raw) {
25 for (int iIdx = 0; raw[iIdx] != '\0'; ++iIdx) {
26 if (raw[iIdx] != '_') {
27 cleaned += raw[iIdx];
28 }
29 }
30 }
31 return String(cleaned.c_str());
32 };
33
34 String targetNormalized = normalize(targetName);
35
37 auto propNames = element.GetPropertyNames();
38 for (int iIdx = 0; iIdx < propNames.GetLength(); ++iIdx) {
39 if (normalize(propNames[iIdx]) == targetNormalized) {
40 return element.TryGetProperty(propNames[iIdx], outProp);
41 }
42 }
43 return false;
44 }
45}
46
47namespace DotNetDupe {
48 namespace System {
49 namespace Text {
50 namespace Json {
51
52 template <>
53 struct JsonConverter<DotNetDupe::Extensions::Logging::FileRolloverConfig> {
54 static JsonElement Write(const DotNetDupe::Extensions::Logging::FileRolloverConfig& value) {
56 JsonElement obj(JsonValueKind::Object);
57 obj.SetProperty("EnableRollover", JsonConverter<bool>::Write(value.EnableRollover));
58 obj.SetProperty("MaxFileSizeInBytes", JsonConverter<long long>::Write(value.MaxFileSizeInBytes));
59 obj.SetProperty("MaxBackupFiles", JsonConverter<int>::Write(value.MaxBackupFiles));
60 return obj;
61 }
62
63 static DotNetDupe::Extensions::Logging::FileRolloverConfig Read(const JsonElement& element) {
65 if (element.GetValueKind() != JsonValueKind::Object) {
66 throw JsonException("Expected a JSON object for FileRolloverConfig");
67 }
68 DotNetDupe::Extensions::Logging::FileRolloverConfig config;
69 JsonElement prop;
70
72 if (TryGetPropertyCaseInsensitive(element, "EnableRollover", prop)) {
74 }
75 if (TryGetPropertyCaseInsensitive(element, "MaxFileSizeInBytes", prop)) {
77 }
78 if (TryGetPropertyCaseInsensitive(element, "MaxBackupFiles", prop)) {
80 }
81 return config;
82 }
83 };
84
85 template <>
86 struct JsonConverter<DotNetDupe::Extensions::Logging::LoggerConfiguration> {
87 static JsonElement Write(const DotNetDupe::Extensions::Logging::LoggerConfiguration& value) {
89 JsonElement obj(JsonValueKind::Object);
90 const char* pMinLevelStr = "Information";
91 switch (value.MinLevel) {
92 case DotNetDupe::Extensions::Logging::LogLevel::Trace: pMinLevelStr = "Trace"; break;
93 case DotNetDupe::Extensions::Logging::LogLevel::Debug: pMinLevelStr = "Debug"; break;
94 case DotNetDupe::Extensions::Logging::LogLevel::Information: pMinLevelStr = "Information"; break;
95 case DotNetDupe::Extensions::Logging::LogLevel::Warning: pMinLevelStr = "Warning"; break;
96 case DotNetDupe::Extensions::Logging::LogLevel::Error: pMinLevelStr = "Error"; break;
97 case DotNetDupe::Extensions::Logging::LogLevel::Critical: pMinLevelStr = "Critical"; break;
98 case DotNetDupe::Extensions::Logging::LogLevel::None: pMinLevelStr = "None"; break;
99 default: break;
100 }
101
103 obj.SetProperty("MinLevel", JsonConverter<String>::Write(String(pMinLevelStr)));
104 obj.SetProperty("IsJsonFormat", JsonConverter<bool>::Write(value.IsJsonFormat));
105 obj.SetProperty("PlainTextFormat", JsonConverter<String>::Write(value.PlainTextFormat));
106 obj.SetProperty("TimestampFormat", JsonConverter<String>::Write(value.TimestampFormat));
107 obj.SetProperty("FilePath", JsonConverter<String>::Write(value.FilePath));
108 obj.SetProperty("Rollover", JsonConverter<DotNetDupe::Extensions::Logging::FileRolloverConfig>::Write(value.Rollover));
109 return obj;
110 }
111
112 static DotNetDupe::Extensions::Logging::LoggerConfiguration Read(const JsonElement& element) {
114 if (element.GetValueKind() != JsonValueKind::Object) {
115 throw JsonException("Expected a JSON object for LoggerConfiguration");
116 }
117 DotNetDupe::Extensions::Logging::LoggerConfiguration config;
118 JsonElement prop;
119
121 if (TryGetPropertyCaseInsensitive(element, "MinLevel", prop)) {
122 if (prop.GetValueKind() == JsonValueKind::Number) {
124 } else if (prop.GetValueKind() == JsonValueKind::String) {
126 } else {
127 throw JsonException("Invalid type for MinLevel in LoggerConfiguration");
128 }
129 }
130
132 if (TryGetPropertyCaseInsensitive(element, "IsJsonFormat", prop)) {
134 }
135 if (TryGetPropertyCaseInsensitive(element, "PlainTextFormat", prop)) {
137 }
138 if (TryGetPropertyCaseInsensitive(element, "TimestampFormat", prop)) {
140 }
141 if (TryGetPropertyCaseInsensitive(element, "FilePath", prop)) {
143 }
144 if (TryGetPropertyCaseInsensitive(element, "Rollover", prop)) {
145 config.Rollover = JsonConverter<DotNetDupe::Extensions::Logging::FileRolloverConfig>::Read(prop);
146 }
147 return config;
148 }
149 };
150
151 }
152 }
153 }
154}
155
156namespace DotNetDupe {
157 namespace Extensions {
158 namespace Logging {
159
162 DotNetDupe::System::String sLower = str.ToLower();
163
165 static const struct { const char* pName; LogLevel eLevel; } s_mappings[] = {
166 { "trace", LogLevel::Trace }, { "0", LogLevel::Trace },
167 { "debug", LogLevel::Debug }, { "1", LogLevel::Debug },
168 { "information", LogLevel::Information }, { "info", LogLevel::Information }, { "2", LogLevel::Information },
169 { "warning", LogLevel::Warning }, { "warn", LogLevel::Warning }, { "3", LogLevel::Warning },
170 { "error", LogLevel::Error }, { "4", LogLevel::Error },
171 { "critical", LogLevel::Critical }, { "5", LogLevel::Critical },
172 { "none", LogLevel::None }, { "6", LogLevel::None }
173 };
174
175 for (const auto& mapping : s_mappings) {
176 if (sLower == mapping.pName) return mapping.eLevel;
177 }
178
180 throw DotNetDupe::System::ArgumentException("Invalid LogLevel value");
181 }
182
186 throw DotNetDupe::System::IO::IOException("File does not exist");
187 }
188
191 return LoadFromJson(sJsonContent);
192 }
193
198
199 }
200 }
201}
202
Defines the exception thrown when an invalid argument is provided to a method.
Provides static methods for the creation, copying, deletion, moving, and opening of a single file.
The exception that is thrown when an I/O error occurs.
Exception thrown when invalid JSON payload or token is encountered per RFC 8259.
Provides functionality to serialize objects to JSON strings and deserialize JSON strings into objects...
The exception that is thrown when one of the arguments provided to a method is not valid.
static bool Exists(const String &sPath)
Determines whether the specified file exists.
Definition File.cpp:31
static String ReadAllText(const String &sPath)
Opens a text file, reads all the text in the file, and then closes the file.
Definition File.cpp:36
The exception that is thrown when an I/O error occurs.
Definition IOException.h:17
Represents text as a sequence of UTF-8 code units with culture-invariant operations.
Definition String.h:74
String ToLower() const
Definition String.cpp:672
String()
Initializes a new instance of the String class to an empty string.
Definition String.cpp:64
const char * GetRawString() const
Definition String.cpp:230
Represents a specific JSON value within a JsonDocument or object hierarchy.
Definition JsonElement.h:39
Array< String > GetPropertyNames() const
Gets an array containing the names of all properties on the current JSON object.
JsonValueKind GetValueKind() const
Gets the type of the current JSON value.
bool TryGetProperty(const String &sPropertyName, JsonElement &objValue) const
Looks for a property named propertyName in the current JSON object.
JsonException()
Initializes a new instance of the JsonException class with a default message.
static T Deserialize(const String &sJson)
Parses the text representing a single JSON value into an instance of the type specified by a generic ...
LogLevel
Defines logging severity levels.
Definition ILogger.h:15
@ Warning
Logs that highlight an abnormal or unexpected event.
Definition ILogger.h:23
@ Critical
Logs that describe an unrecoverable application or system crash.
Definition ILogger.h:27
@ None
Not used for writing log messages. Specifies that a logging category should not write any messages.
Definition ILogger.h:29
@ Error
Logs that highlight when the current flow of execution is stopped due to a failure.
Definition ILogger.h:25
@ Debug
Logs that are used for interactive investigation during development.
Definition ILogger.h:19
@ Information
Logs that track the general flow of the application.
Definition ILogger.h:21
@ Trace
Logs that contain the most detailed messages.
Definition ILogger.h:17
LogLevel ParseLogLevel(const DotNetDupe::System::String &str)
Parses a case-insensitive string into a corresponding LogLevel enumeration value.
long long MaxFileSizeInBytes
Maximum size in bytes of the primary log file before rotation (default: 5 MB).
bool EnableRollover
Indicates whether file rotation is enabled when file size threshold is reached.
int MaxBackupFiles
Maximum number of rotated backup log files to retain (default: 3).
Encapsulates logging system configuration options.
static LoggerConfiguration LoadFromFile(const DotNetDupe::System::String &filePath)
Loads logging configuration options from a JSON file.
DotNetDupe::System::String TimestampFormat
Timestamp formatting template using strftime syntax (e.g. "%Y-%m-%d %H:%M:%S").
DotNetDupe::System::String FilePath
Destination file path when file logging is configured.
bool IsJsonFormat
Specifies whether to serialize log messages as structured JSON objects.
DotNetDupe::System::String PlainTextFormat
Plain text formatting template (e.g. "{Timestamp} [{Level}] [{Category}] {Message}...
FileRolloverConfig Rollover
File rotation settings.
static LoggerConfiguration LoadFromJson(const DotNetDupe::System::String &jsonContent)
Loads logging configuration options from a raw JSON string.
LogLevel MinLevel
Minimum log level required for a message to be recorded.
static JsonElement Write(const String &value)
static String Read(const JsonElement &element)
static bool Read(const JsonElement &element)
static JsonElement Write(const bool &value)
static JsonElement Write(const int &value)
static int Read(const JsonElement &element)
static long long Read(const JsonElement &element)
static JsonElement Write(const long long &value)
Primary template for type-specific JSON serialization converters.