-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConfigLoader.cs
More file actions
40 lines (37 loc) · 2.05 KB
/
ConfigLoader.cs
File metadata and controls
40 lines (37 loc) · 2.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
using System;
using System.IO;
using System.Text.Json;
namespace LogFileCollector
{
/// <summary>
/// Loads AppSettings from a JSON file using System.Text.Json.
/// </summary>
public static class ConfigLoader
{
public static AppSettings Load(string path)
{
string json = File.ReadAllText(path);
var options = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true,
ReadCommentHandling = JsonCommentHandling.Skip,
AllowTrailingCommas = true
};
AppSettings settings = JsonSerializer.Deserialize<AppSettings>(json, options);
// Minimal validation with clear error messages.
if (settings == null) throw new InvalidOperationException("Configuration could not be parsed.");
if (string.IsNullOrWhiteSpace(settings.SourceFolder)) throw new InvalidOperationException("SourceFolder is required.");
if (string.IsNullOrWhiteSpace(settings.TargetFolder)) throw new InvalidOperationException("TargetFolder is required.");
if (string.IsNullOrWhiteSpace(settings.Filter)) settings.Filter = "*.*";
if (settings.FileCreatedDelayMs <= 0) settings.FileCreatedDelayMs = 1000;
if (settings.Logging == null) throw new InvalidOperationException("Logging section is required.");
if (string.IsNullOrWhiteSpace(settings.Logging.LogFilePath)) settings.Logging.LogFilePath = "log.txt";
if (string.IsNullOrWhiteSpace(settings.Logging.LogOutputTemplate))
settings.Logging.LogOutputTemplate = "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}";
if (string.IsNullOrWhiteSpace(settings.Logging.LogLevel)) settings.Logging.LogLevel = "Information";
if (string.IsNullOrWhiteSpace(settings.Logging.RollingInterval)) settings.Logging.RollingInterval = "Day";
if (settings.Logging.RetainedFileCountLimit <= 0) settings.Logging.RetainedFileCountLimit = 10;
return settings;
}
}
}