Cangming.Logs 0.1.10.1124

Prefix Reserved
dotnet add package Cangming.Logs --version 0.1.10.1124
                    
NuGet\Install-Package Cangming.Logs -Version 0.1.10.1124
                    
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="Cangming.Logs" Version="0.1.10.1124" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Cangming.Logs" Version="0.1.10.1124" />
                    
Directory.Packages.props
<PackageReference Include="Cangming.Logs" />
                    
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 Cangming.Logs --version 0.1.10.1124
                    
#r "nuget: Cangming.Logs, 0.1.10.1124"
                    
#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.
#:package Cangming.Logs@0.1.10.1124
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Cangming.Logs&version=0.1.10.1124
                    
Install as a Cake Addin
#tool nuget:?package=Cangming.Logs&version=0.1.10.1124
                    
Install as a Cake Tool

Cangming.Logs

日志领域的基础实现层(net8.0;net10.0),承接 Cangming.Logs.Contracts 契约的默认实现与宿主侧门面:DefaultLogService(契约流参考实现)、LogHub(MEL 静态门面)、PartitionLogExtensions / Routing/(分区路由装饰器)、LogBufferExtensions(缓冲区消息)、LogDomain(工厂 + 中继 + 崩溃环的运行域)、LogPolicy(每秒限流)、Export/LogRecord(导出记录)、Relay/(绑定前缓冲中继)。本工程是"契约 → 具体框架落地"之间的默认支撑,不依赖任何具体日志框架,仅依赖 MEL 抽象包;归档压缩已归 Cangming.Logs.NLog。

包版本由仓库根 Directory.Build.props 统一控制,项目内不覆盖。应用接入的完整步骤、契约流与测试接法见 docs/guide/01-日志应用接入指南.md;从 0.1.6 升级的破坏性变更与 Mercury 检查表见 docs/guide/02-日志与插件升级破坏性变更说明.md。

快速接线(AI 阅读)

作为 ILogService 默认实现使用:需要独立于 NLog 的日志流时直接实例化,注入给生产者(如 NLog 落地层的 LogEntryTarget):

ILogService logService = new DefaultLogService();   // Dispose 由持有方管理

作为业务日志门面使用(推荐入口,等价于 NLog 的 GetCurrentClassLogger 用法):宿主在启动阶段调用一次 Initialize 决定真实输出;静态 logger 字段可以在初始化之前构造,未初始化时的写入会丢弃并计入 LogHub.DroppedBeforeInitialization。

// 宿主启动阶段;越早越好,但不再是静态字段的安全前置
LogHub.Initialize(LoggerFactory.Create(b => b.AddConsole()));   // 仅一次,重复调用抛 InvalidOperationException

// 业务类中,构造顺序不再敏感
private static readonly ILogger s_logger = LogHub.GetCurrentClassLogger();
s_logger.LogInformation("...");   // 初始化后自动绑定;初始化前调用只计数、不抛

LogHub 不创建默认 provider,也不保留 Reset;没有 Initialize 就没有真实输出,库不替宿主选择 Console/Debug/NLog。未初始化时的丢弃数用于启动健康检查。

逐条分区路由

To / SkipMain / WithMain / When / WithPolicy 都是 ILogger 扩展,返回携带路由参数的 ILogger/ILogger<T> 装饰器,入口本身不写日志,条目交回 MEL 原生方法书写,因此 [LoggerMessage]、第三方 ILogger 扩展与测试替身都能直接作用在装饰器上(ADR-0018)。公开面是路由入口 6 个(To、SkipMain、WithMain、When、WithPolicy、Hex)加 HexLogBuilder 的 8 个终端,MEL 的六个级别终端直接复用、不再复制一份。

// LogPartitions 由宿主定义;库只提供 LogPartition 类型与 None/All
logger.To(LogPartitions.Motion).LogInformation("运动消息");                       // 只进 Motion,不进主日志
logger.To(LogPartitions.Motion).WithMain().LogInformation("运动消息也进主日志");
logger.To(LogPartitions.Motion).To(LogPartitions.Runtime).LogWarning(exception, "多分区 {0}", value);
logger.To(LogPartitions.Connection).SkipMain().LogInformation("高频消息");         // SkipMain 现在冗余但保留
logger.When(condition).To(LogPartitions.Runtime).LogInformation("条件消息");
logger.WithPolicy(LogPolicy.PerSecond(5)).LogInformation("限流消息");
  • To 按位或累积;非零掩码默认 SkipMain,需要主日志时显式 .WithMain();To(LogPartition.None) 与解析后为零的掩码保持 WithMain,不写回退;To(All) 为全 1 位。
  • WithMain() 显式请求主日志,与 SkipMain(false) 等价;两者都把模式记为显式设置,因此链上继续 To 不会把它们重置回默认。
  • SkipMain(bool) 以最后一次为准,SkipMain() 无目标时由宿主规则决定落点。
  • When(false) 抑制整条链(IsEnabled 恒为假),但消息插值仍在调用前发生。
  • WithPolicy 在入口调用时判定并占用本秒额度,同一策略实例被多个调用点复用才共享窗口计数。
  • 每次入口派生一个新装饰器、内层 logger 复用,链上只有一层包装;default(HexLogBuilder) 的终端静默返回,不抛空引用。

