日志条目,表示单条日志记录。
public class LogEntry
{
public DateTime Timestamp { get; }
public object Level { get; }
public string? Category { get; }
public string Message { get; }
public Exception? Exception { get; }
public ConcurrentDictionary<string, object?> Properties { get; }
public LogEntry(DateTime timestamp, object level, string? category, string message, Exception? exception = null);
}日志记录器,提供各种日志记录方法。
public class Logger : IDisposable
{
public Logger(LoggerConfiguration configuration);
public void Log(object level, string message, string? category = null, Exception? exception = null);
public void Trace(string message, string? category = null, Exception? exception = null);
public void Debug(string message, string? category = null, Exception? exception = null);
public void Info(string message, string? category = null, Exception? exception = null);
public void Warning(string message, string? category = null, Exception? exception = null);
public void Error(string message, string? category = null, Exception? exception = null);
public void Fatal(string message, string? category = null, Exception? exception = null);
public void Flush();
public void Dispose();
}日志记录器工厂,用于创建和管理日志记录器。
public static class LoggerFactory
{
public static Logger CreateLogger(LoggerConfiguration configuration, string? name = null);
public static Logger GetLogger(string? name = null);
public static void CloseAll();
}预定义的日志级别枚举。
public enum LogLevel
{
Trace = 0,
Debug = 1,
Info = 2,
Warning = 3,
Error = 4,
Fatal = 5,
None = 6
}自定义日志级别,用于创建预定义级别之外的日志级别。
public class CustomLogLevel
{
public int Value { get; }
public string Name { get; }
public static CustomLogLevel Create(int value, string name);
}日志配置类,用于配置日志系统。
public class LoggerConfiguration
{
public object MinimumLevel { get; set; }
public List<ILogWriter> Writers { get; }
public List<ILogHandler> Handlers { get; }
public string? DefaultCategory { get; set; }
public LoggerConfiguration SetMinimumLevel(object level);
public LoggerConfiguration AddConsoleWriter(ILogFormatter? formatter = null);
public LoggerConfiguration AddFileWriter(string filePath, ILogFormatter? formatter = null, long maxFileSize = 10 * 1024 * 1024, int maxRollingFiles = 5);
public LoggerConfiguration AddFileWriterWithDailyRolling(
string filePath,
ILogFormatter? formatter = null,
long maxFileSize = 10 * 1024 * 1024,
int maxRollingFiles = 5,
bool useDailyRolling = true);
public LoggerConfiguration AddWriter(ILogWriter writer);
public LoggerConfiguration AddHandler(ILogHandler handler);
public LoggerConfiguration AddEmailNotification(string smtpServer, int smtpPort, string fromEmail, string toEmail, string username, string password, object levelToHandle = LogLevel.Error);
public LoggerConfiguration AddAction(Action<LogEntry> action, Func<LogEntry, bool>? predicate = null);
public LoggerConfiguration SetDefaultCategory(string category);
}日志输出接口,定义日志写入方法。
public interface ILogWriter : IDisposable
{
void Write(LogEntry entry);
void Flush();
}彩色控制台输出,支持不同级别使用不同颜色。
public class ColorConsoleWriter : ILogWriter
{
public ColorConsoleWriter(ILogFormatter formatter);
public void Write(LogEntry entry);
public void Flush();
public void Dispose();
}滚动文件日志输出类,支持以下功能:
- 按大小滚动 - 当日志文件达到指定大小时,自动创建新文件
- 按日期滚动 - 每天创建新的日志文件
- 会话识别 - 同一天多次启动程序时,创建不同的日志文件
参数:
filePath: 文件路径formatter: 格式化器 (可选,默认为TextFormatter)maxFileSize: 最大文件大小 (默认10MB)maxRollingFiles: 最大滚动文件数 (默认5)encoding: 文件编码 (默认UTF8)useDailyRolling: 是否启用日期滚动 (默认true)
日志文件命名规则:
使用日期滚动时:
- 主文件:
[文件名].[日期].[会话ID].[扩展名](例如:app.2023-04-15.a1b2c3d4.log) - 滚动文件:
[文件名].[日期].[会话ID].[滚动序号].[扩展名](例如:app.2023-04-15.a1b2c3d4.1.log)
不使用日期滚动时:
- 主文件:
[文件名].[扩展名](例如:app.log) - 滚动文件:
[文件名].[滚动序号].[扩展名](例如:app.1.log)
滚动机制:
- 按大小滚动时,将当前文件重命名为第1个滚动文件,之前的第n个滚动文件变为第n+1个,超出maxRollingFiles的最旧文件被删除
- 按日期滚动时,每天创建新的日志文件,同时保留独立的滚动历史
数据库输出,将日志写入数据库表。
public class DatabaseWriter : ILogWriter
{
public DatabaseWriter(DbConnection connection, string tableName = "Logs", bool ownsConnection = false, int batchSize = 100);
public void Write(LogEntry entry);
public void Flush();
public void Dispose();
}HTTP输出,将日志通过HTTP请求发送到指定端点。
public class HttpWriter : ILogWriter
{
public HttpWriter(string endpoint, HttpClient? httpClient = null, int batchSize = 10, JsonSerializerOptions? jsonOptions = null);
public void Write(LogEntry entry);
public void Flush();
public void Dispose();
}自定义输出,允许通过委托自定义日志输出行为。
public class CustomWriter : ILogWriter
{
public CustomWriter(Action<LogEntry> writeAction, Action? flushAction = null, Action? disposeAction = null);
public void Write(LogEntry entry);
public void Flush();
public void Dispose();
}日志格式化器接口,定义日志格式化方法。
public interface ILogFormatter
{
string Format(LogEntry entry);
}文本格式化器,将日志格式化为文本。
public class TextFormatter : ILogFormatter
{
public TextFormatter(string template = "[{timestamp}] [{level}] {message}");
public string Format(LogEntry entry);
}JSON格式化器,将日志格式化为JSON。
public class JsonFormatter : ILogFormatter
{
public JsonFormatter(JsonSerializerOptions? options = null);
public string Format(LogEntry entry);
}XML格式化器,将日志格式化为XML。
public class XmlFormatter : ILogFormatter
{
public string Format(LogEntry entry);
}日志处理器接口,定义日志处理方法。
public interface ILogHandler
{
void Handle(LogEntry entry);
bool ShouldHandle(LogEntry entry);
}回调处理器,通过委托处理日志。
public class ActionHandler : ILogHandler
{
public ActionHandler(Action<LogEntry> action, Func<LogEntry, bool>? predicate = null);
public void Handle(LogEntry entry);
public bool ShouldHandle(LogEntry entry);
}邮件通知处理器,通过邮件发送日志通知。
public class EmailNotificationHandler : ILogHandler
{
public EmailNotificationHandler(string smtpServer, int smtpPort, string fromEmail, string toEmail, string username, string password, object levelToHandle = LogLevel.Error);
public void Handle(LogEntry entry);
public bool ShouldHandle(LogEntry entry);
}日志拦截器,用于拦截和修改日志条目。
public class LogInterceptor
{
public LogInterceptor(Func<LogEntry, bool> predicate, Action<LogEntry> action);
public bool Process(LogEntry entry);
}日志解析器接口,定义日志解析方法。
public interface ILogParser
{
IEnumerable<LogEntry> Parse(string logContent);
IEnumerable<LogEntry> ParseFile(string filePath);
}文本日志解析器,解析文本格式的日志。
public class TextLogParser : ILogParser
{
public TextLogParser(string pattern = @"\[(.*?)\] \[(.*?)\] (.*)");
public IEnumerable<LogEntry> Parse(string logContent);
public IEnumerable<LogEntry> ParseFile(string filePath);
}JSON日志解析器,解析JSON格式的日志。
public class JsonLogParser : ILogParser
{
public JsonLogParser(JsonSerializerOptions? options = null);
public IEnumerable<LogEntry> Parse(string logContent);
public IEnumerable<LogEntry> ParseFile(string filePath);
}日志上下文,用于存储和管理日志上下文属性。
public static class LogContext
{
public static Dictionary<string, object?> Properties { get; }
public static void SetProperty(string key, object? value);
public static object? GetProperty(string key);
public static void ClearProperties();
public static void EnrichLogEntry(LogEntry entry);
}日志记录器扩展方法,提供额外的日志记录功能。
public static class LoggerExtensions
{
public static void WithContext(this Logger logger, Action action, Dictionary<string, object?> contextProperties);
public static T WithContext<T>(this Logger logger, Func<T> func, Dictionary<string, object?> contextProperties);
public static void LogWithProperties(this Logger logger, object level, string message, Dictionary<string, object?> properties, string? category = null, Exception? exception = null);
public static void LogStructured(this Logger logger, object level, string messageTemplate, object values, string? category = null, Exception? exception = null);
public static T Time<T>(this Logger logger, Func<T> action, string operationName, string? category = null);
public static void Time(this Logger logger, Action action, string operationName, string? category = null);
public static void SafeExecute(this Logger logger, Action action, string operationName, string? category = null);
public static T? SafeExecute<T>(this Logger logger, Func<T> func, string operationName, string? category = null, T? defaultValue = default);
}日志分析工具,提供日志分析功能。
public static class LogAnalyzer
{
public static Dictionary<string, int> CountByLevel(IEnumerable<LogEntry> entries);
public static Dictionary<string, int> CountByCategory(IEnumerable<LogEntry> entries);
public static Dictionary<DateTime, int> CountByTimeInterval(IEnumerable<LogEntry> entries, TimeSpan interval);
public static IEnumerable<LogEntry> FindByText(IEnumerable<LogEntry> entries, string text, bool ignoreCase = true);
public static IEnumerable<LogEntry> FindByTimeRange(IEnumerable<LogEntry> entries, DateTime start, DateTime end);
public static IEnumerable<LogEntry> FindByLevel(IEnumerable<LogEntry> entries, object level);
public static IEnumerable<LogEntry> FindByExceptionType(IEnumerable<LogEntry> entries, Type exceptionType);
public static IEnumerable<KeyValuePair<string, int>> GetMostFrequentMessages(IEnumerable<LogEntry> entries, int topCount = 10);
public static Dictionary<int, int> GetHourDistribution(IEnumerable<LogEntry> entries);
}日志导出工具,提供日志导出功能。
public static class LogExporter
{
public static void ExportToFile(IEnumerable<LogEntry> entries, string filePath, ILogFormatter formatter);
public static void ExportToTextFile(IEnumerable<LogEntry> entries, string filePath, string template = "[{timestamp}] [{level}] {message}");
public static void ExportToJsonFile(IEnumerable<LogEntry> entries, string filePath);
public static void ExportToXmlFile(IEnumerable<LogEntry> entries, string filePath);
public static IEnumerable<LogEntry> ImportFromFile(string filePath, ILogParser parser);
public static IEnumerable<LogEntry> ImportFromTextFile(string filePath, string pattern = @"\[(.*?)\] \[(.*?)\] (.*)");
public static IEnumerable<LogEntry> ImportFromJsonFile(string filePath);
}Web日志查看器,提供Web界面查看日志。
public class LogWebViewer
{
public LogWebViewer(string logDirectory, int port = 5000, string? username = null, string? password = null);
public void Start();
public Task StopAsync();
}日志配置Web查看器扩展。
public static class LoggerConfigurationExtensions
{
public static LoggerConfiguration AddWebViewer(this LoggerConfiguration configuration, string logDirectory, int port = 5000, string? username = null, string? password = null);
}