当前位置: 首页 > 工具软件 > LoggerOne > 使用案例 >

php 日志处理类,LoggerOne - 高效、简约、强扩展性PHP日志类库

糜野
2023-12-01

LoggerOne

One Efficient & Light & Flexible high performance PHP log implemention of PSR-3

一个高效、简约、灵活高性能的遵循PSR-3的PHP日志类库实现。

特性/Features

Inherently cached message record using PHP object attribute.

天然的缓存特性(Logger实例属性),延迟批量写入。

安装&使用/Istall&Usage

Install

$ composer require logger-one/logger-one

Invoke by default mode - 默认的调用方式

Will using FileHandler create a log file named for %Y%m%d and appendix .log at LoggerOne root folder, ervery message as line with the original - 在默认情况下,Logger会使用FileHandler 和 CommonFormatter 输出一个保存在Logger同目录的命名格式为 %Y%m%d的日志文件。

$logger = LoggerOne\Logger::getInstance(); // Strongly recommend

$message = 'test log message {placeholder1} {placeholder2}';

$replacements = ['placeholder1' => 'Foo', 'placeholder2' => 'bar'];

$logger->info($message, $replacements);

Change FileHandler default path - 改变默认日志文件保存地址

$logFile = './tmp/loggerOne.log'; // Your path where you want

$handler = new LoggerOne\Handler\FileHandler($logFile);

$logger->setHandler($handler);

$logger->info($message);

Specific Handler & Formatter - 指定使用特定的Handler/Formatter

$handler = new LoggerOne\Handler\FooHandler();

$handler = new LoggerOne\Formatter\BarFormatter();

$logger->setHandler($handler)->setFormatter($formatter);

$logger->info('some test log message');

Flush log message immediately - 立即输出到日志文件的调用方法

Once calling flush method will write all previous message by handler - 这样将不缓存日志内容,而把调用前所有的message立即写入到标的处。

...

$logger->info('some test log message')->flush();

...

定制&扩展/Customization&Extending

Handler Extension Simple - Handler的扩展方式

Put your own MySQLHandler.php in LoggerOne\Handler folder - 将你的扩展文件放置到LoggerOne/Handler目录

namespace LoggerOne\Handler;

class MySQLHandler implements Handler

{

protected $db;

protected $table_name;

public function __construct(string $table_name, object $dbHandle = null)

{

$this->table_name = $table_name;

$this->db = $dbHandle;

}

public function write($messages)

{

$batchData = [];

foreach ($messages as $level => $message) {

$batchData[] = ['level' => $level, 'message' => $message, 'created' => time()];

}

$this->db->insertBatch($this->table_name, $batchData);

}

}

Use MySQLHandler.php - 使用扩展

$logger = new LoggerOne\Logger();

$handler = new LoggerOne\Handler\MysqlHandler($yourLogTableName, $yourDbHandle);

$logger->setHandler($handler);

$logger->info('some test log message');

Formatter Extension Simple - Formatter的扩展方式

The way just like Handler extending - 聪明的你,你可以按你想发灵活的编写你希望的Formatter处理类,过程和Handler扩展流程同理,放到Formatter目录就可以开始使用了。

注意/Notice

If you have not using composer, should remember load all dependency class in your way. - 如果你不使用composer, 请记得用你的方式加载所有必须的依赖类库。

Try to keep your handler write in batches for performace - 如果你做了Handler扩展,为了性能请尽量确保它是批量完成写操作的。

 类似资料: