Skip to content

Commit f23cac3

Browse files
authored
Merge pull request #2 from KaririCode-Framework/develop
docs: add README in English and Brazilian Portuguese
2 parents b9c0c45 + 82ed45c commit f23cac3

File tree

2 files changed

+421
-103
lines changed

2 files changed

+421
-103
lines changed

README.md

Lines changed: 244 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,245 @@
11
# KaririCode Framework: Logging Component
2+
3+
[![en](https://img.shields.io/badge/lang-en-red.svg)](README.md)
4+
[![pt-br](https://img.shields.io/badge/lang-pt--br-green.svg)](README.pt-br.md)
5+
6+
![Docker](https://img.shields.io/badge/Docker-2496ED?style=for-the-badge&logo=docker&logoColor=white)
7+
![Makefile](https://img.shields.io/badge/Makefile-1D1D1D?style=for-the-badge&logo=gnu&logoColor=white)
8+
![PHP](https://img.shields.io/badge/PHP-777BB4?style=for-the-badge&logo=php&logoColor=white)
9+
![PHPUnit](https://img.shields.io/badge/PHPUnit-78E130?style=for-the-badge&logo=phpunit&logoColor=white)
10+
11+
A robust, flexible, and PSR-3 compliant logging component for the KaririCode Framework, providing comprehensive logging capabilities for PHP applications.
12+
13+
## Features
14+
15+
- PSR-3 compliant
16+
- Supports multiple log channels (file, Slack, Papertrail, Elasticsearch)
17+
- Log encryption
18+
- Asynchronous logging support
19+
- Query and performance logging
20+
- Flexible logging formatters
21+
- Supports log rotation and cleanup
22+
- Circuit breaker and retry logic for logging
23+
- Detailed context and structured logging
24+
25+
## Installation
26+
27+
To install the KaririCode Logging component, run the following command:
28+
29+
```bash
30+
composer require kariricode/logging
31+
```
32+
33+
## Basic Usage
34+
35+
### Step 1: Environment Configuration
36+
37+
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.
38+
39+
To copy and create your `.env` file, run the following command:
40+
41+
```bash
42+
make setup-env
43+
```
44+
45+
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:
46+
47+
```ini
48+
# Application environment (e.g., production, develop)
49+
KARIRICODE_APP=develop
50+
51+
# PHP version and port used by the Docker service
52+
KARIRICODE_PHP_VERSION=8.3
53+
KARIRICODE_PHP_PORT=9303
54+
55+
# Default log channel (e.g., file, stderr, slack)
56+
LOG_CHANNEL=file
57+
58+
# Log level (e.g., debug, info, warning, error)
59+
LOG_LEVEL=debug
60+
61+
# Encryption key for log data (ensure this is kept secure)
62+
LOG_ENCRYPTION_KEY=83302e6472acda6a8aeadf78409ceda3959994991393cdafbe23d2a46a148ba4
63+
64+
# Slack configuration for sending critical logs
65+
SLACK_BOT_TOKEN=xoxb-your-bot-token-here
66+
SLACK_CHANNEL=#your-channel-name
67+
68+
# Papertrail logging service configuration
69+
PAPERTRAIL_URL=logs.papertrailapp.com
70+
PAPERTRAIL_PORT=12345
71+
72+
# Formatter for logs written to stderr
73+
LOG_STDERR_FORMATTER=json
74+
75+
# Elasticsearch index for storing logs
76+
ELASTIC_LOG_INDEX=logging-logs
77+
78+
# Enable or disable asynchronous logging
79+
ASYNC_LOG_ENABLED=true
80+
81+
# Enable or disable query logging, and configure thresholds
82+
QUERY_LOG_ENABLED=true
83+
QUERY_LOG_CHANNEL=file
84+
QUERY_LOG_THRESHOLD=100
85+
86+
# Enable or disable performance logging, and configure thresholds
87+
PERFORMANCE_LOG_ENABLED=true
88+
PERFORMANCE_LOG_CHANNEL=file
89+
PERFORMANCE_LOG_THRESHOLD=1000
90+
91+
# Enable or disable error logging
92+
ERROR_LOG_ENABLED=true
93+
ERROR_LOG_CHANNEL=file
94+
95+
# Log cleanup configuration (automatic removal of logs older than the specified number of days)
96+
LOG_CLEANER_ENABLED=true
97+
LOG_CLEANER_KEEP_DAYS=30
98+
99+
# Circuit breaker configuration for managing log retries
100+
CIRCUIT_BREAKER_FAILURE_THRESHOLD=3
101+
CIRCUIT_BREAKER_RESET_TIMEOUT=60
102+
103+
# Retry configuration for log failures
104+
RETRY_MAX_ATTEMPTS=3
105+
RETRY_DELAY=1000
106+
RETRY_MULTIPLIER=2
107+
RETRY_JITTER=100
108+
```
109+
110+
Each of these variables can be adjusted according to your specific needs:
111+
112+
- **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.
113+
- **Log Levels:** This defines the minimum severity level for logs to be recorded (e.g., `debug`, `info`, `warning`, `error`, `critical`).
114+
- **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`.
115+
116+
### Step 2: Loading Environment Variables and Configurations
117+
118+
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.
119+
120+
Here’s how to set it up in your `application.php` file:
121+
122+
```php
123+
<?php
124+
125+
require_once __DIR__ . '/../vendor/autoload.php';
126+
127+
use KaririCode\Logging\LoggerConfiguration;
128+
use KaririCode\Logging\LoggerFactory;
129+
use KaririCode\Logging\LoggerRegistry;
130+
use KaririCode\Logging\Service\LoggerServiceProvider;
131+
use KaririCode\Logging\Util\Config;
132+
133+
// Load environment variables from the .env file
134+
Config::loadEnv();
135+
136+
// Specify the path to the logging configuration file
137+
$configPath = __DIR__ . '/../config/logging.php';
138+
139+
// Initialize the logger configuration
140+
$loggerConfig = new LoggerConfiguration();
141+
$loggerConfig->load($configPath);
142+
143+
// Create the logger factory and registry
144+
$loggerFactory = new LoggerFactory($loggerConfig);
145+
$loggerRegistry = new LoggerRegistry();
146+
147+
// Register the loggers using the service provider
148+
$serviceProvider = new LoggerServiceProvider(
149+
$loggerConfig,
150+
$loggerFactory,
151+
$loggerRegistry
152+
);
153+
$serviceProvider->register();
154+
```
155+
156+
### Step 3: Logging Example
157+
158+
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:
159+
160+
```php
161+
$defaultLogger = $loggerRegistry->getLogger('console');
162+
163+
// Log messages with different severity levels
164+
$defaultLogger->debug('User email is john.doe@example.com');
165+
$defaultLogger->info('User IP is 192.168.1.1');
166+
$defaultLogger->notice('User credit card number is 1234-5678-1234-5678', ['context' => 'credit card']);
167+
$defaultLogger->warning('User phone number is (11) 91234-7890', ['context' => 'phone']);
168+
$defaultLogger->error('An error occurred with email john.doe@example.com', ['context' => 'error']);
169+
$defaultLogger->critical('Critical issue with IP 192.168.1.1', ['context' => 'critical']);
170+
$defaultLogger->alert('Alert regarding credit card 1234-5678-1234-5678', ['context' => 'alert']);
171+
$defaultLogger->emergency('Emergency with phone number 123-456-7890', ['context' => 'emergency']);
172+
```
173+
174+
### Step 4: Using Specialized Loggers
175+
176+
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:
177+
178+
```php
179+
// Asynchronous logger
180+
$asyncLogger = $loggerRegistry->getLogger('async');
181+
if ($asyncLogger) {
182+
for ($i = 0; $i < 3; ++$i) {
183+
$asyncLogger->info("Async log message {$i}", ['context' => "batch {$i}"]);
184+
}
185+
}
186+
187+
// Query logger for database queries
188+
$queryLogger = $loggerRegistry->getLogger('query');
189+
$queryLogger->info('Executing query', ['query' => 'SELECT * FROM users', 'bindings' => []]);
190+
191+
// Performance logger to track execution time
192+
$performanceLogger = $loggerRegistry->getLogger('performance');
193+
$performanceLogger->debug('Performance log', ['execution_time' => 1000]);
194+
195+
// Error logger for handling critical errors
196+
$errorLogger = $loggerRegistry->getLogger('error');
197+
$errorLogger->error('A critical error occurred', ['context' => 'Error details']);
198+
```
199+
200+
### Step 5: Sending Critical Logs to Slack
201+
202+
If you've configured Slack as a logging channel in the `.env` file, you can send critical logs directly to a specified Slack channel:
203+
204+
```php
205+
$slackLogger = $loggerRegistry->getLogger('slack');
206+
$slackLogger->critical('This is a critical message sent to Slack', ['context' => 'slack']);
207+
```
208+
209+
Make sure you’ve set your `SLACK_BOT_TOKEN` and `SLACK_CHANNEL` in the `.env` file for this to work properly.
210+
211+
## Testing
212+
213+
To run tests for the KaririCode Logging Component, you can use PHPUnit. Run the following command inside your Docker container:
214+
215+
```bash
216+
make test
217+
```
218+
219+
For test coverage:
220+
221+
```bash
222+
make coverage
223+
```
224+
225+
## License
226+
227+
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
228+
229+
## Support and Community
230+
231+
- **Documentation**: [https://kariricode.org](https://kariricode.org)
232+
- **Issue Tracker**: [GitHub Issues](https://github.com/KaririCode-Framework/kariricode-contract/issues)
233+
- **Community**: [KaririCode Club Community](https://kariricode.club)
234+
- **Professional Support**: For enterprise-level support, contact us at support@kariricode.org
235+
236+
## Acknowledgments
237+
238+
- The KaririCode Framework team and contributors.
239+
- The PHP community for their continuous support and inspiration.
240+
241+
---
242+
243+
Built with ❤️ by the KaririCode team. Empowering developers to build more robust and flexible PHP applications.
244+
245+
Maintained by Walmir Silva - [walmir.silva@kariricode.org](mailto:walmir.silva@kariricode.org)

0 commit comments

Comments
 (0)