// +---------------------------------------------------------------------- declare (strict_types = 1); namespace app\log\driver; use think\App; use think\contract\LogHandlerInterface; /** * 本地化调试输出到文件 */ class Monolog implements LogHandlerInterface { /** * 配置参数 * @var array */ protected $config = [ 'time_format' => 'c', 'json_options' => JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES, ]; /** * 日志写入接口 * @access public * @param array $log 日志信息 * @return bool */ public function save(array $log): bool { $info = []; // 日志信息封装 $time = \DateTime::createFromFormat('0.u00 U', microtime())->setTimezone(new \DateTimeZone(date_default_timezone_get()))->format($this->config['time_format']); foreach ($log as $type => $val) { $message = []; foreach ($val as $msg) { $message[] = json_encode(['time' => $time, 'type' => $type, 'msg' => $msg], $this->config['json_options']) ; } $info[$type] = $message; } if ($info) { return $this->write($info); } return true; } /** * 日志写入 * @access protected * @param array $message 日志信息 * @param string $destination 日志文件 * @return bool */ protected function write(array $message): bool { $tcp_log_url = env('TCP_LOG_URL'); $tcp_log_port = intval(env('TCP_LOG_PORT')); $project = env('PROJECT_NAME'); $socket = @fsockopen($tcp_log_url,$tcp_log_port ,$errno, $errstr, 1); if ($socket) { fwrite($socket, json_encode(['message' => $message, 'project' => $project], $this->config['json_options'])); fclose($socket); } // return true; } }