Skip to content

Commit d9b80dc

Browse files
author
=
committed
First commit
1 parent 5896a79 commit d9b80dc

File tree

7 files changed

+427
-2
lines changed

7 files changed

+427
-2
lines changed

.gitignore

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
/.idea/
2+
/.vs/
3+
/.vscode/
4+
/vendor/
5+
/composer.lock

README.md

Lines changed: 143 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,143 @@
1-
# Logger
2-
InitPHP Logger Library
1+
# InitPHP Logger
2+
3+
Logger class in accordance with PSR-3 standards
4+
5+
[![Latest Stable Version](http://poser.pugx.org/initphp/logger/v)](https://packagist.org/packages/initphp/logger) [![Total Downloads](http://poser.pugx.org/initphp/logger/downloads)](https://packagist.org/packages/initphp/logger) [![Latest Unstable Version](http://poser.pugx.org/initphp/logger/v/unstable)](https://packagist.org/packages/initphp/logger) [![License](http://poser.pugx.org/initphp/logger/license)](https://packagist.org/packages/initphp/logger) [![PHP Version Require](http://poser.pugx.org/initphp/logger/require/php)](https://packagist.org/packages/initphp/logger)
6+
7+
## Features
8+
9+
- Keeping logs to the database with PDO.
10+
- Printing log records to a file.
11+
- Logging feature with multiple drivers.
12+
13+
## Requirements
14+
15+
- PHP 5.6 or higher
16+
- [PSR-3 Interface Package](https://www.php-fig.org/psr/psr-3/)
17+
- PDO Extension (Only `PDOLogger`)
18+
19+
## Installation
20+
21+
```
22+
composer require initphp/logger
23+
```
24+
25+
## Using
26+
27+
### FileLogger
28+
29+
```php
30+
require_once "vendor/autoload.php";
31+
use \InitPHP\Logger\Logger;
32+
use \InitPHP\Logger\FileLogger;
33+
34+
$logFile = __DIR__ . '/logfile.log';
35+
36+
$logger = new Logger(new FileLogger($logFile));
37+
```
38+
39+
### PdoLogger
40+
41+
```php
42+
require_once "vendor/autoload.php";
43+
use \InitPHP\Logger\Logger;
44+
use \InitPHP\Logger\PDOLogger;
45+
46+
$table = 'logs';
47+
$pdo = new \PDO('mysql:dbname=project;host=localhost', 'root', '');
48+
49+
$logger = new Logger(new PDOLogger($pdo, $table));
50+
51+
$logger->error('User {user} caused an error.', array('user' => 'muhametsafak'));
52+
// INSERT INTO logs (level, message, date) VALUES ('ERROR', 'User muhametsafak caused an error.', '2022-03-11 13:05:45')
53+
```
54+
55+
You can use the following SQL statement to create a sample MySQL table.
56+
57+
```sql
58+
CREATE TABLE `logs` (
59+
`level` ENUM('EMERGENCY','ALERT','CRITICAL','ERROR','WARNING','NOTICE','INFO','DEBUG') NOT NULL,
60+
`message` TEXT NOT NULL,
61+
`date` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
62+
) ENGINE = InnoDB CHARSET=utf8mb4 COLLATE utf8mb4_general_ci;
63+
```
64+
65+
### Multi Logger
66+
67+
```php
68+
require_once "vendor/autoload.php";
69+
use \InitPHP\Logger\Logger;
70+
use \InitPHP\Logger\PDOLogger;
71+
use \InitPHP\Logger\FileLogger;
72+
73+
$logFile = __DIR__ . '/logfile.log';
74+
75+
$table = 'logs';
76+
$pdo = new \PDO('mysql:dbname=project;host=localhost', 'root', '');
77+
78+
$logger = new Logger(new FileLogger($logFile), new PDOLogger($pdo, $table));
79+
```
80+
81+
## Methods
82+
83+
```php
84+
public function emergency(string $msg, array $context = array()): void;
85+
86+
public function alert(string $msg, array $context = array()): void;
87+
88+
public function critical(string $msg, array $context = array()): void;
89+
90+
public function error(string $msg, array $context = array()): void;
91+
92+
public function warning(string $msg, array $context = array()): void;
93+
94+
public function notice(string $msg, array $context = array()): void;
95+
96+
public function info(string $msg, array $context = array()): void;
97+
98+
public function debug(string $msg, array $context = array()): void;
99+
100+
public function log(string $level, string $msg, array $context = array()): void;
101+
```
102+
103+
All of the above methods are used the same way, except for the `log()` method. You can use the `log()` method for your own custom error levels.
104+
105+
**Example 1 :**
106+
107+
```php
108+
$logger->emergency("Something went wrong");
109+
```
110+
111+
It prints an output like this to the log file.
112+
113+
```
114+
2021-09-29T13:34:47+02:00 [EMERGENCY] Something went wrong
115+
```
116+
117+
**Example 2:**
118+
119+
```php
120+
$logger->error("User {username} caused an error.", ["username" => "john"]);
121+
```
122+
123+
It prints an output like this to the log file.
124+
125+
```
126+
2021-09-29T13:34:47+02:00 [ERROR] User john caused an error.
127+
```
128+
129+
That is all.
130+
131+
***
132+
133+
## Getting Help
134+
135+
If you have questions, concerns, bug reports, etc, please file an issue in this repository's Issue Tracker.
136+
137+
## Credits
138+
139+
- [Muhammet ŞAFAK](https://www.muhammetsafak.com.tr)
140+
141+
## License
142+
143+
Copyright © 2022 [MIT License](./LICENSE)

composer.json

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
{
2+
"name": "initphp/logger",
3+
"description": "PSR-3 Logger Library",
4+
"type": "library",
5+
"license": "MIT",
6+
"autoload": {
7+
"psr-4": {
8+
"InitPHP\\Logger\\": "src/"
9+
}
10+
},
11+
"authors": [
12+
{
13+
"name": "Muhammet ŞAFAK",
14+
"email": "[email protected]",
15+
"role": "Developer",
16+
"homepage": "https://www.muhammetsafak.com.tr"
17+
}
18+
],
19+
"minimum-stability": "stable",
20+
"require": {
21+
"php": ">=5.6",
22+
"psr/log": "1.1.4"
23+
}
24+
}

src/FileLogger.php

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
<?php
2+
/**
3+
* FileLogger.php
4+
*
5+
* This file is part of InitPHP.
6+
*
7+
* @author Muhammet ŞAFAK <[email protected]>
8+
* @copyright Copyright © 2022 InitPHP
9+
* @license http://initphp.github.io/license.txt MIT
10+
* @version 1.0
11+
* @link https://www.muhammetsafak.com.tr
12+
*/
13+
14+
namespace InitPHP\Logger;
15+
16+
use \Psr\Log\AbstractLogger;
17+
use \Psr\Log\LoggerInterface;
18+
19+
use const PHP_EOL;
20+
use const FILE_APPEND;
21+
22+
use function strtoupper;
23+
use function date;
24+
25+
class FileLogger extends \Psr\Log\AbstractLogger implements \Psr\Log\LoggerInterface
26+
{
27+
use HelperTrait;
28+
29+
/** @var string */
30+
protected $path;
31+
32+
/**
33+
* @param string $path
34+
*/
35+
public function __construct($path)
36+
{
37+
$this->path = $this->interpolate($path, array(
38+
'year' => date('Y'),
39+
'month' => date('m'),
40+
'day' => date('d'),
41+
'hour' => date('H'),
42+
'minute' => date('i'),
43+
'second' => date('s')
44+
));
45+
}
46+
47+
/**
48+
* @inheritDoc
49+
*/
50+
public function log($level, $message, array $context = array())
51+
{
52+
$this->logLevelVerify($level);
53+
$msg = PHP_EOL . $this->getDate('c') . ' ['
54+
. strtoupper($level)
55+
. '] ' . $this->interpolate($message, $context);
56+
@file_put_contents($this->path, $msg, FILE_APPEND);
57+
}
58+
59+
}

src/HelperTrait.php

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
<?php
2+
/**
3+
* HelperTrait.php
4+
*
5+
* This file is part of InitPHP.
6+
*
7+
* @author Muhammet ŞAFAK <[email protected]>
8+
* @copyright Copyright © 2022 InitPHP
9+
* @license http://initphp.github.io/license.txt MIT
10+
* @version 1.0
11+
* @link https://www.muhammetsafak.com.tr
12+
*/
13+
14+
namespace InitPHP\Logger;
15+
16+
use \DateTime;
17+
use \Psr\Log\InvalidArgumentException;
18+
use \Psr\Log\LogLevel;
19+
20+
use function strtolower;
21+
use function in_array;
22+
use function implode;
23+
use function is_array;
24+
use function is_object;
25+
use function method_exists;
26+
use function strtr;
27+
28+
trait HelperTrait
29+
{
30+
/** @var array */
31+
private $levels = array(
32+
LogLevel::EMERGENCY,
33+
LogLevel::ALERT,
34+
LogLevel::CRITICAL,
35+
LogLevel::ERROR,
36+
LogLevel::WARNING,
37+
LogLevel::WARNING,
38+
LogLevel::NOTICE,
39+
LogLevel::INFO,
40+
LogLevel::DEBUG
41+
);
42+
43+
/**
44+
* @param string $msg
45+
* @param array $context
46+
* @return string
47+
*/
48+
protected function interpolate($msg, array $context = array())
49+
{
50+
if(empty($context)){
51+
return $msg;
52+
}else{
53+
$replace = array();
54+
foreach ($context as $key => $val) {
55+
if (!is_array($val) && (!is_object($val) || method_exists($val, '__toString'))) {
56+
$replace['{' . $key . '}'] = $val;
57+
}
58+
}
59+
return strtr($msg, $replace);
60+
}
61+
}
62+
63+
/**
64+
* @param string $format
65+
* @return string
66+
*/
67+
protected function getDate($format = 'c')
68+
{
69+
return (new DateTime('now'))->format($format);
70+
}
71+
72+
/**
73+
* @param $level
74+
* @return void
75+
*/
76+
protected function logLevelVerify($level)
77+
{
78+
if(in_array(strtolower($level), $this->levels, true) === FALSE){
79+
throw new InvalidArgumentException('Only ' . implode(', ', $this->levels) . ' levels can be logged.');
80+
}
81+
}
82+
}

src/Logger.php

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
<?php
2+
/**
3+
* Logger.php
4+
*
5+
* This file is part of InitPHP.
6+
*
7+
* @author Muhammet ŞAFAK <[email protected]>
8+
* @copyright Copyright © 2022 InitPHP
9+
* @license http://initphp.github.io/license.txt MIT
10+
* @version 1.0
11+
* @link https://www.muhammetsafak.com.tr
12+
*/
13+
14+
namespace InitPHP\Logger;
15+
16+
use \Psr\Log\LoggerInterface;
17+
18+
/**
19+
* @method void emergency(string $message, array $context = array())
20+
* @method void alert(string $message, array $context = array())
21+
* @method void critical(string $message, array $context = array())
22+
* @method void error(string $message, array $context = array())
23+
* @method void warning(string $message, array $context = array())
24+
* @method void notice(string $message, array $context = array())
25+
* @method void info(string $message, array $context = array())
26+
* @method void debug(string $message, array $context = array())
27+
* @method void log(string $level, string $message, array $context = array())
28+
*/
29+
class Logger
30+
{
31+
/** @var LoggerInterface[] */
32+
protected $loggers = [];
33+
34+
public function __construct(...$loggers)
35+
{
36+
foreach ($loggers as $log) {
37+
if($log instanceof LoggerInterface){
38+
$this->loggers[] = $log;
39+
}
40+
}
41+
}
42+
43+
public function __call($name, $arguments)
44+
{
45+
foreach ($this->loggers as $logger) {
46+
$logger->{$name}(...$arguments);
47+
}
48+
}
49+
50+
}

0 commit comments

Comments
 (0)