forked from vimeo/ABLincoln
-
Notifications
You must be signed in to change notification settings - Fork 0
/
FileLoggerTrait.php
65 lines (55 loc) · 2.17 KB
/
FileLoggerTrait.php
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
<?php
namespace Vimeo\ABLincoln\Experiments\Logging;
use \Monolog\Logger;
use \Monolog\Handler\StreamHandler;
use \Monolog\Formatter\LineFormatter;
/**
* Give experiments the ability to log to files. Configures a Monolog PSR-3
* file logger and uses it in conjunction with the methods defined in
* PSRLoggerTrait.
*/
trait FileLoggerTrait
{
use PSRLoggerTrait;
// We only want to set up the logger for each experiment once, the first
// time it's instantiated. We do this by maintaining these class variables.
protected static $loggers = [];
protected static $file_paths = [];
/**
* Set up Monolog logger to write to file. _configureLogger() only gets
* called once in AbstractExperiment upon making an experiment assignment
* so the logger will only be initialized a single time when needed.
*/
protected function _configureLogger()
{
// use previously instantiated logger if already set up
if (array_key_exists($this->name, self::$loggers)) {
$this->setLogger(self::$loggers[$this->name]);
return;
}
// if file path not set for experiment default to 'experiment_name.log'
if (!array_key_exists($this->name, self::$file_paths)) {
self::$file_paths[$this->name] = $this->name . '.log';
}
// create new logger with channel=experiment_name and given level/path
$logger = new Logger($this->name);
$handler = new StreamHandler(self::$file_paths[$this->name], $this->log_level);
// format to ignore empty context + extra arrays
$handler->setFormatter(new LineFormatter(null, null, false, true));
$logger->pushHandler($handler);
$this->setLogger($logger);
self::$loggers[$this->name] = $logger;
}
/**
* Set the file path to log to - if not given, file name defaults to
* 'experiment_name.log'. This function should be called in the experiment
* setup() method so that the file path is set before the logger gets
* instantiated.
*
* @param string $path file path to log to
*/
public function setLogFile($path)
{
self::$file_paths[$this->name] = $path;
}
}