C# by Patrik

Logging Utilities for URL Handling in C#

In structured logging within C#, it's common to log endpoint URLs that consist of a base address and a path. To ensure safe and consistent logging, developers should use a centralized utility method to combine these values without risking exceptions or malformed URLs. This Snipp outlines two recommended approaches for implementing this functionality in a logging-safe way.

...see more

The CombineUrl method offers a safe, reusable way to concatenate a base URI and path string for logging purposes. It is wrapped in a try-catch block to avoid exceptions from malformed input, making it reliable for use in production logging. This method returns a string and can be placed inside a centralized LoggingHelpers class for consistent use across the codebase.

public static class LoggingHelpers
{
    public static string CombineUrl(Uri? baseAddress, string path)
    {
        try
        {
            if (string.IsNullOrWhiteSpace(path))  return baseAddress?.ToString() ?? string.Empty;

            if (baseAddress == null)  return path;

            return new Uri(baseAddress, path).ToString();
        }
        catch (Exception ex)
        {
            return $"[InvalidUrl: {ex.Message}]";
        }
    }
}
...see more

TryCombineUrl follows the .NET convention for “Try” methods by returning a bool indicating success and providing the result via an out parameter. This approach is ideal when logging failures explicitly or when avoiding exceptions is critical. It can be used in structured logging or conditional logging scenarios where fallback logic may be required.

public static class LoggingHelpers
{
    public static bool TryCombineUrl(Uri? baseAddress, string path, out string? fullUrl)
    {
        try
        {
            if (string.IsNullOrWhiteSpace(path))
            {
                fullUrl = baseAddress?.ToString() ?? string.Empty;
            }
            else if (baseAddress == null)
            {
                fullUrl = path;
            }
            else
            {
                fullUrl = new Uri(baseAddress, path).ToString();
            }

            return true;
        }
        catch
        {
            fullUrl = null;
            return false;
        }
    }
}

Comments