mcpField
B
bitrix-logger

bitrix-logger

github.com/bxmaximum开发47278 次安装2 周前更新
代码仓库

关于 bitrix-logger

bitrix-logger 是面向 Bitrix 开发者的 PSR-3 日志记录技能,介绍日志器配置、注入和写入方式。内容涵盖 File、syslog、事件日志及 JSON Lines 格式化器,并说明 LoggerFactory 与 LoggerRegistry 的用法。

主要功能

  1. 01配置 PSR-3 日志器实现
  2. 02使用 LoggerFactory 创建日志器
  3. 03通过 LoggerRegistry 启用日志器 ID
  4. 04设置格式化器与日志配置
  5. 05记录带上下文的消息和异常

适用场景

  1. 01为 Bitrix 服务注入 LoggerInterface
  2. 02按模块配置和启用日志器
  3. 03将日志写入文件或系统日志
  4. 04使用 JSON Lines 格式记录上下文

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/bxmaximum/bitrix-framework-skills --skill bitrix-logger

安装后在 Claude Code 中输入/bitrix-logger确认已加载。

详细介绍

日志记录(PSR-3)

基线:main 23.0+ · 已验证:main 26.800.0

代码依赖 Psr\Log\LoggerInterface;具体实现由 .settings.php 中的 loggers 选择。AddMessage2Log() 仅用于兼容。

实现(Bitrix\Main\Diag\)

类说明
FileLogger(string $fileName, ?int $maxSize = null)默认最大 1 MB,超出后重命名为 <file>.old;0 = 不轮转
SysLogger(string $prefix = '', int $flags = LOG_ODELAY, int $facility = LOG_USER)系统 syslog
EventLogger(?string $module, ?string $auditType, ?callable $callback)b_event_log(管理界面中的 事件日志)——仅适用于低日志量
LogFormatter($showArguments = false, $argMaxChars = 30)默认格式化器;占位符 {date} {host} {level} {delimiter} {exception} {trace},以及上下文键
JsonLinesFormatter(自 main 25.300 起;较早版本:LogFormatter)仅将 $context 写为一行 JSON——消息文本会被丢弃,请将其放入上下文

level 和 formatter 设置仅适用于 Bitrix\Main\Diag\Logger 子类,不适用于 Monolog。

获取日志记录器

自 main 26.250* 起——LoggerFactory + LoggerRegistry:

use Bitrix\Main\Diag\LoggerFactory;
use Bitrix\Main\Diag\LoggerRegistry;

$logger = (new LoggerFactory())->createById('vendor.module.sync'); // NullLogger unless the id is enabled
(new LoggerRegistry())->enable('vendor.module.sync');               // option loggers:logger_is_enabled_<id> = Y
$logger = (new LoggerFactory())->createById('vendor.module.sync', [], false); // skip the registry check
  • 已启用的 ID 若没有对应的 loggers 条目,则使用默认日志记录器(LOG_FILENAME 常量)或 NullLogger。
  • 通过这种方式创建的内核 ID 在启用前不会输出日志:main.Messenger.Receiver、main.Messenger.Requeue、main.config.feature、bizproc.imbot,……
  • Logger::create($id, $params) — 自 main 26.300 起已弃用;在 main 26.250 之前是唯一的 API;若 $id 未配置则返回 null:$logger = Logger::create('id') ?? new NullLogger();。

将其注入服务(模块 .settings.php):

\Vendor\Module\Public\Service\SyncService::class => [
    'className' => \Vendor\Module\Public\Service\SyncService::class,
    'constructorParams' => static fn () => [(new \Bitrix\Main\Diag\LoggerFactory())->createById('vendor.module.sync')],
],

loggers 部分

将其放入 /local/.settings_extra.php:闭包无法在内核重写主文件(bitrix-settings)时保留。

'services' => [
    'value' => [
        'vendor.formatter.json' => ['className' => \Bitrix\Main\Diag\JsonLinesFormatter::class],
    ],
],
'loggers' => [
    'value' => [
        'vendor.module.sync' => [
            'constructor' => static fn () => new \Bitrix\Main\Diag\FileLogger('/var/log/site/sync.log', 10 * 1024 * 1024),
            'level' => \Psr\Log\LogLevel::INFO,     // threshold
            'formatter' => 'vendor.formatter.json', // service id
        ],
        'main.HttpClient' => [
            'constructor' => static function (\Bitrix\Main\Web\Http\DebugInterface $debug, \Psr\Http\Message\RequestInterface $request) {
                $debug->setDebugLevel(\Bitrix\Main\Web\HttpDebug::ALL);
                return new \Bitrix\Main\Diag\FileLogger('/var/log/site/http.log');
            },
        ],
    ],
    'readonly' => true,
],

条目形式:constructor 闭包(接收工厂 $params),或 className + constructorParams(数组或返回数组的闭包)。

内核日志记录器 ID

ID使用方闭包参数
main.DefaultAddMessage2Log()、默认日志记录器$logFileName、$showArgs
main.HttpClientHttpClient / PSR-18 处理器DebugInterface $debug、RequestInterface $request
main.GeoIpManagerGeoIP 管理器—
main.EventLog.SysLogger、main.EventLog.FileLoggerCEventLog 后端—、$path, $maxSize

不存在 main.Mail 或 main.Engine ID。

写入日志

$this->logger->error('Sync of order {orderId} failed: {exception}', ['orderId' => $id, 'exception' => $e]);
  • 占位符 {key} 从上下文获取;exception 会输出类名、消息和跟踪信息。
  • 没有异常时记录堆栈跟踪:'trace' => \Bitrix\Main\Diag\Helper::getBackTrace(6, DEBUG_BACKTRACE_IGNORE_ARGS)。
  • Monolog(composer require monolog/monolog):从 constructor 闭包返回 Monolog\Logger;在 Monolog 中设置其级别和格式化器。

检查清单

  • 服务接收 LoggerInterface(默认使用 NullLogger),业务代码中不要 new FileLogger()。
  • 日志记录器 ID 以模块 ID 为前缀;使用 LoggerFactory 时,通过 LoggerRegistry 启用。
  • 日志文件位于 DOCUMENT_ROOT 之外,并设置轮转大小。
  • 消息或上下文中不得包含密码、令牌或个人数据。
  • 使用 JsonLinesFormatter 的调用方应将消息放入上下文。

评论

支持 Markdown