首页 > 解决方案 > CodeIgniter 4 将所有日志文件输出到标准输出

问题描述

有没有办法将所有日志文件输出到codeIgniter4中的stdout?

标签: phpcodeigniterlogging

解决方案


首先,前往system\Log\Handlers\FileHandler.php

在函数句柄中,将其添加file_put_contents('php://stdout', $msg); 到第 138 行。

您将开始在标准输出中看到日志。

FileHandler.php 中的函数句柄

    public function handle($level, $message): bool
{
    $filepath = $this->path . 'log-' . date('Y-m-d') . '.' . $this->fileExtension;

    $msg = '';

    if (! is_file($filepath))
    {
        $newfile = true;

        // Only add protection to php files
        if ($this->fileExtension === 'php')
        {
            $msg .= "<?php defined('SYSTEMPATH') || exit('No direct script access allowed'); ?>\n\n";
        }
    }

    if (! $fp = @fopen($filepath, 'ab'))
    {
        return false;
    }

    // Instantiating DateTime with microseconds appended to initial date is needed for proper support of this format
    if (strpos($this->dateFormat, 'u') !== false)
    {
        $microtime_full  = microtime(true);
        $microtime_short = sprintf('%06d', ($microtime_full - floor($microtime_full)) * 1000000);
        $date            = new \DateTime(date('Y-m-d H:i:s.' . $microtime_short, $microtime_full));
        $date            = $date->format($this->dateFormat);
    }
    else
    {
        $date = date($this->dateFormat);
    }

    $msg .= strtoupper($level) . ' - ' . $date . ' --> ' . $message . "\n";
    file_put_contents('php://stdout', $msg);

    flock($fp, LOCK_EX);

    for ($written = 0, $length = strlen($msg); $written < $length; $written += $result)
    {
        if (($result = fwrite($fp, substr($msg, $written))) === false)
        {
            // if we get this far, we'll never see this during travis-ci
            // @codeCoverageIgnoreStart
            break;
            // @codeCoverageIgnoreEnd
        }
    }

    flock($fp, LOCK_UN);
    fclose($fp);

    if (isset($newfile) && $newfile === true)
    {
        chmod($filepath, $this->filePermissions);
    }

    return is_int($result);
}

//--------------------------------------------------------------------

}


推荐阅读