< Summary

Information
Class: Chronicler.Diagnostics.DiagnosticLogger
Assembly: Chronicler.Diagnostics
File(s): /home/runner/work/Chronicler/Chronicler/src/Chronicler.Diagnostics/DiagnosticLogger.cs
Line coverage
100%
Covered lines: 46
Uncovered lines: 0
Coverable lines: 46
Total lines: 164
Line coverage: 100%
Branch coverage
100%
Covered branches: 12
Total branches: 12
Branch coverage: 100%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)100%11100%
get_Channel()100%11100%
get_DebugChannel()100%11100%
get_EnableDebugLogging()100%11100%
set_EnableDebugLogging(...)100%11100%
get_MinimumLevel()100%11100%
set_MinimumLevel(...)100%11100%
get_LogHandler()100%11100%
set_LogHandler(...)100%22100%
get_CustomFormatter()100%11100%
set_CustomFormatter(...)100%22100%
IsEnabled(...)100%11100%
DefaultLogHandler(...)100%22100%
DefaultLogFormatter(...)100%22100%
HandleDiagnosticEvent(...)100%11100%
ResolveSource(...)100%22100%
CreateChannel(...)100%11100%
RefreshDebugMinimumLevel()100%22100%

File(s)

/home/runner/work/Chronicler/Chronicler/src/Chronicler.Diagnostics/DiagnosticLogger.cs

#LineLine coverage
 1//=======================================================================
 2// DiagnosticLogger.cs
 3//=======================================================================
 4// MIT License, Copyright (c) 2024-present David Oravsky (mrdav30)
 5// See LICENSE file in the project root for full license information.
 6//=======================================================================
 7
 8namespace Chronicler.Diagnostics;
 9
 10using System;
 11using System.Diagnostics.CodeAnalysis;
 12
 13/// <summary>
 14/// Provides reusable logger state and diagnostic channels for libraries using Chronicler diagnostics.
 15/// </summary>
 16/// <remarks>
 17/// Static logger facades can delegate to a derived instance of this type while keeping their existing public API.
 18/// </remarks>
 19public abstract class DiagnosticLogger
 20{
 21    private readonly DiagnosticChannel _channel;
 22    private readonly DiagnosticChannel _debugChannel;
 23    private Action<DiagnosticLevel, string, string> _logHandler;
 24    private Func<DiagnosticLevel, string, string, string> _customFormatter;
 25    private bool _enableDebugLogging;
 26
 27    /// <summary>Creates normal and debug channels for a library logger.</summary>
 28    /// <param name="channelName">The shared channel label. Null or blank uses <c>Default</c>.</param>
 29    /// <remarks>Normal diagnostics start at Warning. Debug diagnostics start disabled.</remarks>
 730    protected DiagnosticLogger(string channelName)
 31    {
 732        _channel = CreateChannel(channelName);
 733        _debugChannel = CreateChannel(channelName);
 734        Name = _channel.Name;
 735        _logHandler = DefaultLogHandler;
 736        _customFormatter = DefaultLogFormatter;
 737        MinimumLevel = DiagnosticLevel.Warning;
 738        RefreshDebugMinimumLevel();
 739    }
 40
 41    /// <summary>Gets the logger label.</summary>
 42    /// <value>The normalized name shared by its two channels.</value>
 43    public string Name { get; }
 44
 45    /// <summary>Gets the normal diagnostics channel.</summary>
 46    /// <value>The same mutable channel throughout the logger's lifetime. Its initial threshold is Warning.</value>
 347    public DiagnosticChannel Channel => _channel;
 48
 49    /// <summary>Gets the independently gated debug channel.</summary>
 50    /// <value>The same mutable channel throughout the logger's lifetime. Its initial threshold is None.</value>
 551    public DiagnosticChannel DebugChannel => _debugChannel;
 52
 53    /// <summary>Gets or sets the debug gate.</summary>
 54    /// <value>False by default. Setting this property selects the normal threshold or disables the debug channel.</valu
 55    public bool EnableDebugLogging
 56    {
 157        get => _enableDebugLogging;
 58        set
 59        {
 160            _enableDebugLogging = value;
 161            RefreshDebugMinimumLevel();
 162        }
 63    }
 64
 65    /// <summary>Gets or sets the normal channel's threshold.</summary>
 66    /// <value>Setting the property also updates the debug threshold when debug logging is enabled.</value>
 67    public DiagnosticLevel MinimumLevel
 68    {
 169        get => _channel.MinimumLevel;
 70        set
 71        {
 1172            _channel.MinimumLevel = value;
 1173            RefreshDebugMinimumLevel();
 1174        }
 75    }
 76
 77    /// <summary>Gets or sets the log dispatch callback.</summary>
 78    /// <value>The retained callback receiving severity, message, and resolved source. Null restores <see cref="DefaultL
 79    [AllowNull]
 80    public Action<DiagnosticLevel, string, string> LogHandler
 81    {
 182        get => _logHandler;
 483        set => _logHandler = value ?? DefaultLogHandler;
 84    }
 85
 86    /// <summary>Gets or sets the formatter used by the default log handler.</summary>
 87    /// <value>The retained formatter mapping severity, message, and source to one entry. Null restores <see cref="Defau
 88    [AllowNull]
 89    public Func<DiagnosticLevel, string, string, string> CustomFormatter
 90    {
 491        get => _customFormatter;
 292        set => _customFormatter = value ?? DefaultLogFormatter;
 93    }
 94
 95    /// <summary>
 96    /// Determines whether normal diagnostics at the specified level are currently enabled.
 97    /// </summary>
 98    /// <param name="level">The diagnostic level to evaluate.</param>
 99    /// <returns><see langword="true"/> when messages at <paramref name="level"/> will be emitted; otherwise, <see langw
 100    public bool IsEnabled(DiagnosticLevel level)
 101    {
 2102        return _channel.IsEnabled(level);
 103    }
 104
 105    /// <summary>Formats a message and writes one console line.</summary>
 106    /// <param name="level">Error goes to standard error. Other levels go to standard output.</param>
 107    /// <param name="message">The text passed to the current formatter.</param>
 108    /// <param name="source">The origin label passed to the current formatter.</param>
 109    /// <remarks>Calling directly bypasses both channel thresholds.</remarks>
 110    public virtual void DefaultLogHandler(DiagnosticLevel level, string message, string source)
 111    {
 2112        string entry = CustomFormatter(level, message, source);
 2113        if (level == DiagnosticLevel.Error)
 1114            Console.Error.WriteLine(entry);
 115        else
 1116            Console.WriteLine(entry);
 1117    }
 118
 119    /// <summary>Formats a logger entry with severity and origin.</summary>
 120    /// <param name="level">The severity written in brackets.</param>
 121    /// <param name="message">The text appended after the logger and source prefix.</param>
 122    /// <param name="source">The suffix on the logger name. Null or whitespace omits the suffix.</param>
 123    /// <returns>Text of the form <c>[level] Name.Source: message</c>. The formatter adds no line break.</returns>
 124    public virtual string DefaultLogFormatter(DiagnosticLevel level, string message, string source)
 125    {
 5126        if (string.IsNullOrWhiteSpace(source))
 2127            return $"[{level}] {Name}: {message}";
 128
 3129        return $"[{level}] {Name}.{source}: {message}";
 130    }
 131
 132    /// <summary>Dispatches an event from either channel through the current log handler.</summary>
 133    /// <param name="diagnostic">The already enabled event whose severity, message, and resolved source are forwarded.</
 134    protected virtual void HandleDiagnosticEvent(in DiagnosticEvent diagnostic)
 135    {
 2136        _logHandler(diagnostic.Level, diagnostic.Message, ResolveSource(diagnostic));
 2137    }
 138
 139    /// <summary>Selects the origin label forwarded to the log handler.</summary>
 140    /// <param name="diagnostic">The event whose source and channel names are inspected.</param>
 141    /// <returns>The event's source, or its channel name when the source is blank.</returns>
 142    protected virtual string ResolveSource(in DiagnosticEvent diagnostic)
 143    {
 2144        return string.IsNullOrWhiteSpace(diagnostic.Source)
 2145            ? diagnostic.Channel
 2146            : diagnostic.Source;
 147    }
 148
 149    private DiagnosticChannel CreateChannel(string channelName)
 150    {
 14151        return new DiagnosticChannel(channelName)
 14152        {
 14153            MinimumLevel = DiagnosticLevel.Warning,
 14154            Sink = HandleDiagnosticEvent
 14155        };
 156    }
 157
 158    private void RefreshDebugMinimumLevel()
 159    {
 19160        _debugChannel.MinimumLevel = _enableDebugLogging
 19161            ? _channel.MinimumLevel
 19162            : DiagnosticLevel.None;
 19163    }
 164}