旧的 InfoTo / WarnTo / DebugTo / ErrorTo / TraceTo / FatalTo,以及 0.4 删除的 LogRouteBuilder、MelLoggerExtensions(Info 系列)与 LogMessageFormatter 都不再保留 [Obsolete] 包装;迁移到 logger.To(...).LogInformation(...) / logger.SkipMain()。

  • 分区与结构化字段同时成立:logger.To(p).LogInformation("速度 {speed}", v) 的条目既有 cangming.partition 也有 speed(桥实验见 NLogBridgeStructuredFieldTests)。
  • 载荷链(Hex)的消息与 LogBuffer 的内容都是纯文本、不当模板解析;动态标签请先 if (logger.IsEnabled(...)) 再插值,否则级别关掉仍会分配字符串。
  • LogDomain(Cangming.Logs.Domain)把工厂、中继、崩溃环与 BeginScope 收成一个实例,LogPolicy.PerSecond 是唯一的限流规则;订阅方需要导出自有格式时用 Export/LogRecord.From(entry) 与 ToEntry(),该记录不承载 Properties 扩展槽。

消息渲染

渲染完全交给 MEL,本库不再自带渲染器:logger.To(p).LogInformation(msg, args) 与 logger.LogInformation(msg, args) 的文本逐字相同(对拍用例 tests/UnitTest.Cangming.Logs/RoutedMessageParityTests.cs),占位符顺序消费、固定文化、{{/}} 转义、对齐与格式说明符、非法模板抛 FormatException 都以 MEL 为准,级别被过滤时不渲染也不抛。缓冲区消息统一走 logger.LogBuffer(level, sb):IsEnabled 为真才 ToString(),内容按最终文本写出,不再为六个级别各开一个 StringBuilder 终端。

完整规则与示例见 docs/guide/01-日志应用接入指南.md §4.4,决策依据见 ADR-0018。

二进制载荷

高频二进制帧走 Hex(span) 链,默认前 64 字节、大写空格分隔、无前后缀;超出默认窗口时追加 …(+N):

logger.Hex(frame).Info("收帧");                          // 主日志、无分区、前 64 字节
logger.To(LogPartitions.DeviceIo).Hex(frame).Info("收帧");
logger.To(LogPartitions.DeviceIo).Hex(frame).Slice(12, 12).Style(HexLetterCase.Lower, '-').Wrap("RX:", ";").Info("收帧");
  • HexLogBuilder 是 ref struct:span 不装箱、不跨 await、不进 state,因此结构上不可能泄漏;终端读完即弃,池化数组可以立刻归还。
  • 配置方法只改字段、零分配;渲染是单趟写入,IsEnabled 在渲染之前。
  • 切片是绝对偏移且越界收敛不抛;显式 Slice 之后不再截断。
  • WithSpan() 输出 [len=… @…+…] 元信息,取证场景建议打开;默认关闭,库不替调用点决定日志长相。

规则与示例见 docs/guide/01-日志应用接入指南.md §4.5,决策依据见 ADR-0015。

绑定前缓冲(Relay)

LogServiceRelay(命名空间 Cangming.Logs.Relay)填的是「生产端已就绪、下游 ILogService 还没就绪」这段空档:插件加载时已经开始写契约流,真正的日志收集服务在宿主启动更晚的阶段才注册。接线顺序固定为 LogEntryTarget → 宿主适配器 : ILogService → LogServiceRelay → 真正服务,中继只暴露 Write(LogEntry) 而不实现 ILogService,因此非 NLog 宿主也能直接用它,ILogService 的「写不抛出、不缓冲」契约也不会被中继改写。宿主不要为同一目的再写一个队列:LogEntryTarget 的工厂重试只决定服务实例何时出现,不保存条目,自建队列只会多一份没有上限、没有指标、也没有重放的积压。

using Cangming.Logs.Contracts;

// 宿主适配器(示意,放在宿主工程里):Write 转给中继;订阅仍由真正服务承担,中继不代管
internal sealed class RelaySink(LogServiceRelay relay) : ILogService
{
    public void Write(LogEntry entry) => relay.Write(entry);

    public IDisposable Subscribe(LogAdmission? admission, LogSink sink)
        => throw new NotSupportedException("订阅请向真正服务注册,中继只缓冲写入");
}
using Cangming.Logs.Contracts;
using Cangming.Logs.NLog;
using Cangming.Logs.Relay;

var relay = new LogServiceRelay();                    // 默认 200 条 / 256 KiB
var target = new LogEntryTarget("ContractLog", new RelaySink(relay));

// 下游就绪后绑定:ResolveLogService 是宿主自己的解析方法,成功后按 FIFO 重放
if (!relay.Bind(ResolveLogService))
    Console.WriteLine($"下游未就绪,{relay.PendingCount} 条仍在缓冲");
