laravel模块之日志

前言:laravel模块解读,测试是最好的解读

日志

  • Log
    • Logger.php 实现了psr的日志接口
    • LogManager.php 日志管理者
    • LogServiceProvider.php 日志服务提供者

psr的日志接口提供了常用的方法

1
2
3
4
5
6
7
8
9
10
11
12
interface LoggerInterface
{
public function emergency($message, array $context = array());
public function alert($message, array $context = array());
public function critical($message, array $context = array());
public function error($message, array $context = array());
public function warning($message, array $context = array());
public function notice($message, array $context = array());
public function info($message, array $context = array());
public function debug($message, array $context = array());
public function log($level, $message, array $context = array());
}

Logger类实现了psr接口,同时还得实现写入,通过writeLog()方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/**
* Write a message to the log.
*
* @param string $level
* @param string $message
* @param array $context
* @return void
*/
protected function writeLog($level, $message, $context)
{
$this->fireLogEvent($level, $message = $this->formatMessage($message), $context);

$this->logger->{$level}($message, $context);
}

测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<?php
/**
* Created by PhpStorm.
* User: 小粽子
* Date: 2018/6/6
* Time: 22:13
*/
namespace Tests\Log;

use Illuminate\Log\Logger;
use PHPUnit\Framework\TestCase;
use Mockery as m;

class LoggerTest extends TestCase
{
protected function tearDown()
{
m::close();
}

public function testMethodsPassErrorAdditionsToMonolog()
{
$writer = new Logger($monolog = m::mock('Monolog\Logger'));
$monolog->shouldReceive('error')->once()->with('foo', []);

$writer->error('foo');
}
}