coding styles nullable

This commit is contained in:
2019-12-08 19:54:52 +01:00
parent c78348324a
commit aa9fcd4a36
109 changed files with 12952 additions and 14462 deletions
+133 -140
View File
@@ -1,146 +1,139 @@
using System;
using Swan.Lite.Logging;
namespace Swan.Logging
{
namespace Swan.Logging {
/// <summary>
/// Represents a Console implementation of <c>ILogger</c>.
/// </summary>
/// <seealso cref="ILogger" />
public class ConsoleLogger : TextLogger, ILogger {
/// <summary>
/// Represents a Console implementation of <c>ILogger</c>.
/// Initializes a new instance of the <see cref="ConsoleLogger"/> class.
/// </summary>
/// <seealso cref="ILogger" />
public class ConsoleLogger : TextLogger, ILogger
{
/// <summary>
/// Initializes a new instance of the <see cref="ConsoleLogger"/> class.
/// </summary>
protected ConsoleLogger()
{
// Empty
}
/// <summary>
/// Gets the current instance of ConsoleLogger.
/// </summary>
/// <value>
/// The instance.
/// </value>
public static ConsoleLogger Instance { get; } = new ConsoleLogger();
/// <summary>
/// Gets or sets the debug logging prefix.
/// </summary>
/// <value>
/// The debug prefix.
/// </value>
public static string DebugPrefix { get; set; } = "DBG";
/// <summary>
/// Gets or sets the trace logging prefix.
/// </summary>
/// <value>
/// The trace prefix.
/// </value>
public static string TracePrefix { get; set; } = "TRC";
/// <summary>
/// Gets or sets the warning logging prefix.
/// </summary>
/// <value>
/// The warn prefix.
/// </value>
public static string WarnPrefix { get; set; } = "WRN";
/// <summary>
/// Gets or sets the fatal logging prefix.
/// </summary>
/// <value>
/// The fatal prefix.
/// </value>
public static string FatalPrefix { get; set; } = "FAT";
/// <summary>
/// Gets or sets the error logging prefix.
/// </summary>
/// <value>
/// The error prefix.
/// </value>
public static string ErrorPrefix { get; set; } = "ERR";
/// <summary>
/// Gets or sets the information logging prefix.
/// </summary>
/// <value>
/// The information prefix.
/// </value>
public static string InfoPrefix { get; set; } = "INF";
/// <summary>
/// Gets or sets the color of the information output logging.
/// </summary>
/// <value>
/// The color of the information.
/// </value>
public static ConsoleColor InfoColor { get; set; } = ConsoleColor.Cyan;
/// <summary>
/// Gets or sets the color of the debug output logging.
/// </summary>
/// <value>
/// The color of the debug.
/// </value>
public static ConsoleColor DebugColor { get; set; } = ConsoleColor.Gray;
/// <summary>
/// Gets or sets the color of the trace output logging.
/// </summary>
/// <value>
/// The color of the trace.
/// </value>
public static ConsoleColor TraceColor { get; set; } = ConsoleColor.DarkGray;
/// <summary>
/// Gets or sets the color of the warning logging.
/// </summary>
/// <value>
/// The color of the warn.
/// </value>
public static ConsoleColor WarnColor { get; set; } = ConsoleColor.Yellow;
/// <summary>
/// Gets or sets the color of the error logging.
/// </summary>
/// <value>
/// The color of the error.
/// </value>
public static ConsoleColor ErrorColor { get; set; } = ConsoleColor.DarkRed;
/// <summary>
/// Gets or sets the color of the error logging.
/// </summary>
/// <value>
/// The color of the error.
/// </value>
public static ConsoleColor FatalColor { get; set; } = ConsoleColor.Red;
/// <inheritdoc />
public LogLevel LogLevel { get; set; } = DebugLogger.IsDebuggerAttached ? LogLevel.Trace : LogLevel.Info;
/// <inheritdoc />
public void Log(LogMessageReceivedEventArgs logEvent)
{
// Select the writer based on the message type
var writer = logEvent.MessageType == LogLevel.Error
? TerminalWriters.StandardError
: TerminalWriters.StandardOutput;
var (outputMessage, color) = GetOutputAndColor(logEvent);
Terminal.Write(outputMessage, color, writer);
}
/// <inheritdoc />
public void Dispose()
{
// Do nothing
}
}
protected ConsoleLogger() {
// Empty
}
/// <summary>
/// Gets the current instance of ConsoleLogger.
/// </summary>
/// <value>
/// The instance.
/// </value>
public static ConsoleLogger Instance { get; } = new ConsoleLogger();
/// <summary>
/// Gets or sets the debug logging prefix.
/// </summary>
/// <value>
/// The debug prefix.
/// </value>
public static String DebugPrefix { get; set; } = "DBG";
/// <summary>
/// Gets or sets the trace logging prefix.
/// </summary>
/// <value>
/// The trace prefix.
/// </value>
public static String TracePrefix { get; set; } = "TRC";
/// <summary>
/// Gets or sets the warning logging prefix.
/// </summary>
/// <value>
/// The warn prefix.
/// </value>
public static String WarnPrefix { get; set; } = "WRN";
/// <summary>
/// Gets or sets the fatal logging prefix.
/// </summary>
/// <value>
/// The fatal prefix.
/// </value>
public static String FatalPrefix { get; set; } = "FAT";
/// <summary>
/// Gets or sets the error logging prefix.
/// </summary>
/// <value>
/// The error prefix.
/// </value>
public static String ErrorPrefix { get; set; } = "ERR";
/// <summary>
/// Gets or sets the information logging prefix.
/// </summary>
/// <value>
/// The information prefix.
/// </value>
public static String InfoPrefix { get; set; } = "INF";
/// <summary>
/// Gets or sets the color of the information output logging.
/// </summary>
/// <value>
/// The color of the information.
/// </value>
public static ConsoleColor InfoColor { get; set; } = ConsoleColor.Cyan;
/// <summary>
/// Gets or sets the color of the debug output logging.
/// </summary>
/// <value>
/// The color of the debug.
/// </value>
public static ConsoleColor DebugColor { get; set; } = ConsoleColor.Gray;
/// <summary>
/// Gets or sets the color of the trace output logging.
/// </summary>
/// <value>
/// The color of the trace.
/// </value>
public static ConsoleColor TraceColor { get; set; } = ConsoleColor.DarkGray;
/// <summary>
/// Gets or sets the color of the warning logging.
/// </summary>
/// <value>
/// The color of the warn.
/// </value>
public static ConsoleColor WarnColor { get; set; } = ConsoleColor.Yellow;
/// <summary>
/// Gets or sets the color of the error logging.
/// </summary>
/// <value>
/// The color of the error.
/// </value>
public static ConsoleColor ErrorColor { get; set; } = ConsoleColor.DarkRed;
/// <summary>
/// Gets or sets the color of the error logging.
/// </summary>
/// <value>
/// The color of the error.
/// </value>
public static ConsoleColor FatalColor { get; set; } = ConsoleColor.Red;
/// <inheritdoc />
public LogLevel LogLevel { get; set; } = DebugLogger.IsDebuggerAttached ? LogLevel.Trace : LogLevel.Info;
/// <inheritdoc />
public void Log(LogMessageReceivedEventArgs logEvent) {
// Select the writer based on the message type
TerminalWriters writer = logEvent.MessageType == LogLevel.Error ? TerminalWriters.StandardError : TerminalWriters.StandardOutput;
(String outputMessage, ConsoleColor color) = this.GetOutputAndColor(logEvent);
Terminal.Write(outputMessage, color, writer);
}
/// <inheritdoc />
public void Dispose() {
// Do nothing
}
}
}
+45 -49
View File
@@ -1,53 +1,49 @@
using Swan.Lite.Logging;
using System;
using Swan.Lite.Logging;
namespace Swan.Logging
{
namespace Swan.Logging {
/// <summary>
/// Represents a logger target. This target will write to the
/// Debug console using System.Diagnostics.Debug.
/// </summary>
/// <seealso cref="ILogger" />
public class DebugLogger : TextLogger, ILogger {
/// <summary>
/// Represents a logger target. This target will write to the
/// Debug console using System.Diagnostics.Debug.
/// Initializes a new instance of the <see cref="DebugLogger"/> class.
/// </summary>
/// <seealso cref="ILogger" />
public class DebugLogger : TextLogger, ILogger
{
/// <summary>
/// Initializes a new instance of the <see cref="DebugLogger"/> class.
/// </summary>
protected DebugLogger()
{
// Empty
}
/// <summary>
/// Gets the current instance of DebugLogger.
/// </summary>
/// <value>
/// The instance.
/// </value>
public static DebugLogger Instance { get; } = new DebugLogger();
/// <summary>
/// Gets a value indicating whether a debugger is attached.
/// </summary>
/// <value>
/// <c>true</c> if this instance is debugger attached; otherwise, <c>false</c>.
/// </value>
public static bool IsDebuggerAttached => System.Diagnostics.Debugger.IsAttached;
/// <inheritdoc/>
public LogLevel LogLevel { get; set; } = IsDebuggerAttached ? LogLevel.Trace : LogLevel.None;
/// <inheritdoc/>
public void Log(LogMessageReceivedEventArgs logEvent)
{
var (outputMessage, _) = GetOutputAndColor(logEvent);
System.Diagnostics.Debug.Write(outputMessage);
}
/// <inheritdoc/>
public void Dispose()
{
// do nothing
}
}
protected DebugLogger() {
// Empty
}
/// <summary>
/// Gets the current instance of DebugLogger.
/// </summary>
/// <value>
/// The instance.
/// </value>
public static DebugLogger Instance { get; } = new DebugLogger();
/// <summary>
/// Gets a value indicating whether a debugger is attached.
/// </summary>
/// <value>
/// <c>true</c> if this instance is debugger attached; otherwise, <c>false</c>.
/// </value>
public static Boolean IsDebuggerAttached => System.Diagnostics.Debugger.IsAttached;
/// <inheritdoc/>
public LogLevel LogLevel { get; set; } = IsDebuggerAttached ? LogLevel.Trace : LogLevel.None;
/// <inheritdoc/>
public void Log(LogMessageReceivedEventArgs logEvent) {
(String outputMessage, ConsoleColor _) = this.GetOutputAndColor(logEvent);
System.Diagnostics.Debug.Write(outputMessage);
}
/// <inheritdoc/>
public void Dispose() {
// do nothing
}
}
}
+112 -123
View File
@@ -6,129 +6,118 @@ using System.Threading.Tasks;
using Swan.Lite.Logging;
using Swan.Threading;
namespace Swan.Logging
{
namespace Swan.Logging {
/// <summary>
/// A helper class to write into files the messages sent by the <see cref="Terminal" />.
/// </summary>
/// <seealso cref="ILogger" />
public class FileLogger : TextLogger, ILogger {
private readonly ManualResetEventSlim _doneEvent = new ManualResetEventSlim(true);
private readonly ConcurrentQueue<String> _logQueue = new ConcurrentQueue<String>();
private readonly ExclusiveTimer _timer;
private readonly String _filePath;
private Boolean _disposedValue; // To detect redundant calls
/// <summary>
/// A helper class to write into files the messages sent by the <see cref="Terminal" />.
/// Initializes a new instance of the <see cref="FileLogger"/> class.
/// </summary>
/// <seealso cref="ILogger" />
public class FileLogger : TextLogger, ILogger
{
private readonly ManualResetEventSlim _doneEvent = new ManualResetEventSlim(true);
private readonly ConcurrentQueue<string> _logQueue = new ConcurrentQueue<string>();
private readonly ExclusiveTimer _timer;
private readonly string _filePath;
private bool _disposedValue; // To detect redundant calls
/// <summary>
/// Initializes a new instance of the <see cref="FileLogger"/> class.
/// </summary>
public FileLogger()
: this(SwanRuntime.EntryAssemblyDirectory, true)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="FileLogger"/> class.
/// </summary>
/// <param name="filePath">The filePath.</param>
/// <param name="dailyFile">if set to <c>true</c> [daily file].</param>
public FileLogger(string filePath, bool dailyFile)
{
_filePath = filePath;
DailyFile = dailyFile;
_timer = new ExclusiveTimer(
async () => await WriteLogEntries().ConfigureAwait(false),
TimeSpan.Zero,
TimeSpan.FromSeconds(5));
}
/// <inheritdoc />
public LogLevel LogLevel { get; set; }
/// <summary>
/// Gets the file path.
/// </summary>
/// <value>
/// The file path.
/// </value>
public string FilePath => DailyFile
? Path.Combine(Path.GetDirectoryName(_filePath), Path.GetFileNameWithoutExtension(_filePath) + $"_{DateTime.UtcNow:yyyyMMdd}" + Path.GetExtension(_filePath))
: _filePath;
/// <summary>
/// Gets a value indicating whether [daily file].
/// </summary>
/// <value>
/// <c>true</c> if [daily file]; otherwise, <c>false</c>.
/// </value>
public bool DailyFile { get; }
/// <inheritdoc />
public void Log(LogMessageReceivedEventArgs logEvent)
{
var (outputMessage, _) = GetOutputAndColor(logEvent);
_logQueue.Enqueue(outputMessage);
}
/// <inheritdoc />
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Releases unmanaged and - optionally - managed resources.
/// </summary>
/// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
protected virtual void Dispose(bool disposing)
{
if (_disposedValue) return;
if (disposing)
{
_timer.Pause();
_timer.Dispose();
_doneEvent.Wait();
_doneEvent.Reset();
WriteLogEntries(true).Await();
_doneEvent.Dispose();
}
_disposedValue = true;
}
private async Task WriteLogEntries(bool finalCall = false)
{
if (_logQueue.IsEmpty)
return;
if (!finalCall && !_doneEvent.IsSet)
return;
_doneEvent.Reset();
try
{
using (var file = File.AppendText(FilePath))
{
while (!_logQueue.IsEmpty)
{
if (_logQueue.TryDequeue(out var entry))
await file.WriteAsync(entry).ConfigureAwait(false);
}
}
}
finally
{
if (!finalCall)
_doneEvent.Set();
}
}
}
public FileLogger() : this(SwanRuntime.EntryAssemblyDirectory, true) {
}
/// <summary>
/// Initializes a new instance of the <see cref="FileLogger"/> class.
/// </summary>
/// <param name="filePath">The filePath.</param>
/// <param name="dailyFile">if set to <c>true</c> [daily file].</param>
public FileLogger(String filePath, Boolean dailyFile) {
this._filePath = filePath;
this.DailyFile = dailyFile;
this._timer = new ExclusiveTimer(async () => await this.WriteLogEntries().ConfigureAwait(false), TimeSpan.Zero, TimeSpan.FromSeconds(5));
}
/// <inheritdoc />
public LogLevel LogLevel {
get; set;
}
/// <summary>
/// Gets the file path.
/// </summary>
/// <value>
/// The file path.
/// </value>
public String FilePath => this.DailyFile ? Path.Combine(Path.GetDirectoryName(this._filePath), Path.GetFileNameWithoutExtension(this._filePath) + $"_{DateTime.UtcNow:yyyyMMdd}" + Path.GetExtension(this._filePath)) : this._filePath;
/// <summary>
/// Gets a value indicating whether [daily file].
/// </summary>
/// <value>
/// <c>true</c> if [daily file]; otherwise, <c>false</c>.
/// </value>
public Boolean DailyFile {
get;
}
/// <inheritdoc />
public void Log(LogMessageReceivedEventArgs logEvent) {
(String outputMessage, ConsoleColor _) = this.GetOutputAndColor(logEvent);
this._logQueue.Enqueue(outputMessage);
}
/// <inheritdoc />
public void Dispose() {
this.Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Releases unmanaged and - optionally - managed resources.
/// </summary>
/// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
protected virtual void Dispose(Boolean disposing) {
if(this._disposedValue) {
return;
}
if(disposing) {
this._timer.Pause();
this._timer.Dispose();
this._doneEvent.Wait();
this._doneEvent.Reset();
this.WriteLogEntries(true).Await();
this._doneEvent.Dispose();
}
this._disposedValue = true;
}
private async Task WriteLogEntries(Boolean finalCall = false) {
if(this._logQueue.IsEmpty) {
return;
}
if(!finalCall && !this._doneEvent.IsSet) {
return;
}
this._doneEvent.Reset();
try {
using StreamWriter file = File.AppendText(this.FilePath);
while(!this._logQueue.IsEmpty) {
if(this._logQueue.TryDequeue(out String entry)) {
await file.WriteAsync(entry).ConfigureAwait(false);
}
}
} finally {
if(!finalCall) {
this._doneEvent.Set();
}
}
}
}
}
+21 -21
View File
@@ -1,24 +1,24 @@
namespace Swan.Logging
{
using System;
using System;
namespace Swan.Logging {
/// <summary>
/// Interface for a logger implementation.
/// </summary>
public interface ILogger : IDisposable {
/// <summary>
/// Interface for a logger implementation.
/// Gets the log level.
/// </summary>
public interface ILogger : IDisposable
{
/// <summary>
/// Gets the log level.
/// </summary>
/// <value>
/// The log level.
/// </value>
LogLevel LogLevel { get; }
/// <summary>
/// Logs the specified log event.
/// </summary>
/// <param name="logEvent">The <see cref="LogMessageReceivedEventArgs"/> instance containing the event data.</param>
void Log(LogMessageReceivedEventArgs logEvent);
}
/// <value>
/// The log level.
/// </value>
LogLevel LogLevel {
get;
}
/// <summary>
/// Logs the specified log event.
/// </summary>
/// <param name="logEvent">The <see cref="LogMessageReceivedEventArgs"/> instance containing the event data.</param>
void Log(LogMessageReceivedEventArgs logEvent);
}
}
+38 -40
View File
@@ -1,43 +1,41 @@
namespace Swan
{
namespace Swan {
/// <summary>
/// Defines the log levels.
/// </summary>
public enum LogLevel {
/// <summary>
/// Defines the log levels.
/// The none message type
/// </summary>
public enum LogLevel
{
/// <summary>
/// The none message type
/// </summary>
None,
/// <summary>
/// The trace message type
/// </summary>
Trace,
/// <summary>
/// The debug message type
/// </summary>
Debug,
/// <summary>
/// The information message type
/// </summary>
Info,
/// <summary>
/// The warning message type
/// </summary>
Warning,
/// <summary>
/// The error message type
/// </summary>
Error,
/// <summary>
/// The fatal message type
/// </summary>
Fatal,
}
None,
/// <summary>
/// The trace message type
/// </summary>
Trace,
/// <summary>
/// The debug message type
/// </summary>
Debug,
/// <summary>
/// The information message type
/// </summary>
Info,
/// <summary>
/// The warning message type
/// </summary>
Warning,
/// <summary>
/// The error message type
/// </summary>
Error,
/// <summary>
/// The fatal message type
/// </summary>
Fatal,
}
}
+143 -127
View File
@@ -1,131 +1,147 @@
using System;
#nullable enable
using System;
namespace Swan
{
namespace Swan {
/// <summary>
/// Event arguments representing the message that is logged
/// on to the terminal. Use the properties to forward the data to
/// your logger of choice.
/// </summary>
/// <seealso cref="System.EventArgs" />
public class LogMessageReceivedEventArgs : EventArgs {
/// <summary>
/// Event arguments representing the message that is logged
/// on to the terminal. Use the properties to forward the data to
/// your logger of choice.
/// Initializes a new instance of the <see cref="LogMessageReceivedEventArgs" /> class.
/// </summary>
/// <seealso cref="System.EventArgs" />
public class LogMessageReceivedEventArgs : EventArgs
{
/// <summary>
/// Initializes a new instance of the <see cref="LogMessageReceivedEventArgs" /> class.
/// </summary>
/// <param name="sequence">The sequence.</param>
/// <param name="messageType">Type of the message.</param>
/// <param name="utcDate">The UTC date.</param>
/// <param name="source">The source.</param>
/// <param name="message">The message.</param>
/// <param name="extendedData">The extended data.</param>
/// <param name="callerMemberName">Name of the caller member.</param>
/// <param name="callerFilePath">The caller file path.</param>
/// <param name="callerLineNumber">The caller line number.</param>
public LogMessageReceivedEventArgs(
ulong sequence,
LogLevel messageType,
DateTime utcDate,
string source,
string message,
object? extendedData,
string callerMemberName,
string callerFilePath,
int callerLineNumber)
{
Sequence = sequence;
MessageType = messageType;
UtcDate = utcDate;
Source = source;
Message = message;
CallerMemberName = callerMemberName;
CallerFilePath = callerFilePath;
CallerLineNumber = callerLineNumber;
ExtendedData = extendedData;
}
/// <summary>
/// Gets logging message sequence.
/// </summary>
/// <value>
/// The sequence.
/// </value>
public ulong Sequence { get; }
/// <summary>
/// Gets the type of the message.
/// It can be a combination as the enumeration is a set of bitwise flags.
/// </summary>
/// <value>
/// The type of the message.
/// </value>
public LogLevel MessageType { get; }
/// <summary>
/// Gets the UTC date at which the event at which the message was logged.
/// </summary>
/// <value>
/// The UTC date.
/// </value>
public DateTime UtcDate { get; }
/// <summary>
/// Gets the name of the source where the logging message
/// came from. This can come empty if the logger did not set it.
/// </summary>
/// <value>
/// The source.
/// </value>
public string Source { get; }
/// <summary>
/// Gets the body of the message.
/// </summary>
/// <value>
/// The message.
/// </value>
public string Message { get; }
/// <summary>
/// Gets the name of the caller member.
/// </summary>
/// <value>
/// The name of the caller member.
/// </value>
public string CallerMemberName { get; }
/// <summary>
/// Gets the caller file path.
/// </summary>
/// <value>
/// The caller file path.
/// </value>
public string CallerFilePath { get; }
/// <summary>
/// Gets the caller line number.
/// </summary>
/// <value>
/// The caller line number.
/// </value>
public int CallerLineNumber { get; }
/// <summary>
/// Gets an object representing extended data.
/// It could be an exception or anything else.
/// </summary>
/// <value>
/// The extended data.
/// </value>
public object? ExtendedData { get; }
/// <summary>
/// Gets the Extended Data properties cast as an Exception (if possible)
/// Otherwise, it return null.
/// </summary>
/// <value>
/// The exception.
/// </value>
public Exception? Exception => ExtendedData as Exception;
}
/// <param name="sequence">The sequence.</param>
/// <param name="messageType">Type of the message.</param>
/// <param name="utcDate">The UTC date.</param>
/// <param name="source">The source.</param>
/// <param name="message">The message.</param>
/// <param name="extendedData">The extended data.</param>
/// <param name="callerMemberName">Name of the caller member.</param>
/// <param name="callerFilePath">The caller file path.</param>
/// <param name="callerLineNumber">The caller line number.</param>
public LogMessageReceivedEventArgs(
UInt64 sequence,
LogLevel messageType,
DateTime utcDate,
String source,
String message,
Object? extendedData,
String callerMemberName,
String callerFilePath,
Int32 callerLineNumber) {
this.Sequence = sequence;
this.MessageType = messageType;
this.UtcDate = utcDate;
this.Source = source;
this.Message = message;
this.CallerMemberName = callerMemberName;
this.CallerFilePath = callerFilePath;
this.CallerLineNumber = callerLineNumber;
this.ExtendedData = extendedData;
}
/// <summary>
/// Gets logging message sequence.
/// </summary>
/// <value>
/// The sequence.
/// </value>
public UInt64 Sequence {
get;
}
/// <summary>
/// Gets the type of the message.
/// It can be a combination as the enumeration is a set of bitwise flags.
/// </summary>
/// <value>
/// The type of the message.
/// </value>
public LogLevel MessageType {
get;
}
/// <summary>
/// Gets the UTC date at which the event at which the message was logged.
/// </summary>
/// <value>
/// The UTC date.
/// </value>
public DateTime UtcDate {
get;
}
/// <summary>
/// Gets the name of the source where the logging message
/// came from. This can come empty if the logger did not set it.
/// </summary>
/// <value>
/// The source.
/// </value>
public String Source {
get;
}
/// <summary>
/// Gets the body of the message.
/// </summary>
/// <value>
/// The message.
/// </value>
public String Message {
get;
}
/// <summary>
/// Gets the name of the caller member.
/// </summary>
/// <value>
/// The name of the caller member.
/// </value>
public String CallerMemberName {
get;
}
/// <summary>
/// Gets the caller file path.
/// </summary>
/// <value>
/// The caller file path.
/// </value>
public String CallerFilePath {
get;
}
/// <summary>
/// Gets the caller line number.
/// </summary>
/// <value>
/// The caller line number.
/// </value>
public Int32 CallerLineNumber {
get;
}
/// <summary>
/// Gets an object representing extended data.
/// It could be an exception or anything else.
/// </summary>
/// <value>
/// The extended data.
/// </value>
public Object? ExtendedData {
get;
}
/// <summary>
/// Gets the Extended Data properties cast as an Exception (if possible)
/// Otherwise, it return null.
/// </summary>
/// <value>
/// The exception.
/// </value>
public Exception? Exception => this.ExtendedData as Exception;
}
}
File diff suppressed because it is too large Load Diff
+57 -83
View File
@@ -1,89 +1,63 @@
using Swan.Logging;
using System;
namespace Swan.Lite.Logging
{
namespace Swan.Lite.Logging {
/// <summary>
/// Use this class for text-based logger.
/// </summary>
public abstract class TextLogger {
/// <summary>
/// Use this class for text-based logger.
/// Gets or sets the logging time format.
/// set to null or empty to prevent output.
/// </summary>
public abstract class TextLogger
{
/// <summary>
/// Gets or sets the logging time format.
/// set to null or empty to prevent output.
/// </summary>
/// <value>
/// The logging time format.
/// </value>
public static string LoggingTimeFormat { get; set; } = "HH:mm:ss.fff";
/// <summary>
/// Gets the color of the output of the message (the output message has a new line char in the end).
/// </summary>
/// <param name="logEvent">The <see cref="LogMessageReceivedEventArgs" /> instance containing the event data.</param>
/// <returns>
/// The output message formatted and the color of the console to be used.
/// </returns>
protected (string outputMessage, ConsoleColor color) GetOutputAndColor(LogMessageReceivedEventArgs logEvent)
{
var (prefix , color) = GetConsoleColorAndPrefix(logEvent.MessageType);
var loggerMessage = string.IsNullOrWhiteSpace(logEvent.Message)
? string.Empty
: logEvent.Message.RemoveControlCharsExcept('\n');
var outputMessage = CreateOutputMessage(logEvent.Source, loggerMessage, prefix, logEvent.UtcDate);
// Further format the output in the case there is an exception being logged
if (logEvent.MessageType == LogLevel.Error && logEvent.Exception != null)
{
try
{
outputMessage += $"{logEvent.Exception.Stringify().Indent()}{Environment.NewLine}";
}
catch
{
// Ignore
}
}
return (outputMessage, color);
}
private static (string Prefix, ConsoleColor color) GetConsoleColorAndPrefix(LogLevel messageType)
{
switch (messageType)
{
case LogLevel.Debug:
return (ConsoleLogger.DebugPrefix, ConsoleLogger.DebugColor);
case LogLevel.Error:
return (ConsoleLogger.ErrorPrefix, ConsoleLogger.ErrorColor);
case LogLevel.Info:
return (ConsoleLogger.InfoPrefix, ConsoleLogger.InfoColor);
case LogLevel.Trace:
return (ConsoleLogger.TracePrefix, ConsoleLogger.TraceColor);
case LogLevel.Warning:
return (ConsoleLogger.WarnPrefix, ConsoleLogger.WarnColor);
case LogLevel.Fatal:
return (ConsoleLogger.FatalPrefix, ConsoleLogger.FatalColor);
default:
return (new string(' ', ConsoleLogger.InfoPrefix.Length), Terminal.Settings.DefaultColor);
}
}
private static string CreateOutputMessage(string sourceName, string loggerMessage, string prefix, DateTime date)
{
var friendlySourceName = string.IsNullOrWhiteSpace(sourceName)
? string.Empty
: sourceName.SliceLength(sourceName.LastIndexOf('.') + 1, sourceName.Length);
var outputMessage = string.IsNullOrWhiteSpace(sourceName)
? loggerMessage
: $"[{friendlySourceName}] {loggerMessage}";
return string.IsNullOrWhiteSpace(LoggingTimeFormat)
? $" {prefix} >> {outputMessage}{Environment.NewLine}"
: $" {date.ToLocalTime().ToString(LoggingTimeFormat)} {prefix} >> {outputMessage}{Environment.NewLine}";
}
}
/// <value>
/// The logging time format.
/// </value>
public static String LoggingTimeFormat { get; set; } = "HH:mm:ss.fff";
/// <summary>
/// Gets the color of the output of the message (the output message has a new line char in the end).
/// </summary>
/// <param name="logEvent">The <see cref="LogMessageReceivedEventArgs" /> instance containing the event data.</param>
/// <returns>
/// The output message formatted and the color of the console to be used.
/// </returns>
protected (String outputMessage, ConsoleColor color) GetOutputAndColor(LogMessageReceivedEventArgs logEvent) {
(String prefix, ConsoleColor color) = GetConsoleColorAndPrefix(logEvent.MessageType);
String loggerMessage = String.IsNullOrWhiteSpace(logEvent.Message) ? String.Empty : logEvent.Message.RemoveControlCharsExcept('\n');
String outputMessage = CreateOutputMessage(logEvent.Source, loggerMessage, prefix, logEvent.UtcDate);
// Further format the output in the case there is an exception being logged
if(logEvent.MessageType == LogLevel.Error && logEvent.Exception != null) {
try {
outputMessage += $"{logEvent.Exception.Stringify().Indent()}{Environment.NewLine}";
} catch {
// Ignore
}
}
return (outputMessage, color);
}
private static (String Prefix, ConsoleColor color) GetConsoleColorAndPrefix(LogLevel messageType) => messageType switch
{
LogLevel.Debug => (ConsoleLogger.DebugPrefix, ConsoleLogger.DebugColor),
LogLevel.Error => (ConsoleLogger.ErrorPrefix, ConsoleLogger.ErrorColor),
LogLevel.Info => (ConsoleLogger.InfoPrefix, ConsoleLogger.InfoColor),
LogLevel.Trace => (ConsoleLogger.TracePrefix, ConsoleLogger.TraceColor),
LogLevel.Warning => (ConsoleLogger.WarnPrefix, ConsoleLogger.WarnColor),
LogLevel.Fatal => (ConsoleLogger.FatalPrefix, ConsoleLogger.FatalColor),
_ => (new String(' ', ConsoleLogger.InfoPrefix.Length), Terminal.Settings.DefaultColor),
};
private static String CreateOutputMessage(String sourceName, String loggerMessage, String prefix, DateTime date) {
String friendlySourceName = String.IsNullOrWhiteSpace(sourceName) ? String.Empty : sourceName.SliceLength(sourceName.LastIndexOf('.') + 1, sourceName.Length);
String outputMessage = String.IsNullOrWhiteSpace(sourceName) ? loggerMessage : $"[{friendlySourceName}] {loggerMessage}";
return String.IsNullOrWhiteSpace(LoggingTimeFormat) ? $" {prefix} >> {outputMessage}{Environment.NewLine}" : $" {date.ToLocalTime().ToString(LoggingTimeFormat)} {prefix} >> {outputMessage}{Environment.NewLine}";
}
}
}