mirror of
https://github.com/ahwootech/BRUTAL.git
synced 2026-11-26 04:58:24 +01:00
SOURCE DUMP v1
This commit is contained in:
parent
bd62d51ec9
commit
fb20299e9d
4 changed files with 768360 additions and 0 deletions
18
brutal.logging/Brutal.Logging/DefaultCategory.cs
Normal file
18
brutal.logging/Brutal.Logging/DefaultCategory.cs
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
namespace Brutal.Logging;
|
||||
|
||||
/// <summary>
|
||||
/// A default log category to use when no other is specified
|
||||
/// </summary>
|
||||
/// <example>
|
||||
/// The following code demonstrates how to import the default logger globally:
|
||||
/// <code>
|
||||
/// global using static Brutal.Logging.DefaultCategory;
|
||||
/// </code>
|
||||
/// </example>
|
||||
public static class DefaultCategory
|
||||
{
|
||||
/// <summary>
|
||||
/// A default log category
|
||||
/// </summary>
|
||||
public static readonly LogCategory Log = LogCategory.Make("Default");
|
||||
}
|
||||
267
brutal.logging/Brutal.Logging/LogCategory.cs
Normal file
267
brutal.logging/Brutal.Logging/LogCategory.cs
Normal file
|
|
@ -0,0 +1,267 @@
|
|||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Runtime.CompilerServices;
|
||||
using Brutal.Logging.Internal;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Brutal.Logging;
|
||||
|
||||
/// <summary>
|
||||
/// Represents an abstract logging category that provides methods for structured logging.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// A logging category is designed to group related logging messages and control the logging level.
|
||||
/// This class provides various logging methods to handle message logging at different levels.
|
||||
/// Implementations of this abstract class define specific behavior for each category.
|
||||
/// </remarks>
|
||||
public sealed class LogCategory
|
||||
{
|
||||
#region Categories
|
||||
|
||||
internal static readonly Dictionary<string, LogCategory> Categories = [];
|
||||
|
||||
/// <summary>
|
||||
/// Gets a logging category by name.
|
||||
/// </summary>
|
||||
/// <exception cref="KeyNotFoundException">Thrown if the category does not exist.</exception>
|
||||
public static LogCategory Get(string categoryName)
|
||||
{
|
||||
return Categories[categoryName];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Tries to get a logging category by name.
|
||||
/// </summary>
|
||||
public static bool TryGet(string categoryName, [MaybeNullWhen(false)] out LogCategory category)
|
||||
{
|
||||
return Categories.TryGetValue(categoryName, out category);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Tries to get a logging category by name, or creates it if it does not exist.
|
||||
/// </summary>
|
||||
public static LogCategory Make(string categoryName)
|
||||
{
|
||||
if (Categories.TryGetValue(categoryName, out var category))
|
||||
return category;
|
||||
|
||||
category = new LogCategory(categoryName) { Logger = LogSystem.Factory?.CreateLogger(categoryName) };
|
||||
|
||||
Categories[categoryName] = category;
|
||||
return category;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
/// <summary>
|
||||
/// Represents the name of the logging category.
|
||||
/// This property is used to uniquely identify a specific logging category, allowing
|
||||
/// for categorization and filtering of logged messages.
|
||||
/// </summary>
|
||||
public string Name { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Represents whether this category is enabled and will display logs
|
||||
/// </summary>
|
||||
public bool IsCategoryEnabled = true;
|
||||
|
||||
/// <summary>
|
||||
/// Represents whether the caller info (member name, file path, line number) should be displayed in the logs
|
||||
/// </summary>
|
||||
public bool AppendCallerInfo = false;
|
||||
|
||||
public ILogger? Logger { get; internal set; }
|
||||
|
||||
/// <summary>
|
||||
/// Represents a logging category that provides methods for structured and leveled logging.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// A logging category is a logical grouping for log entries, enabling control over log level filtering and organization.
|
||||
/// The class serves as a base for defining specific logging behavior.
|
||||
/// </remarks>
|
||||
private LogCategory(string name)
|
||||
{
|
||||
Name = name;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Logging will be skipped for this category if these conditions are not met
|
||||
/// </summary>
|
||||
private bool LoggingEnabled => LogSystem.IsEnabled && IsCategoryEnabled;
|
||||
|
||||
/// <summary>
|
||||
/// Is logging enabled for this category at this level?
|
||||
/// </summary>
|
||||
public bool IsEnabled(LogLevel level) =>
|
||||
LogSystem.IsEnabled && IsCategoryEnabled && Logger?.IsEnabled(level) == true;
|
||||
|
||||
/// <summary>
|
||||
/// Logs a message at the given level, with optional details about the source member, file, and line number.
|
||||
/// </summary>
|
||||
/// <param name="logLevel">The level to log on.</param>
|
||||
/// <param name="message">The message to log.</param>
|
||||
/// <param name="sourceMemberName">The name of the method that invokes this log call. Automatically populated by the CallerMemberName attribute if not specified.</param>
|
||||
/// <param name="sourceFilePath">The file path of the caller. Automatically populated by the CallerFilePath attribute if not specified.</param>
|
||||
/// <param name="sourceLineNumber">The line number in the source file where the log call originates. Automatically populated by the CallerLineNumber attribute if not specified.</param>
|
||||
/// <param name="appendCallerInfo">For internal use, to forcibly append caller information even if <see cref="AppendCallerInfo"/> is false.
|
||||
/// Defaults to null i.e. follow <see cref="AppendCallerInfo"/>.</param>
|
||||
private void Log<TLevel>(
|
||||
LogLevel logLevel,
|
||||
[InterpolatedStringHandlerArgument("")] LogString<TLevel> message = default,
|
||||
[CallerMemberName] string sourceMemberName = "",
|
||||
[CallerFilePath] string sourceFilePath = "",
|
||||
[CallerLineNumber] int sourceLineNumber = 0,
|
||||
bool? appendCallerInfo = null
|
||||
)
|
||||
where TLevel : unmanaged, ILogLevel
|
||||
{
|
||||
// Thread-safety paranoia: drain the handler first to avoid leaking the rented StringBuilder
|
||||
// in case a guard below mismatches due to a race condition
|
||||
// (level/logger state flipped on another thread between ctor and here).
|
||||
var messageString = message.ToStringAndClear();
|
||||
|
||||
if (!LoggingEnabled)
|
||||
return;
|
||||
|
||||
if (Logger is null)
|
||||
throw new LogNotInitializedException();
|
||||
|
||||
if (!Logger.IsEnabled(logLevel))
|
||||
return;
|
||||
|
||||
// A span pass-through materializes only now: unlike the rented SB drained above it holds
|
||||
// no pooled resource, so deferring past the guards keeps suppressed logs allocation-free.
|
||||
messageString ??= message.Span.ToString();
|
||||
|
||||
if (appendCallerInfo ?? AppendCallerInfo)
|
||||
{
|
||||
Logger.Log(
|
||||
logLevel,
|
||||
"{Message} {SourceMemberName} (in {SourceFilePath}:{SourceLineNumber})",
|
||||
messageString,
|
||||
sourceMemberName,
|
||||
sourceFilePath,
|
||||
sourceLineNumber
|
||||
);
|
||||
}
|
||||
else
|
||||
Logger.Log(logLevel, messageString);
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="Log{TLevel}"/>
|
||||
public void Log(
|
||||
LogLevel logLevel,
|
||||
[InterpolatedStringHandlerArgument("", nameof(logLevel))] LogString<Dynamic> message = default,
|
||||
[CallerMemberName] string sourceMemberName = "",
|
||||
[CallerFilePath] string sourceFilePath = "",
|
||||
[CallerLineNumber] int sourceLineNumber = 0
|
||||
)
|
||||
{
|
||||
Log<Dynamic>(logLevel, message, sourceMemberName, sourceFilePath, sourceLineNumber);
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="Log{TLevel}"/>
|
||||
public void Trace(
|
||||
[InterpolatedStringHandlerArgument("")] LogString<Trace> message = default,
|
||||
[CallerMemberName] string sourceMemberName = "",
|
||||
[CallerFilePath] string sourceFilePath = "",
|
||||
[CallerLineNumber] int sourceLineNumber = 0
|
||||
)
|
||||
{
|
||||
Log(LogLevel.Trace, message, sourceMemberName, sourceFilePath, sourceLineNumber);
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="Log{TLevel}"/>
|
||||
public void Debug(
|
||||
[InterpolatedStringHandlerArgument("")] LogString<Debug> message = default,
|
||||
[CallerMemberName] string sourceMemberName = "",
|
||||
[CallerFilePath] string sourceFilePath = "",
|
||||
[CallerLineNumber] int sourceLineNumber = 0
|
||||
)
|
||||
{
|
||||
Log(LogLevel.Debug, message, sourceMemberName, sourceFilePath, sourceLineNumber);
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="Log{TLevel}"/>
|
||||
public void Info(
|
||||
[InterpolatedStringHandlerArgument("")] LogString<Information> message = default,
|
||||
[CallerMemberName] string sourceMemberName = "",
|
||||
[CallerFilePath] string sourceFilePath = "",
|
||||
[CallerLineNumber] int sourceLineNumber = 0
|
||||
)
|
||||
{
|
||||
Log(LogLevel.Information, message, sourceMemberName, sourceFilePath, sourceLineNumber);
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="Log{TLevel}"/>
|
||||
public void Warning(
|
||||
[InterpolatedStringHandlerArgument("")] LogString<Warning> message = default,
|
||||
[CallerMemberName] string sourceMemberName = "",
|
||||
[CallerFilePath] string sourceFilePath = "",
|
||||
[CallerLineNumber] int sourceLineNumber = 0
|
||||
)
|
||||
{
|
||||
Log(LogLevel.Warning, message, sourceMemberName, sourceFilePath, sourceLineNumber);
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="Log{TLevel}"/>
|
||||
public void Error(
|
||||
[InterpolatedStringHandlerArgument("")] LogString<Error> message = default,
|
||||
[CallerMemberName] string sourceMemberName = "",
|
||||
[CallerFilePath] string sourceFilePath = "",
|
||||
[CallerLineNumber] int sourceLineNumber = 0
|
||||
)
|
||||
{
|
||||
Log(LogLevel.Error, message, sourceMemberName, sourceFilePath, sourceLineNumber);
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="Log{TLevel}"/>
|
||||
public void Critical(
|
||||
[InterpolatedStringHandlerArgument("")] LogString<Critical> message = default,
|
||||
[CallerMemberName] string sourceMemberName = "",
|
||||
[CallerFilePath] string sourceFilePath = "",
|
||||
[CallerLineNumber] int sourceLineNumber = 0
|
||||
)
|
||||
{
|
||||
Log(LogLevel.Critical, message, sourceMemberName, sourceFilePath, sourceLineNumber);
|
||||
}
|
||||
|
||||
#pragma warning disable CS1573 // Parameter has no matching param tag in the XML comment (but other parameters do)
|
||||
/// <inheritdoc cref="Log{TLevel}"/>
|
||||
/// <param name="exception">The exception object containing details for the logged error message.</param>
|
||||
public void Error(
|
||||
Exception exception,
|
||||
[CallerMemberName] string sourceMemberName = "",
|
||||
[CallerFilePath] string sourceFilePath = "",
|
||||
[CallerLineNumber] int sourceLineNumber = 0
|
||||
)
|
||||
{
|
||||
Log<Error>(
|
||||
LogLevel.Error,
|
||||
$"{exception}",
|
||||
sourceMemberName,
|
||||
sourceFilePath,
|
||||
sourceLineNumber,
|
||||
appendCallerInfo: true
|
||||
);
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="Log{TLevel}"/>
|
||||
/// <param name="exception">The exception object containing details for the logged critical message.</param>
|
||||
public void Critical(
|
||||
Exception exception,
|
||||
[CallerMemberName] string sourceMemberName = "",
|
||||
[CallerFilePath] string sourceFilePath = "",
|
||||
[CallerLineNumber] int sourceLineNumber = 0
|
||||
)
|
||||
{
|
||||
Log<Critical>(
|
||||
LogLevel.Critical,
|
||||
$"{exception}",
|
||||
sourceMemberName,
|
||||
sourceFilePath,
|
||||
sourceLineNumber,
|
||||
appendCallerInfo: true
|
||||
);
|
||||
}
|
||||
#pragma warning restore CS1573 // Parameter has no matching param tag in the XML comment (but other parameters do)
|
||||
}
|
||||
136
brutal.logging/Brutal.Logging/LogString.cs
Normal file
136
brutal.logging/Brutal.Logging/LogString.cs
Normal file
|
|
@ -0,0 +1,136 @@
|
|||
using System.ComponentModel;
|
||||
using System.Runtime.CompilerServices;
|
||||
using Brutal.Strings;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Brutal.Logging.Internal;
|
||||
|
||||
// NOTE: purposely not using static abstract here for potential .NET Standard compatibility.
|
||||
[EditorBrowsable(EditorBrowsableState.Never)]
|
||||
public interface ILogLevel
|
||||
{
|
||||
LogLevel Level { get; }
|
||||
}
|
||||
|
||||
[EditorBrowsable(EditorBrowsableState.Never)]
|
||||
public readonly struct Trace : ILogLevel
|
||||
{
|
||||
public LogLevel Level => LogLevel.Trace;
|
||||
}
|
||||
|
||||
[EditorBrowsable(EditorBrowsableState.Never)]
|
||||
public readonly struct Debug : ILogLevel
|
||||
{
|
||||
public LogLevel Level => LogLevel.Debug;
|
||||
}
|
||||
|
||||
[EditorBrowsable(EditorBrowsableState.Never)]
|
||||
public readonly struct Information : ILogLevel
|
||||
{
|
||||
public LogLevel Level => LogLevel.Information;
|
||||
}
|
||||
|
||||
[EditorBrowsable(EditorBrowsableState.Never)]
|
||||
public readonly struct Warning : ILogLevel
|
||||
{
|
||||
public LogLevel Level => LogLevel.Warning;
|
||||
}
|
||||
|
||||
[EditorBrowsable(EditorBrowsableState.Never)]
|
||||
public readonly struct Error : ILogLevel
|
||||
{
|
||||
public LogLevel Level => LogLevel.Error;
|
||||
}
|
||||
|
||||
[EditorBrowsable(EditorBrowsableState.Never)]
|
||||
public readonly struct Critical : ILogLevel
|
||||
{
|
||||
public LogLevel Level => LogLevel.Critical;
|
||||
}
|
||||
|
||||
[EditorBrowsable(EditorBrowsableState.Never)]
|
||||
public readonly struct Dynamic : ILogLevel
|
||||
{
|
||||
public LogLevel Level =>
|
||||
throw new InvalidOperationException(
|
||||
"LogString<Dynamic> must receive its LogLevel via the 5-param ctor; never call default(Dynamic).Level."
|
||||
);
|
||||
}
|
||||
|
||||
/// Conditionally suppresses interpolation when the category is disabled. Compiler-only - not for manual construction.
|
||||
[InterpolatedStringHandler, EditorBrowsable(EditorBrowsableState.Never)]
|
||||
public readonly ref struct LogString<TLevel>
|
||||
where TLevel : unmanaged, ILogLevel
|
||||
{
|
||||
private readonly StringBuilder<char>? _sb;
|
||||
|
||||
public LogString(
|
||||
int literalLength,
|
||||
int formattedCount,
|
||||
LogCategory category,
|
||||
LogLevel logLevel,
|
||||
out bool shouldAppend
|
||||
)
|
||||
{
|
||||
shouldAppend = category.IsEnabled(logLevel);
|
||||
_sb = shouldAppend ? StringBuilderPool<char>.Shared.Get() : null;
|
||||
}
|
||||
|
||||
public LogString(int literalLength, int formattedCount, LogCategory category, out bool shouldAppend)
|
||||
: this(literalLength, formattedCount, category, default(TLevel).Level, out shouldAppend) { }
|
||||
|
||||
public void AppendLiteral(string value) => _sb?.Append(value);
|
||||
|
||||
public void AppendFormatted<T>(T value, int alignment = 0, string? format = null) =>
|
||||
_sb?.Append(value, alignment, format);
|
||||
|
||||
// ref-struct holes can't flow through AppendFormatted<T> (no `allows ref struct`).
|
||||
public void AppendFormatted(ReadOnlySpan<byte> value, int alignment = 0, string? format = null) =>
|
||||
_sb?.Append(value, alignment);
|
||||
|
||||
public void AppendFormatted(ReadOnlySpan<char> value, int alignment = 0, string? format = null) =>
|
||||
_sb?.Append(value, alignment);
|
||||
|
||||
public void AppendFormatted(string? value, int alignment = 0, string? format = null) =>
|
||||
_sb?.Append(value, alignment);
|
||||
|
||||
#region string pass-through
|
||||
|
||||
private readonly string? _message;
|
||||
|
||||
private LogString(string message) => _message = message;
|
||||
|
||||
public static implicit operator LogString<TLevel>(string message) => new(message);
|
||||
|
||||
#endregion
|
||||
|
||||
#region span pass-through
|
||||
|
||||
private readonly ReadOnlySpan<char> _span;
|
||||
|
||||
private LogString(ReadOnlySpan<char> message) => _span = message;
|
||||
|
||||
public static implicit operator LogString<TLevel>(ReadOnlySpan<char> message) => new(message);
|
||||
|
||||
/* Exposed as a raw span, not a "SpanToString"-style method: unlike ToStringAndClear, which
|
||||
LogCategory.Log must call unconditionally before the enabled guards (pool-return paranoia),
|
||||
a span holds no pooled resource, so its .ToString() can - and must - wait until after the
|
||||
guards, or every suppressed log pays for a string it never uses. */
|
||||
internal ReadOnlySpan<char> Span => _span;
|
||||
|
||||
#endregion
|
||||
|
||||
/// Don't call this twice as the StringBuilder will be returned to the pool.
|
||||
internal string? ToStringAndClear()
|
||||
{
|
||||
if (_message != null)
|
||||
return _message;
|
||||
|
||||
if (_sb is null)
|
||||
return null;
|
||||
|
||||
var result = _sb.WrittenSpan.ToString();
|
||||
StringBuilderPool<char>.Shared.Return(_sb);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
40
brutal.logging/Brutal.Logging/LogSystem.cs
Normal file
40
brutal.logging/Brutal.Logging/LogSystem.cs
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Brutal.Logging;
|
||||
|
||||
/// <summary>
|
||||
/// Base class for all logging exceptions
|
||||
/// </summary>
|
||||
public class LogException(string message) : Exception(message);
|
||||
|
||||
/// <summary>
|
||||
/// Exception thrown when the logging system is used before being initialized
|
||||
/// </summary>
|
||||
public class LogNotInitializedException()
|
||||
: LogException("Log not initialized. Call Log.Initialize before using the logging system.");
|
||||
|
||||
/// <summary>
|
||||
/// Static class for handling logging functionality across the framework.
|
||||
/// Provides methods for initializing, printing, and managing log messages
|
||||
/// with different log levels, as well as interacting with external configurations.
|
||||
/// </summary>
|
||||
public static class LogSystem
|
||||
{
|
||||
internal static ILoggerFactory? Factory;
|
||||
|
||||
/// <summary>
|
||||
/// Enable or Disable all logging completely
|
||||
/// </summary>
|
||||
public static bool IsEnabled = false;
|
||||
|
||||
/// <summary>
|
||||
/// Initialize and enable the log system
|
||||
/// </summary>
|
||||
public static void Initialize(Action<ILoggingBuilder> builder)
|
||||
{
|
||||
IsEnabled = true;
|
||||
Factory = LoggerFactory.Create(builder);
|
||||
foreach (var (categoryName, category) in LogCategory.Categories)
|
||||
category.Logger = Factory.CreateLogger(categoryName);
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue