kariricode/logging 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

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

kariricode/logging

Composer 安装命令:

composer require kariricode/logging

包简介

A robust, flexible, and PSR-3 compliant logging component for the KaririCode Framework, providing comprehensive logging capabilities for PHP applications.

README 文档

README

en pt-br

Docker Makefile PHP PHPUnit

A robust, flexible, and PSR-3 compliant logging component for the KaririCode Framework, providing comprehensive logging capabilities for PHP applications.

Features

  • PSR-3 compliant
  • Supports multiple log channels (file, Slack, Papertrail, Elasticsearch)
  • Log encryption
  • Asynchronous logging support
  • Query and performance logging
  • Flexible logging formatters
  • Supports log rotation and cleanup
  • Circuit breaker and retry logic for logging
  • Detailed context and structured logging

Installation

To install the KaririCode Logging component, run the following command:

composer require kariricode/logging

Basic Usage

Step 1: Environment Configuration

The KaririCode Logging Component relies on several environment variables to configure logging channels, log levels, external services, and other parameters. These variables are defined in a .env file, and the project comes with a default .env.example that should be copied to .env for initial setup.

To copy and create your .env file, run the following command:

make setup-env

This command will create a .env file if it doesn't already exist. Afterward, you can modify the values according to your requirements. Below are some key variables and their descriptions:

# Application environment (e.g., production, develop)
KARIRICODE_APP=develop

# PHP version and port used by the Docker service
KARIRICODE_PHP_VERSION=8.3
KARIRICODE_PHP_PORT=9303

# Default log channel (e.g., file, stderr, slack)
LOG_CHANNEL=file

# Log level (e.g., debug, info, warning, error)
LOG_LEVEL=debug

# Encryption key for log data (ensure this is kept secure)
LOG_ENCRYPTION_KEY=83302e6472acda6a8aeadf78409ceda3959994991393cdafbe23d2a46a148ba4

# Slack configuration for sending critical logs
SLACK_BOT_TOKEN=xoxb-your-bot-token-here
SLACK_CHANNEL=#your-channel-name

# Papertrail logging service configuration
PAPERTRAIL_URL=logs.papertrailapp.com
PAPERTRAIL_PORT=12345

# Formatter for logs written to stderr
LOG_STDERR_FORMATTER=json

# Elasticsearch index for storing logs
ELASTIC_LOG_INDEX=logging-logs

# Enable or disable asynchronous logging
ASYNC_LOG_ENABLED=true

# Enable or disable query logging, and configure thresholds
QUERY_LOG_ENABLED=true
QUERY_LOG_CHANNEL=file
QUERY_LOG_THRESHOLD=100

# Enable or disable performance logging, and configure thresholds
PERFORMANCE_LOG_ENABLED=true
PERFORMANCE_LOG_CHANNEL=file
PERFORMANCE_LOG_THRESHOLD=1000

# Enable or disable error logging
ERROR_LOG_ENABLED=true
ERROR_LOG_CHANNEL=file

# Log cleanup configuration (automatic removal of logs older than the specified number of days)
LOG_CLEANER_ENABLED=true
LOG_CLEANER_KEEP_DAYS=30

# Circuit breaker configuration for managing log retries
CIRCUIT_BREAKER_FAILURE_THRESHOLD=3
CIRCUIT_BREAKER_RESET_TIMEOUT=60

# Retry configuration for log failures
RETRY_MAX_ATTEMPTS=3
RETRY_DELAY=1000
RETRY_MULTIPLIER=2
RETRY_JITTER=100

Each of these variables can be adjusted according to your specific needs:

  • Log Channels: You can choose between different logging channels such as file, slack, or stderr. For example, LOG_CHANNEL=slack will send critical logs to a Slack channel.
  • Log Levels: This defines the minimum severity level for logs to be recorded (e.g., debug, info, warning, error, critical).
  • External Services: If you want to send logs to external services like Slack or Papertrail, ensure you correctly set SLACK_BOT_TOKEN, PAPERTRAIL_URL, and PAPERTRAIL_PORT.

Step 2: Loading Environment Variables and Configurations

After configuring your .env file, you need to load the environment variables in your application and specify the path to the logging configuration file. This is done in the initialization of the application.

