Skip to content

Commit

Permalink
First commit
Browse files Browse the repository at this point in the history
  • Loading branch information
= committed Mar 15, 2022
1 parent 5896a79 commit d9b80dc
Show file tree
Hide file tree
Showing 7 changed files with 427 additions and 2 deletions.
5 changes: 5 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
/.idea/
/.vs/
/.vscode/
/vendor/
/composer.lock
145 changes: 143 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,143 @@
# Logger
InitPHP Logger Library
# InitPHP Logger

Logger class in accordance with PSR-3 standards

[![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)

## Features

- Keeping logs to the database with PDO.
- Printing log records to a file.
- Logging feature with multiple drivers.

## Requirements

- PHP 5.6 or higher
- [PSR-3 Interface Package](https://www.php-fig.org/psr/psr-3/)
- PDO Extension (Only `PDOLogger`)

## Installation

```
composer require initphp/logger
```

## Using

### FileLogger

```php
require_once "vendor/autoload.php";
use \InitPHP\Logger\Logger;
use \InitPHP\Logger\FileLogger;

$logFile = __DIR__ . '/logfile.log';

$logger = new Logger(new FileLogger($logFile));
```

### PdoLogger

```php
require_once "vendor/autoload.php";
use \InitPHP\Logger\Logger;
use \InitPHP\Logger\PDOLogger;

$table = 'logs';
$pdo = new \PDO('mysql:dbname=project;host=localhost', 'root', '');

$logger = new Logger(new PDOLogger($pdo, $table));

$logger->error('User {user} caused an error.', array('user' => 'muhametsafak'));
// INSERT INTO logs (level, message, date) VALUES ('ERROR', 'User muhametsafak caused an error.', '2022-03-11 13:05:45')
```

You can use the following SQL statement to create a sample MySQL table.

```sql
CREATE TABLE `logs` (
`level` ENUM('EMERGENCY','ALERT','CRITICAL','ERROR','WARNING','NOTICE','INFO','DEBUG') NOT NULL,
`message` TEXT NOT NULL,
`date` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE = InnoDB CHARSET=utf8mb4 COLLATE utf8mb4_general_ci;
```

### Multi Logger

```php
require_once "vendor/autoload.php";
use \InitPHP\Logger\Logger;
use \InitPHP\Logger\PDOLogger;
use \InitPHP\Logger\FileLogger;

$logFile = __DIR__ . '/logfile.log';

$table = 'logs';
$pdo = new \PDO('mysql:dbname=project;host=localhost', 'root', '');

$logger = new Logger(new FileLogger($logFile), new PDOLogger($pdo, $table));
```

## Methods

```php
public function emergency(string $msg, array $context = array()): void;

public function alert(string $msg, array $context = array()): void;

public function critical(string $msg, array $context = array()): void;

public function error(string $msg, array $context = array()): void;

public function warning(string $msg, array $context = array()): void;

public function notice(string $msg, array $context = array()): void;

public function info(string $msg, array $context = array()): void;

public function debug(string $msg, array $context = array()): void;

public function log(string $level, string $msg, array $context = array()): void;
```

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.

**Example 1 :**

```php
$logger->emergency("Something went wrong");
```

It prints an output like this to the log file.

```
2021-09-29T13:34:47+02:00 [EMERGENCY] Something went wrong
```

**Example 2:**

```php
$logger->error("User {username} caused an error.", ["username" => "john"]);
```

It prints an output like this to the log file.

```
2021-09-29T13:34:47+02:00 [ERROR] User john caused an error.
```

That is all.

***

## Getting Help

If you have questions, concerns, bug reports, etc, please file an issue in this repository's Issue Tracker.

## Credits

- [Muhammet ŞAFAK](https://www.muhammetsafak.com.tr)

## License

Copyright © 2022 [MIT License](./LICENSE)
24 changes: 24 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
{
"name": "initphp/logger",
"description": "PSR-3 Logger Library",
"type": "library",
"license": "MIT",
"autoload": {
"psr-4": {
"InitPHP\\Logger\\": "src/"
}
},
"authors": [
{
"name": "Muhammet ŞAFAK",
"email": "info@muhammetsafak.com.tr",
"role": "Developer",
"homepage": "https://www.muhammetsafak.com.tr"
}
],
"minimum-stability": "stable",
"require": {
"php": ">=5.6",
"psr/log": "1.1.4"
}
}
59 changes: 59 additions & 0 deletions src/FileLogger.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
<?php
/**
* FileLogger.php
*
* This file is part of InitPHP.
*
* @author Muhammet ŞAFAK <info@muhammetsafak.com.tr>
* @copyright Copyright © 2022 InitPHP
* @license http://initphp.github.io/license.txt MIT
* @version 1.0
* @link https://www.muhammetsafak.com.tr
*/

namespace InitPHP\Logger;

use \Psr\Log\AbstractLogger;
use \Psr\Log\LoggerInterface;

use const PHP_EOL;
use const FILE_APPEND;

use function strtoupper;
use function date;

class FileLogger extends \Psr\Log\AbstractLogger implements \Psr\Log\LoggerInterface
{
use HelperTrait;

/** @var string */
protected $path;

/**
* @param string $path
*/
public function __construct($path)
{
$this->path = $this->interpolate($path, array(
'year' => date('Y'),
'month' => date('m'),
'day' => date('d'),
'hour' => date('H'),
'minute' => date('i'),
'second' => date('s')
));
}

/**
* @inheritDoc
*/
public function log($level, $message, array $context = array())
{
$this->logLevelVerify($level);
$msg = PHP_EOL . $this->getDate('c') . ' ['
. strtoupper($level)
. '] ' . $this->interpolate($message, $context);
@file_put_contents($this->path, $msg, FILE_APPEND);
}

}
82 changes: 82 additions & 0 deletions src/HelperTrait.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
<?php
/**
* HelperTrait.php
*
* This file is part of InitPHP.
*
* @author Muhammet ŞAFAK <info@muhammetsafak.com.tr>
* @copyright Copyright © 2022 InitPHP
* @license http://initphp.github.io/license.txt MIT
* @version 1.0
* @link https://www.muhammetsafak.com.tr
*/

namespace InitPHP\Logger;

use \DateTime;
use \Psr\Log\InvalidArgumentException;
use \Psr\Log\LogLevel;

use function strtolower;
use function in_array;
use function implode;
use function is_array;
use function is_object;
use function method_exists;
use function strtr;

trait HelperTrait
{
/** @var array */
private $levels = array(
LogLevel::EMERGENCY,
LogLevel::ALERT,
LogLevel::CRITICAL,
LogLevel::ERROR,
LogLevel::WARNING,
LogLevel::WARNING,
LogLevel::NOTICE,
LogLevel::INFO,
LogLevel::DEBUG
);

/**
* @param string $msg
* @param array $context
* @return string
*/
protected function interpolate($msg, array $context = array())
{
if(empty($context)){
return $msg;
}else{
$replace = array();
foreach ($context as $key => $val) {
if (!is_array($val) && (!is_object($val) || method_exists($val, '__toString'))) {
$replace['{' . $key . '}'] = $val;
}
}
return strtr($msg, $replace);
}
}

/**
* @param string $format
* @return string
*/
protected function getDate($format = 'c')
{
return (new DateTime('now'))->format($format);
}

/**
* @param $level
* @return void
*/
protected function logLevelVerify($level)
{
if(in_array(strtolower($level), $this->levels, true) === FALSE){
throw new InvalidArgumentException('Only ' . implode(', ', $this->levels) . ' levels can be logged.');
}
}
}
50 changes: 50 additions & 0 deletions src/Logger.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
<?php
/**
* Logger.php
*
* This file is part of InitPHP.
*
* @author Muhammet ŞAFAK <info@muhammetsafak.com.tr>
* @copyright Copyright © 2022 InitPHP
* @license http://initphp.github.io/license.txt MIT
* @version 1.0
* @link https://www.muhammetsafak.com.tr
*/

namespace InitPHP\Logger;

use \Psr\Log\LoggerInterface;

/**
* @method void emergency(string $message, array $context = array())
* @method void alert(string $message, array $context = array())
* @method void critical(string $message, array $context = array())
* @method void error(string $message, array $context = array())
* @method void warning(string $message, array $context = array())
* @method void notice(string $message, array $context = array())
* @method void info(string $message, array $context = array())
* @method void debug(string $message, array $context = array())
* @method void log(string $level, string $message, array $context = array())
*/
class Logger
{
/** @var LoggerInterface[] */
protected $loggers = [];

public function __construct(...$loggers)
{
foreach ($loggers as $log) {
if($log instanceof LoggerInterface){
$this->loggers[] = $log;
}
}
}

public function __call($name, $arguments)
{
foreach ($this->loggers as $logger) {
$logger->{$name}(...$arguments);
}
}

}
Loading

0 comments on commit d9b80dc

Please sign in to comment.