项 口径
容量 new LogServiceRelay(pendingCapacity = 200, pendingByteCapacity = 256 * 1024);条数与 UTF-8 字节双上限,任一超限都从队首淘汰最旧条目并计 PendingOverflow
单条超预算 字节上限只淘汰到队列剩一条为止,所以单条自身就超预算时保留它,不会「写一条大消息就把缓冲清空」;字节按 LogEntry.Message 与 Category 的 UTF-8 长度之和估算
绑定失败 Bind 的工厂抛异常或返回 null 时返回 false、BindFailures 递增,Pending 原样保留,修好后再绑一次即可重放;并发 Bind 只有一个赢家,其余立即 false
重放上限 一次绑定最多 8 批、每批最多 pendingCapacity 条,批次用尽仍有积压时转 Bound 并清空剩余,清掉的条数记入 ReplayDropped;该上限只防「持续高流量下绑定永不完成」,正常流量不会触发
重入 下游 Write 里再次写中继最多再转发一层,第三层直接丢弃并计 ReentryDropped,无限递归在源头截断;额度按线程独立,不同线程互不消耗
解绑 Unbind 只在 Bound 生效,切回未绑定并清掉下游引用,Pending 保留,重新绑定后按原顺序重放;解除瞬间在途的写入可能仍向旧服务转发一次
状态 IsBound 只在重放完成后为 true,重放中与解绑后为 false,因此不要用它判断「能否写入」——任何状态写入都合法
生命周期 不实现 ILogService,避免非 NLog 宿主为缓冲中继拉入 NLog;不实现 IDisposable,实例由宿主持有,Unbind 也不释放下游

Metrics 在队列锁内构造只读快照,快照里的 PendingCount/PendingBytes 与同一时刻的队列一致、不是累计值;五个计数器单调递增且来源互不重叠,任一上升都能直接定位到唯一的丢弃或失败路径,ReplayDropped 与 ReentryDropped 只分别在批次用尽与嵌套超限时上涨,别的失败不会带动它们:

指标 含义 只在哪条路径递增
PendingOverflow 因条数或字节上限被淘汰的最旧条目数 入队淘汰
BindFailures 下游工厂抛异常或返回 null 的次数 Bind 失败
ReplayDropped 重放批次用尽后仍有积压而被清空的条目数 批次上限
ReentryDropped 第三层重入被丢弃的条目数 Forward 嵌套超限
ForwardFailures 下游 Write 抛异常并被吞掉的次数 Bound 直连与重放转发
PendingCount / PendingBytes 读取瞬间的队列快照,不是累计值 —

关键行为与效率语义

  • DefaultLogService.Write:宿主已写 cangming.seq 时原样保留,只有 SequenceId == 0 才用 Interlocked 补号;无人订阅时条目流过即弃,内存不随日志量增长;订阅者异常就地吞掉,"写不抛出"与订阅方缺陷互不影响。
  • LogHub.Initialize:Interlocked.CompareExchange 保证多线程竞争下仅一个线程成功发布工厂;重复初始化抛 InvalidOperationException;工厂生命周期由宿主管理,本门面不代为释放。
  • To 每次派生一个装饰器(实测 48 B,ADR-0018 §4),入口本身不写、不渲染;格式化与渲染由 MEL 在 IsEnabled 为真之后进行,关闭级别不构造合并 state。
  • 归档压缩已迁到 Cangming.Logs.NLog/Archive/(唯一使用者是 CompressingFileTarget),核心不再承担文件压缩职责。

同族项目

项目 角色
Cangming.Logs.Contracts 契约:ILogService / LogEntry(含 v2 的 Fields/Source/SessionId) / LogSeverity / LogPartition / LogRouteMode / 四个保留键与两个宿主键
Cangming.Logs.NLog 生产环境落地(NLog Target / 转换 / 分区过滤 / 序号 Target / 压缩归档 / DefaultLogging),依赖本工程
Cangming.Logs.xUnit 测试环境落地(MEL → ITestOutputHelper,以及 CaptureLoggerProvider 捕获)
Cangming.Logs.App 应用级数据源(LogFeed 面板数据源、SupportBundle 支持包),只依赖本工程与 Contracts
Cangming.Logs.Testing 测试替身与断言(RecordingLogService、LogAssert),只依赖 Contracts
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 is compatible.  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 (12)

Showing the top 5 NuGet packages that depend on Cangming.Logs:

Package Downloads
Rays.Core

Rays.Core.Description

Rays.Plugins

仅组织内部使用。为软件实现插件管理机制的基础库。

Rays.Commlink

仅组织内部使用。提供串口通信、网络通信支持功能的核心库。

Rays.WPF

仅组织内部使用。提供与WPF相关的核心库。

Rays.Plugins.WPF

仅组织内部使用。为桌面软件(WPF)实现WPF界面插件管理机制的基础库。

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
0.1.10.1124 51 11/24/2026
0.1.9.1122 247 11/22/2026
0.1.8.1117 210 11/17/2026
0.1.7.1116 222 11/16/2026
0.1.6.1109 215 11/9/2026
0.1.5.1105 222 11/5/2026
0.1.4.1105 220 11/5/2026
0.1.3.1102 230 11/2/2026
0.1.2.1029 734 10/29/2026
0.1.1.1028 178 10/28/2026

见仓库根 CHANGELOG.md