Hierarchical Log File Organization in C# .NET
Organize diagnostic logs on disk using a tiered directory structure: a root Log folder contains subdirectories for each service, which in turn hold monthly folders, with individual plain-text files for each calendar day.
The helper below traverses upward from the executable location to establish a project-relative log root, then constructs the necessary heirarchy and returns the absolute path for the current day's file:
using System;
using System.IO;
public static class DailyLogFactory
{
public static string BuildLogLocation(string serviceName)
{
string executionPath = AppDomain.CurrentDomain.BaseDirectory;
// Ascend three levels: typically bin → Debug → netX.X
string anchor = executionPath;
for (int level = 0; level < 3; level++)
{
DirectoryInfo parent = Directory.GetParent(anchor);
if (parent != null) anchor = parent.FullName;
}
string repository = Path.Combine(anchor, "Log");
string branch = Path.Combine(repository, serviceName);
string leaf = Path.Combine(branch, DateTime.Now.ToString("yyyyMM"));
Directory.CreateDirectory(leaf);
string dailyRecord = Path.Combine(leaf, $"{DateTime.Now:yyyyMMdd}.log");
if (!File.Exists(dailyRecord))
{
using (var handle = File.Create(dailyRecord)) { }
}
return dailyRecord;
}
}
Because Directory.CreateDirectory succeeds whether or not the target exists, the method avoids brittle conditional branching. Path.Combine produces correct separators for the host OS, and the using block guarantees the fille handle is released immediateyl after creation.
Write entries by resolving the path and appending formatted text:
string targetPath = DailyLogFactory.BuildLogLocation("WxService");
string payload = $"[{DateTime.Now}] Service started.{Environment.NewLine}";
File.AppendAllText(targetPath, payload);