定制 yiisoft/log 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

yiisoft/log

Composer 安装命令:

composer require yiisoft/log

包简介

Yii Logging Library

README 文档

README

Yii

Yii Logging Library


Latest Stable Version Total Downloads Build status Code coverage Mutation testing badge static analysis type-coverage

This package provides a PSR-3 compatible logging library. It is used extensively in the Yii Framework but it can also be used as a separate package.

The logger sends or passes messages to multiple targets. Each target may filter these messages according to their severity level, and category, and then export them to some medium such as a file, an email or a syslog.

Requirements

  • PHP 8.0 or higher.

Installation

The package can be installed with Composer:

composer require yiisoft/log

General usage

Creating a logger:

/**
 * List of class instances that extend the \Yiisoft\Log\Target abstract class.
 * 
 * @var \Yiisoft\Log\Target[] $targets
 */
$logger = new \Yiisoft\Log\Logger($targets);

Writing logs:

$logger->emergency('Emergency message', ['key' => 'value']);
$logger->alert('Alert message', ['key' => 'value']);
$logger->critical('Critical message', ['key' => 'value']);
$logger->warning('Warning message', ['key' => 'value']);
$logger->notice('Notice message', ['key' => 'value']);
$logger->info('Info message', ['key' => 'value']);
$logger->debug('Debug message', ['key' => 'value']);

PSR-3 Message Placeholders

The logger is PSR-3 compatible and supports message placeholders with additional enhancements. Placeholders in the message string are replaced with values from the context array:

$logger->info('User {username} logged in from {ip}', [
    'username' => 'john_doe',
    'ip' => '192.168.1.1',
]);
// Logs: "User john_doe logged in from 192.168.1.1"

Placeholder names must be enclosed in curly braces {placeholder} and correspond to keys in the context array.

Nested Context Values

As an enhancement beyond the PSR-3 specification, the logger supports accessing nested array values using dot notation:

$logger->info('User {user.name} with ID {user.id} performed action', [
    'user' => [
        'id' => 123,
        'name' => 'John Doe',
    ],
]);
// Logs: "User John Doe with ID 123 performed action"

Supported Data Types

Placeholders can handle various data types:

  • Strings and numbers: Rendered as-is
  • null: Rendered as an empty string
  • Stringable objects: Converted using __toString()
  • Arrays and objects: Rendered as formatted strings using VarDumper
$logger->warning('Failed to process order {order_id}', [
    'order_id' => 12345,
]);

$logger->error('Invalid data: {data}', [
    'data' => ['key' => 'value'],
]);

Context Data Preservation

The context array is preserved in the log message and can be used by log targets for filtering, formatting, or exporting. This allows you to pass structured data alongside human-readable messages:

$logger->info('Payment processed', [
    'amount' => 99.99,
    'currency' => 'USD',
    'transaction_id' => 'txn_123456',
    'user_id' => 42,
]);

Message Flushing and Exporting

Log messages are collected and stored in memory. To limit memory consumption, the logger will flush the recorded messages to the log targets each time a certain number of log messages accumulate. You can customize this number by calling the \Yiisoft\Log\Logger::setFlushInterval() method:

$logger->setFlushInterval(100); // default is 1000

Each log target also collects and stores messages in memory. Message exporting in a target follows the same principle as in the logger. To change the number of stored messages, pass the exportInterval constructor parameter:

$target = new \Yiisoft\Log\StreamTarget(exportInterval: 100); // default is 1000

The setExportInterval() setter is deprecated; use the constructor parameter instead. The same applies to setCategories(), setExcept(), setLevels(), setFormat(), setPrefix(), setTimestampFormat() and setEnabled().

Note: All message flushing and exporting also occurs when the application ends.

Logging targets

This package contains two targets:

  • Yiisoft\Log\PsrTarget - passes log messages to another PSR-3 compatible logger.
  • Yiisoft\Log\StreamTarget - writes log messages to the specified output stream.

Extra logging targets are implemented as separate packages:

Context providers

Context providers are used to provide additional context data for log messages. You can define your own context provider in the Logger constructor:

$logger = new \Yiisoft\Log\Logger(contextProvider: $myContextProvider);

Out of the box, the following context providers are available:

  • SystemContextProvider — adds system information (time, memory usage, trace, default category);
  • CommonContextProvider — adds common data;
  • CompositeContextProvider — allows combining multiple context providers.

