bitrix-logger
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseLogging in Bitrix (PSR-3)
Bitrix中的日志系统(PSR-3)
Bitrix follows the PSR-3 standard. In code, inject , and in , configure the specific implementation. Direct calls to are legacy; in new code, write via DI logger.
\Psr\Log\LoggerInterface.settings.phpAddMessage2LogBitrix遵循PSR-3标准。在代码中,注入,并在中配置具体的实现。直接调用属于旧写法;在新代码中,应通过DI日志器进行日志记录。
\Psr\Log\LoggerInterface.settings.phpAddMessage2LogBuilt-in Implementations
内置实现
All are in the namespace:
\Bitrix\Main\Diag\| Class | Purpose |
|---|---|
| Abstract base class; |
| Into a file, with auto-rotation when |
| Into system |
| Into |
| Default formatter: interpolates |
| From 25.300.0; one JSON line per entry, convenient for ELK/Loki |
Levels are constants of (, , , , , , , ).
\Psr\Log\LogLevel::*emergencyalertcriticalerrorwarningnoticeinfodebug所有实现均位于命名空间下:
\Bitrix\Main\Diag\| 类 | 用途 |
|---|---|
| 抽象基类; |
| 将日志写入文件,当超过 |
| 通过 |
| 将日志写入 |
| 默认格式化器:解析 |
| 从版本25.300.0开始支持;每条日志为一行JSON,适用于ELK/Loki等系统 |
日志级别为的常量(、、、、、、、)。
\Psr\Log\LogLevel::*emergencyalertcriticalerrorwarningnoticeinfodebugService with Logger (DI — Recommended)
结合日志器的服务(DI——推荐方式)
php
<?php declare(strict_types=1);
namespace Vendor\Module\Application\Service;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
final class PostService
{
public function __construct(
private readonly LoggerInterface $logger = new NullLogger(),
) {}
public function publish(int $postId): void
{
try
{
// ...
$this->logger->info('Post {id} published', ['id' => $postId]);
}
catch (\Throwable $e)
{
$this->logger->error('Publish failed for post {id}: {exception}', [
'id' => $postId,
'exception' => $e,
]);
throw $e;
}
}
}Registration in :
/local/modules/vendor.module/.settings.phpphp
'services' => [
'value' => [
\Vendor\Module\Application\Service\PostService::class => [
'constructor' => static fn (): \Vendor\Module\Application\Service\PostService =>
new \Vendor\Module\Application\Service\PostService(
new \Bitrix\Main\Diag\FileLogger('/var/log/bitrix/post-service.log'),
),
],
],
'readonly' => true,
],php
<?php declare(strict_types=1);
namespace Vendor\Module\Application\Service;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
final class PostService
{
public function __construct(
private readonly LoggerInterface $logger = new NullLogger(),
) {}
public function publish(int $postId): void
{
try
{
// ...
$this->logger->info('Post {id} published', ['id' => $postId]);
}
catch (\Throwable $e)
{
$this->logger->error('Publish failed for post {id}: {exception}', [
'id' => $postId,
'exception' => $e,
]);
throw $e;
}
}
}在中注册:
/local/modules/vendor.module/.settings.phpphp
'services' => [
'value' => [
\Vendor\Module\Application\Service\PostService::class => [
'constructor' => static fn (): \Vendor\Module\Application\Service\PostService =>
new \Vendor\Module\Application\Service\PostService(
new \Bitrix\Main\Diag\FileLogger('/var/log/bitrix/post-service.log'),
),
],
],
'readonly' => true,
],PSR-3 Placeholders
PSR-3占位符
Message is a template with , values are taken from :
{key}$contextphp
$logger->warning('User {userId} tried {action} on post {postId}', [
'userId' => $uid, 'action' => 'delete', 'postId' => $pid,
]);Special keys understood by :
LogFormatter- — current time (interpolated automatically).
{date} - — HTTP_HOST (automatic).
{host} - — entry separator (automatic).
{delimiter} - —
{exception}object → formats class, message, stack trace.\Throwable - — manual stack trace:
{trace}.Diag\Helper::getBackTrace(6, DEBUG_BACKTRACE_IGNORE_ARGS, 3)
Enable arguments in stack trace:
php
$logger->setFormatter(new \Bitrix\Main\Diag\LogFormatter(showArguments: true, argMaxChars: 120));日志消息为带有的模板,值从中获取:
{key}$contextphp
$logger->warning('User {userId} tried {action} on post {postId}', [
'userId' => $uid, 'action' => 'delete', 'postId' => $pid,
]);LogFormatter- — 当前时间(自动解析)。
{date} - — HTTP_HOST(自动解析)。
{host} - — 日志条目分隔符(自动解析)。
{delimiter} - —
{exception}对象 → 格式化类名、消息和调用栈。\Throwable - — 手动调用栈:
{trace}。Diag\Helper::getBackTrace(6, DEBUG_BACKTRACE_IGNORE_ARGS, 3)
启用调用栈中的参数显示:
php
$logger->setFormatter(new \Bitrix\Main\Diag\LogFormatter(showArguments: true, argMaxChars: 120));Configuration via .settings.php
— loggers
section
.settings.phploggers通过.settings.php
配置——loggers
段
.settings.phploggersAllows overriding loggers for named kernel points (, , ) and your own identifiers.
main.HttpClientmain.Defaultmain.GeoIpManagerphp
return [
'services' => [
'value' => [
'formatter.withArgs' => [
'className' => \Bitrix\Main\Diag\LogFormatter::class,
'constructorParams' => [true],
],
],
'readonly' => true,
],
'loggers' => [
'value' => [
'main.Default' => [
'constructor' => static fn () => new \Bitrix\Main\Diag\FileLogger(
'/var/log/bitrix/app.log', 10 * 1024 * 1024,
),
'level' => \Psr\Log\LogLevel::INFO,
'formatter' => 'formatter.withArgs',
],
'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/bitrix/http-' . spl_object_hash($request) . '.log',
);
},
'level' => \Psr\Log\LogLevel::DEBUG,
],
'vendor.module.myLogger' => [
'constructor' => static fn () => new \Bitrix\Main\Diag\FileLogger(
'/var/log/bitrix/vendor.module.log',
),
'level' => \Psr\Log\LogLevel::DEBUG,
],
],
'readonly' => true,
],
];允许覆盖命名内核节点(、、)和自定义标识的日志器。
main.HttpClientmain.Defaultmain.GeoIpManagerphp
return [
'services' => [
'value' => [
'formatter.withArgs' => [
'className' => \Bitrix\Main\Diag\LogFormatter::class,
'constructorParams' => [true],
],
],
'readonly' => true,
],
'loggers' => [
'value' => [
'main.Default' => [
'constructor' => static fn () => new \Bitrix\Main\Diag\FileLogger(
'/var/log/bitrix/app.log', 10 * 1024 * 1024,
),
'level' => \Psr\Log\LogLevel::INFO,
'formatter' => 'formatter.withArgs',
],
'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/bitrix/http-' . spl_object_hash($request) . '.log',
);
},
'level' => \Psr\Log\LogLevel::DEBUG,
],
'vendor.module.myLogger' => [
'constructor' => static fn () => new \Bitrix\Main\Diag\FileLogger(
'/var/log/bitrix/vendor.module.log',
),
'level' => \Psr\Log\LogLevel::DEBUG,
],
],
'readonly' => true,
],
];Important
注意事项
-
closures must be in
constructor/.settings.php— the file is not edited by Admin Panel, closures are not serialized..settings_extra.php -
— threshold level; logger ignores messages below this.
level -
— key from
formattersection.services -
Retrieving logger in code:php
$logger = \Bitrix\Main\Diag\Logger::create('vendor.module.myLogger'); $logger = \Bitrix\Main\Diag\Logger::create('vendor.module.myLogger', [$this, $extraArg]);
-
闭包必须放在
constructor/.settings.php中——该文件不会被后台管理面板修改,闭包不会被序列化。.settings_extra.php -
— 阈值级别;日志器会忽略低于该级别的消息。
level -
— 来自
formatter段的键。services -
在代码中获取日志器:php
$logger = \Bitrix\Main\Diag\Logger::create('vendor.module.myLogger'); $logger = \Bitrix\Main\Diag\Logger::create('vendor.module.myLogger', [$this, $extraArg]);
Named Kernel Points
命名内核节点
| ID | Used In | Factory Parameters |
|---|---|---|
| | |
| | |
| | — |
| | — |
| | |
There are no named loggers or . Prefer closures for (see examples above) over / arrays.
main.Mailmain.EngineconstructorFileLoggerclassNamesettingsConfiguring these loggers redirects all kernel calls — convenient for auditing external calls (see example in ).
bitrix-http-client| ID | 使用场景 | 工厂参数 |
|---|---|---|
| | |
| | |
| | — |
| | — |
| | |
不存在名为或的日志器。相比/数组,更推荐为使用闭包(见上方示例)。
main.Mailmain.EngineclassNamesettingsFileLoggerconstructor配置这些日志器会重定向所有内核调用——便于审计外部调用(见示例)。
bitrix-http-clientLoggerAware + Factory
LoggerAware + 工厂
For classes that should be supplied with a logger "by identifier":
php
final class Indexer implements \Psr\Log\LoggerAwareInterface
{
use \Psr\Log\LoggerAwareTrait;
public function run(): void
{
$this->ensureLogger()->info('Indexing started');
}
private function ensureLogger(): \Psr\Log\LoggerInterface
{
if ($this->logger === null)
{
$this->setLogger(\Bitrix\Main\Diag\Logger::create('vendor.module.indexer', [$this]));
}
return $this->logger;
}
}对于需要通过“标识”注入日志器的类:
php
final class Indexer implements \Psr\Log\LoggerAwareInterface
{
use \Psr\Log\LoggerAwareTrait;
public function run(): void
{
$this->ensureLogger()->info('Indexing started');
}
private function ensureLogger(): \Psr\Log\LoggerInterface
{
if ($this->logger === null)
{
$this->setLogger(\Bitrix\Main\Diag\Logger::create('vendor.module.indexer', [$this]));
}
return $this->logger;
}
}Monolog via Composer
通过Composer集成Monolog
bash
composer require monolog/monologIntegration into :
.settings.phpphp
'loggers' => [
'value' => [
'vendor.module.external' => [
'constructor' => static function () {
$log = new \Monolog\Logger('vendor.module');
$log->pushHandler(new \Monolog\Handler\StreamHandler('/var/log/bitrix/monolog.log'));
return $log;
},
'level' => \Psr\Log\LogLevel::DEBUG,
],
],
],bash
composer require monolog/monolog在中集成:
.settings.phpphp
'loggers' => [
'value' => [
'vendor.module.external' => [
'constructor' => static function () {
$log = new \Monolog\Logger('vendor.module');
$log->pushHandler(new \Monolog\Handler\StreamHandler('/var/log/bitrix/monolog.log'));
return $log;
},
'level' => \Psr\Log\LogLevel::DEBUG,
],
],
],Checklist
检查清单
- PSR-3 standard followed (placeholders, context, exception key).
- Loggers are configured via rather than hardcoded in services.
.settings.php - Threshold is set for each environment.
level - Loggers for external integrations () are redirected to separate files for audit.
HttpClient - For heavy load, is used for external collectors.
JsonLinesFormatter - Logs are stored outside or protected by
DOCUMENT_ROOT..htaccess - Sensitive data (passwords, tokens) are stripped from context before logging.
Link in with named loggers for unified error tracking. See skill .
exception_handling.log.settings.phpbitrix-settings- 遵循PSR-3标准(占位符、上下文、exception键)。
- 日志器通过配置,而非硬编码在服务中。
.settings.php - 为每个环境设置阈值。
level - 将外部集成()的日志器重定向到单独文件以便审计。
HttpClient - 高负载场景下,为外部收集器使用。
JsonLinesFormatter - 日志存储在之外,或通过
DOCUMENT_ROOT保护。.htaccess - 日志记录前从上下文中移除敏感数据(密码、令牌)。
将中的与命名日志器关联,实现统一错误追踪。详见技能。
.settings.phpexception_handling.logbitrix-settings