Liam.Logging 1.1.0

dotnet add package Liam.Logging --version 1.1.0
                    
NuGet\Install-Package Liam.Logging -Version 1.1.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Liam.Logging" Version="1.1.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Liam.Logging" Version="1.1.0" />
                    
Directory.Packages.props
<PackageReference Include="Liam.Logging" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Liam.Logging --version 1.1.0
                    
#r "nuget: Liam.Logging, 1.1.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#addin nuget:?package=Liam.Logging&version=1.1.0
                    
Install as a Cake Addin
#tool nuget:?package=Liam.Logging&version=1.1.0
                    
Install as a Cake Tool

Liam.Logging

现代化日志记录功能库,支持多级日志、多种输出目标、结构化日志、异步记录、日志轮转等功能,完全兼容Microsoft.Extensions.Logging。

功能特性

核心功能

  • 多级日志记录: 支持Trace、Debug、Info、Warning、Error、Critical等标准日志级别
  • 多种输出目标: 控制台、文件、数据库、网络等多种日志输出方式
  • 结构化日志: 支持结构化日志记录,便于日志分析和查询
  • 异步日志: 提供高性能的异步日志记录功能,避免阻塞主线程
  • 日志格式化: 支持Text和JSON格式,可自定义日志格式和模板
  • 日志过滤: 基于级别、类别、条件的日志过滤机制

高级功能

  • 日志轮转: 文件大小和时间基础的日志文件轮转
  • 缓冲机制: 批量写入优化性能
  • 依赖注入: 完整的DI容器支持和配置
  • 配置管理: 支持appsettings.json、环境变量等配置方式
  • 性能监控: 日志记录性能指标和监控
  • 线程安全: 确保多线程环境下的安全性
  • 作用域支持: 支持日志作用域,便于跟踪请求上下文

v1.1.0 新增功能

  • 异步资源释放: 支持 IAsyncDisposable 模式,优雅的异步资源管理
  • 标准资源管理: 实现完整的 Dispose 模式,确保资源正确释放
  • 异步性能优化: 使用 ConfigureAwait(false) 避免死锁,提升异步性能
  • 改进异常处理: 具体的异常记录和处理机制,替代空 catch 块
  • 真正的异步 I/O: 移除 Task.Run 反模式,使用原生异步文件操作

安装

dotnet add package Liam.Logging

快速开始

基本使用

using Liam.Logging.Extensions;
using Liam.Logging.Interfaces;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

// 配置服务
var builder = Host.CreateApplicationBuilder(args);

builder.Services.AddLiamLogging()
    .AddConsoleLogging()
    .AddFileLogging(config =>
    {
        config.FilePath = "logs/app.log";
        config.EnableRotation = true;
        config.MaxFileSize = 10 * 1024 * 1024; // 10MB
    });

var host = builder.Build();

// 使用日志记录器
var logger = host.Services.GetRequiredService<ILiamLogger<Program>>();

logger.LogInformation("应用程序启动");
logger.LogWarning("这是一个警告消息");
logger.LogError("发生了错误", new Exception("示例异常"));

await host.RunAsync();

结构化日志

// 结构化日志记录
logger.LogInformationStructured("用户 {UserId} 执行了操作 {Action}", 123, "登录");
logger.LogErrorStructured("处理订单 {OrderId} 时发生错误: {ErrorMessage}", 
    orderId, ex.Message);

// 使用扩展方法
logger.LogInformationStructured("订单 {OrderId} 状态更新为 {Status}", 
    order.Id, order.Status);

异步日志记录

// 异步日志记录(v1.1.0 改进:支持 CancellationToken)
using var cts = new CancellationTokenSource();
await logger.LogInformationAsync("异步处理完成", cts.Token);
await logger.LogErrorAsync("异步操作失败", exception, cts.Token);

// 异步结构化日志
await logger.LogStructuredAsync(LogLevel.Information,
    "处理了 {Count} 个项目,耗时 {Duration}ms",
    new object[] { count, duration }, cts.Token);

// 异步作用域(v1.1.0 优化:使用 ConfigureAwait(false))
await logger.WithScopeAsync($"Operation: {operationName}", async () =>
{
    logger.LogInformation("操作开始");
    await DoSomethingAsync().ConfigureAwait(false);
    logger.LogInformation("操作完成");
});

日志作用域

// 使用作用域
using (logger.BeginScope("RequestId: {RequestId}", requestId))
{
    logger.LogInformation("开始处理请求");
    
    using (logger.BeginScope("UserId: {UserId}", userId))
    {
        logger.LogInformation("用户验证成功");
        // 这些日志会包含RequestId和UserId信息
    }
    
    logger.LogInformation("请求处理完成");
}