Here’s how to set it up in your application.php file:

<?php

require_once __DIR__ . '/../vendor/autoload.php';

use KaririCode\Logging\LoggerConfiguration;
use KaririCode\Logging\LoggerFactory;
use KaririCode\Logging\LoggerRegistry;
use KaririCode\Logging\Service\LoggerServiceProvider;
use KaririCode\Logging\Util\Config;

// Load environment variables from the .env file
Config::loadEnv();

// Specify the path to the logging configuration file
$configPath = __DIR__ . '/../config/logging.php';

// Initialize the logger configuration
$loggerConfig = new LoggerConfiguration();
$loggerConfig->load($configPath);

// Create the logger factory and registry
$loggerFactory = new LoggerFactory($loggerConfig);
$loggerRegistry = new LoggerRegistry();

// Register the loggers using the service provider
$serviceProvider = new LoggerServiceProvider(
    $loggerConfig,
    $loggerFactory,
    $loggerRegistry
);
$serviceProvider->register();

Step 3: Logging Example

Once the environment variables and the configuration are loaded, you can start using the loggers. Here's an example of logging messages at different levels:

$defaultLogger = $loggerRegistry->getLogger('console');

// Log messages with different severity levels
$defaultLogger->debug('User email is john.doe@example.com');
$defaultLogger->info('User IP is 192.168.1.1');
$defaultLogger->notice('User credit card number is 1234-5678-1234-5678', ['context' => 'credit card']);
$defaultLogger->warning('User phone number is (11) 91234-7890', ['context' => 'phone']);
$defaultLogger->error('An error occurred with email john.doe@example.com', ['context' => 'error']);
$defaultLogger->critical('Critical issue with IP 192.168.1.1', ['context' => 'critical']);
$defaultLogger->alert('Alert regarding credit card 1234-5678-1234-5678', ['context' => 'alert']);
$defaultLogger->emergency('Emergency with phone number 123-456-7890', ['context' => 'emergency']);

Step 4: Using Specialized Loggers

The KaririCode Logging Component also supports specialized loggers, such as for asynchronous logging, query logging, and performance logging. Here’s how you can use these loggers:

// Asynchronous logger
$asyncLogger = $loggerRegistry->getLogger('async');
if ($asyncLogger) {
    for ($i = 0; $i < 3; ++$i) {
        $asyncLogger->info("Async log message {$i}", ['context' => "batch {$i}"]);
    }
}

// Query logger for database queries
$queryLogger = $loggerRegistry->getLogger('query');
$queryLogger->info('Executing query', ['query' => 'SELECT * FROM users', 'bindings' => []]);

// Performance logger to track execution time
$performanceLogger = $loggerRegistry->getLogger('performance');
$performanceLogger->debug('Performance log', ['execution_time' => 1000]);

// Error logger for handling critical errors
$errorLogger = $loggerRegistry->getLogger('error');
$errorLogger->error('A critical error occurred', ['context' => 'Error details']);

Step 5: Sending Critical Logs to Slack

If you've configured Slack as a logging channel in the .env file, you can send critical logs directly to a specified Slack channel:

$slackLogger = $loggerRegistry->getLogger('slack');
$slackLogger->critical('This is a critical message sent to Slack', ['context' => 'slack']);

Make sure you’ve set your SLACK_BOT_TOKEN and SLACK_CHANNEL in the .env file for this to work properly.

Testing

To run tests for the KaririCode Logging Component, you can use PHPUnit. Run the following command inside your Docker container:

make test

For test coverage:

make coverage

License

This project is licensed under the MIT License - see the LICENSE file for details.

Support and Community

Acknowledgments

  • The KaririCode Framework team and contributors.
  • The PHP community for their continuous support and inspiration.

Built with ❤️ by the KaririCode team. Empowering developers to build more robust and flexible PHP applications.

Maintained by Walmir Silva - walmir.silva@kariricode.org

kariricode/logging 适用场景与选型建议

kariricode/logging 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 10 次下载、GitHub Stars 达 0, 最近一次更新时间为 2024 年 09 月 23 日, 在 PHP 生态内属于活跃度较高的组件。

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

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

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

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

  • 总下载量: 10
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 29
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 0
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2024-09-23