kariricode / logging
为KaririCode框架提供的强大、灵活且遵循PSR-3规范的日志组件,为PHP应用程序提供全面的日志功能。
Requires
- php: ^8.3
- composer/composer: ^2.7
- kariricode/contract: ^2.6
Requires (Dev)
- enlightn/security-checker: ^2.0
- friendsofphp/php-cs-fixer: ^3.58
- mockery/mockery: ^1.6
- nunomaduro/phpinsights: ^2.11
- phpunit/phpunit: ^10.5
- squizlabs/php_codesniffer: ^3.10
This package is auto-updated.
Last update: 2024-09-28 16:32:16 UTC
README
为KaririCode框架提供的强大、灵活且遵循PSR-3规范的日志组件,为PHP应用程序提供全面的日志功能。
特性
- 遵循PSR-3规范
- 支持多个日志通道(文件、Slack、Papertrail、Elasticsearch)
- 日志加密
- 支持异步日志记录
- 查询和性能日志记录
- 灵活的日志格式化
- 支持日志轮转和清理
- 日志记录的断路器和重试逻辑
- 详细的上下文和结构化日志
安装
要安装KaririCode日志组件,请运行以下命令
composer require kariricode/logging
基本用法
步骤 1:环境配置
KaririCode日志组件依赖于多个环境变量来配置日志通道、日志级别、外部服务和其他参数。这些变量定义在一个.env
文件中,项目附带一个默认的.env.example
文件,应将其复制到.env
中进行初始设置。
要复制并创建您的.env
文件,请运行以下命令
make setup-env
此命令将在文件不存在的情况下创建一个.env
文件。之后,您可以根据需求修改值。以下是一些关键变量及其描述
# 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
每个这些变量都可以根据您的具体需求进行调整
- 日志通道:您可以选择不同的日志通道,例如
file
、slack
或stderr
。例如,LOG_CHANNEL=slack
将发送关键日志到Slack通道。 - 日志级别:这定义了记录日志的最小严重级别(例如,
debug
、info
、warning
、error
、critical
)。 - 外部服务:如果您想将日志发送到外部服务如Slack或Papertrail,确保您正确设置了
SLACK_BOT_TOKEN
、PAPERTRAIL_URL
和PAPERTRAIL_PORT
。
步骤 2:加载环境变量和配置
配置完您的.env
文件后,您需要在应用程序中加载环境变量并指定日志配置文件的路径。这在进行应用程序初始化时完成。
以下是如何在您的application.php
文件中设置它
<?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();
步骤 3:日志示例
加载环境变量和配置后,您就可以开始使用日志记录器了。以下是在不同级别记录日志消息的示例
$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']);
步骤 4:使用专用日志记录器
KaririCode日志组件还支持专用日志记录器,例如用于异步日志记录、查询日志记录和性能日志记录。以下是使用这些日志记录器的方法
// 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']);
步骤 5:将关键日志发送到Slack
如果您已在.env
文件中将Slack配置为日志通道,则可以直接将关键日志发送到指定的Slack通道
$slackLogger = $loggerRegistry->getLogger('slack'); $slackLogger->critical('This is a critical message sent to Slack', ['context' => 'slack']);
请确保您已在.env
文件中设置了SLACK_BOT_TOKEN
和SLACK_CHANNEL
,以便正确工作。
测试
要为KaririCode日志组件运行测试,您可以使用PHPUnit。在Docker容器内部运行以下命令
make test
测试覆盖率
make coverage
许可证
本项目受MIT许可证许可 - 有关详细信息,请参阅LICENSE文件。
支持和社区
- 文档:https://kariricode.org
- 问题跟踪器:GitHub Issues
- 社区: KaririCode Club 社区
- 专业支持: 如需企业级支持,请联系我们 support@kariricode.org
致谢
- 感谢 KaririCode 框架团队和贡献者。
- 感谢 PHP 社区持续的支持和灵感。
由 KaririCode 团队用❤️打造。赋予开发者构建更强大和灵活的 PHP 应用程序的能力。
由 Walmir Silva 维护 - walmir.silva@kariricode.org