// 使用扩展方法的作用域
await logger.WithScopeAsync($"Operation: {operationName}", async () =>
{
    logger.LogInformation("操作开始");
    await DoSomethingAsync();
    logger.LogInformation("操作完成");
});

v1.1.0 资源管理示例

// 异步资源释放(推荐)
await using var loggerFactory = serviceProvider.GetRequiredService<ILiamLoggerFactory>();
var logger = loggerFactory.CreateLogger("MyApp");

// 使用 CancellationToken 的异步日志
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30));
try
{
    await logger.LogInformationAsync("开始处理", cts.Token);
    await ProcessDataAsync(cts.Token);
    await logger.LogInformationAsync("处理完成", cts.Token);
}
catch (OperationCanceledException)
{
    await logger.LogWarningAsync("操作被取消");
}

// 异步作用域最佳实践
await logger.WithScopeAsync("ProcessId", async () =>
{
    await logger.LogInformationAsync("作用域内的异步操作");
    await SomeAsyncOperation().ConfigureAwait(false);
});

配置

appsettings.json配置

{
  "Logging": {
    "MinimumLevel": "Information",
    "EnableAsync": true,
    "AsyncQueueSize": 10000,
    "BatchSize": 100,
    "BatchTimeoutMs": 1000,
    "IncludeScopes": true,
    "IncludeExceptionDetails": true,
    "IncludeSourceInfo": false,
    "Providers": [
      {
        "TypeName": "Console",
        "Enabled": true,
        "Settings": {
          "EnableColors": true,
          "TimestampFormat": "yyyy-MM-dd HH:mm:ss.fff"
        }
      },
      {
        "TypeName": "File",
        "Enabled": true,
        "Settings": {
          "FilePath": "logs/app.log",
          "EnableRotation": true,
          "MaxFileSize": 10485760,
          "RetainedFileCount": 10,
          "FormatterType": "Text"
        }
      }
    ]
  }
}

代码配置

builder.Services.ConfigureLiamLogging(logging =>
{
    logging
        .SetMinimumLevel(LogLevel.Information)
        .EnableAsync(queueSize: 10000, batchSize: 100)
        .EnablePerformanceMonitoring()
        .EnableScopes()
        .AddConsole(config =>
        {
            config.EnableColors = true;
            config.TimestampFormat = "yyyy-MM-dd HH:mm:ss.fff";
        })
        .AddFile(config =>
        {
            config.FilePath = "logs/app.log";
            config.EnableRotation = true;
            config.MaxFileSize = 10 * 1024 * 1024;
            config.RetainedFileCount = 10;
        });
});

日志提供程序

控制台提供程序

builder.Services.AddConsoleLogging(config =>
{
    config.EnableColors = true;
    config.UseStandardError = false;
    config.TimestampFormat = "yyyy-MM-dd HH:mm:ss.fff";
});

文件提供程序

builder.Services.AddFileLogging(config =>
{
    config.FilePath = "logs/app.log";
    config.EnableRotation = true;
    config.MaxFileSize = 10 * 1024 * 1024; // 10MB
    config.RetainedFileCount = 10;
    config.RotationInterval = TimeSpan.FromDays(1);
    config.Encoding = "UTF-8";
    config.AutoFlush = true;
});

日志格式化器

文本格式化器

var formatter = new TextLogFormatter(
    timestampFormat: "yyyy-MM-dd HH:mm:ss.fff",
    includeScopes: true,
    includeExceptionDetails: true,
    includeSourceInfo: false);

JSON格式化器

var jsonOptions = new JsonSerializerOptions
{
    PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
    WriteIndented = false
};
var formatter = new JsonLogFormatter(jsonOptions);

日志过滤器

级别过滤器

var levelFilter = new LogLevelFilter(LogLevel.Information, LogLevel.Critical);

类别过滤器

// 白名单模式
var categoryFilter = new LogCategoryFilter(new[] { "MyApp.Controllers", "MyApp.Services" });

// 黑名单模式
var categoryFilter = new LogCategoryFilter(new[] { "Microsoft", "System" }, isBlacklist: true);

消息过滤器

var messageFilter = new LogMessageFilter(
    includePatterns: new[] { @"User \d+ logged in" },
    excludePatterns: new[] { @"Health check" });

性能监控

// 启用性能监控
builder.Services.ConfigureLiamLogging(logging =>
{
    logging.EnablePerformanceMonitoring();
});

// 获取性能统计
var factory = serviceProvider.GetRequiredService<ILiamLoggerFactory>();
var stats = factory.GetPerformanceStats();