By default, the logger uses the built-in SystemContextProvider.

SystemContextProvider

The SystemContextProvider adds the following data to the context:

  • time — current Unix timestamp with microseconds (float value);
  • trace — array of call stack information;
  • memory — memory usage in bytes.
  • category — category of the log message (always "application").

Yiisoft\Log\ContextProvider\SystemContextProvider constructor parameters:

  • traceLevel — how much call stack information (file name and line number) should be logged for each log message. If the traceLevel is greater than 0, a similar number of call stacks will be logged at most. Note that only application call stacks are counted.
  • excludedTracePaths — array of paths to exclude from tracing when tracing is enabled with traceLevel.

An example of custom parameters' usage:

$logger = new \Yiisoft\Log\Logger(
    contextProvider: new Yiisoft\Log\ContextProvider\SystemContextProvider(
        traceLevel: 3,
        excludedTracePaths: [
            '/vendor/yiisoft/di',
        ],
    ),
);

CommonContextProvider

The CommonContextProvider allows the adding of additional common information to the log context, for example:

$logger = new \Yiisoft\Log\Logger(
    contextProvider: new Yiisoft\Log\ContextProvider\CommonContextProvider([
       'environment' => 'production',
    ]),
);

CompositeContextProvider

The CompositeContextProvider allows the combining of multiple context providers into one, for example:

$logger = new \Yiisoft\Log\Logger(
    contextProvider: new Yiisoft\Log\ContextProvider\CompositeContextProvider(
        new Yiisoft\Log\ContextProvider\SystemContextProvider(),
        new Yiisoft\Log\ContextProvider\CommonContextProvider(['environment' => 'production'])
    ),
);

Configuring LoggerInterface in Yii3

In a Yii3 application, Psr\Log\LoggerInterface is resolved through the DI container. To use Yiisoft\Log\Logger as the implementation, add the binding to your application's DI config (e.g. config/common/di/logger.php):

use Psr\Log\LoggerInterface;
use Yiisoft\Definitions\ReferencesArray;
use Yiisoft\Log\Logger;
use Yiisoft\Log\StreamTarget;
use Yiisoft\Log\Target\File\FileTarget;

return [
    LoggerInterface::class => [
        'class' => Logger::class,
        '__construct()' => [
            'targets' => ReferencesArray::from([
                FileTarget::class,
                StreamTarget::class,
            ]),
        ],
    ],
];

Each target listed in ReferencesArray::from() is resolved by the DI container as a separate service. Target packages like yiisoft/log-target-file ship their own di.php and params.php configs that are merged automatically by the config plugin, so FileTarget works out of the box with default settings (writes to @runtime/logs/app.log with rotation). StreamTarget from this package writes to php://stdout by default and requires no extra configuration.

To use only StreamTarget without the file target package:

use Psr\Log\LoggerInterface;
use Yiisoft\Definitions\ReferencesArray;
use Yiisoft\Log\Logger;
use Yiisoft\Log\StreamTarget;

return [
    LoggerInterface::class => [
        'class' => Logger::class,
        '__construct()' => [
            'targets' => ReferencesArray::from([
                StreamTarget::class,
            ]),
        ],
    ],
];

When using the yiisoft/config plugin, the shipped event configs are loaded automatically. The package provides events-web.php and events-console.php files that define event handlers to flush logs after the HTTP response is emitted and when a console command terminates.

Documentation

If you need help or have a question, the Yii Forum is available. You may also check out other Yii Community Resources.

License

The Yii Logging Library is free software. It is released under the terms of the BSD License. Please see LICENSE for more information.

Maintained by Yii Software.

Support the project

Open Collective

Follow updates

Official website Twitter Telegram Facebook Slack

yiisoft/log 适用场景与选型建议

yiisoft/log 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 954.94k 次下载、GitHub Stars 达 43, 最近一次更新时间为 2018 年 07 月 15 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「log」 「framework」 「logger」 「yii」 「psr-3」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 yiisoft/log 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 yiisoft/log 我们能提供哪些服务?
定制开发 / 二次开发

基于 yiisoft/log 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 954.94k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 46
  • 点击次数: 19
  • 依赖项目数: 82
  • 推荐数: 2

GitHub 信息

  • Stars: 43
  • Watchers: 15
  • Forks: 21
  • 开发语言: PHP

其他信息

  • 授权协议: BSD-3-Clause
  • 更新时间: 2018-07-15