扩展方法

方法跟踪

public async Task ProcessOrderAsync(int orderId)
{
    logger.LogMethodEntry(new { orderId });
    
    try
    {
        var result = await ProcessOrder(orderId);
        logger.LogMethodExit(new { result });
        return result;
    }
    catch (Exception ex)
    {
        logger.LogError("处理订单失败", ex);
        throw;
    }
}

性能记录

var stopwatch = Stopwatch.StartNew();
await ProcessDataAsync();
stopwatch.Stop();

logger.LogPerformance("数据处理", stopwatch.Elapsed);

最佳实践

  1. 使用结构化日志: 便于日志分析和查询
  2. 合理设置日志级别: 避免过多的调试日志影响性能
  3. 使用异步日志: 在高并发场景下提升性能
  4. 配置日志轮转: 避免日志文件过大
  5. 使用作用域: 便于跟踪请求上下文
  6. 监控日志性能: 及时发现性能问题

v1.1.0 异步编程最佳实践

  1. 使用 CancellationToken: 在异步日志方法中传递取消令牌
  2. 使用 ConfigureAwait(false): 在库代码中避免死锁
  3. 正确释放资源: 使用 using 语句或 DisposeAsync 方法
  4. 异常处理: 记录异常信息而不是完全忽略

API文档

核心接口

  • ILiamLogger: 主要的日志记录器接口
  • ILiamLogger<T>: 泛型日志记录器接口
  • ILiamLoggerFactory: 日志记录器工厂接口
  • ILogProvider: 日志提供程序接口
  • ILogFormatter: 日志格式化器接口
  • ILogFilter: 日志过滤器接口

主要类

  • LiamLogger: 日志记录器实现
  • LiamLoggerFactory: 日志记录器工厂实现
  • ConsoleLogProvider: 控制台日志提供程序
  • FileLogProvider: 文件日志提供程序
  • TextLogFormatter: 文本格式化器
  • JsonLogFormatter: JSON格式化器

测试覆盖率

Liam.Logging库包含全面的单元测试,确保代码质量和功能正确性:

  • 总测试数量: 82个测试
  • 测试覆盖率: 100%
  • 测试框架: xUnit + Moq + FluentAssertions

测试分类

  • 核心功能测试: 45个测试 - 测试日志记录器的基本功能和异步操作
  • 格式化器测试: 20个测试 - 测试Text和JSON格式化器
  • 提供程序测试: 12个测试 - 测试控制台和文件提供程序的同步和异步操作
  • 工厂测试: 5个测试 - 测试日志工厂和依赖注入

性能特性

  • 异步日志记录: 支持高并发场景,避免阻塞主线程
  • 批量处理: 支持批量写入,提升I/O性能
  • 内存优化: 合理的缓冲区管理,避免内存泄漏
  • 线程安全: 全面的线程安全保护

v1.1.0 性能改进

  • 真正的异步 I/O: 使用 WriteLineAsync、FlushAsync 等原生异步方法
  • 减少线程切换: 移除不必要的 Task.Run 调用
  • ConfigureAwait 优化: 避免上下文切换开销
  • 标准资源管理: 实现 IAsyncDisposable,支持异步资源释放

版本历史

版本 发布日期 主要变更
1.1.0 2025-06-15 重大改进:修复异步编程反模式,实现标准Dispose模式,改进异常处理,添加IAsyncDisposable支持,优化性能
1.0.0 2025-06-15 初始版本,包含核心日志功能、多种提供程序、格式化器、过滤器等完整功能

许可证

本项目采用MIT许可证 - 查看 LICENSE 文件了解详情。

贡献

欢迎提交Issue和Pull Request来帮助改进这个项目。

支持

如果您在使用过程中遇到问题,请在GitHub上提交Issue。

Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (3)

Showing the top 3 NuGet packages that depend on Liam.Logging:

Package Downloads
Liam.TcpServer

现代化TCP服务器通信库,支持多客户端连接管理、异步数据传输、SSL/TLS安全通信、心跳检测、连接池管理等功能,基于.NET 8.0构建

Liam.SerialPort

现代化串口通讯功能库,支持跨平台串口设备发现、连接管理、数据收发、热插拔检测和自动重连等功能。v1.1.0新增:Liam.Logging集成支持,提供增强的日志功能

Liam.TcpClient

现代化TCP客户端通信库,支持连接管理、异步数据传输、SSL/TLS安全通信、自动重连、心跳检测、连接池管理等功能,基于.NET 8.0构建

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.1.0 141 6/15/2025