6
5

More than 5 years have passed since last update.

PHPログ出力クラス

Posted at

例によって、オレオレフレームワークの一部

log4php に依存しています。
http://logging.apache.org/log4php/

log4j とか log4net みたいに非同期で書き出しができればいいのに…

Log.class.php
<?php

namespace common;

/**
 * Log
 */
final class Log
{

    /**
     * ログファイルのプリフィックス
     */
    const PREFIX = 'Message: ';

    /**
     * Log4php オブジェクト
     * @var Object Log4phpObject
     */
    static private $_logger = null;

    /**
     * ログ設定を取得する
     * @return array
     */
    static public function getConfig()
    {
        if (!file_exists(LOG_DIR)) {
            if (!mkdir(LOG_DIR, 0775, true)) {
                throw new SystemErrorException(ExceptionCode::SYSTEM_LOGDIR_ERR);
            }
        }
        $objDate = new \DateTime;
        $date = $objDate->format('Ymd');
        $log = LOG_DIR . "/{$date}.log";

        switch (MODE) {
            case DEVELOPPING:
                $level = 'trace';
                break;
            case TEST:
                $level = 'trace';
                break;
            case PRODUCTION:
                $level = 'info';
                break;
        }

        $option = array(
            'appenders' => array(
                'default' => array(
                    'class' => 'LoggerAppenderFile',
                    'layout' => array(
                        'class' => 'LoggerLayoutPattern',
                        'conversionPattern' => '%date{Y-m-d H:i:s,u} %-5level %msg%n'
                    ),
                    'params' => array(
                        'file' => $log,
                        'append' => true
                    )
                )
            ),
            'rootLogger' => array(
                'appenders' => array('default'),
                'level' => $level
            )
        );

        return $option;
    }

    /**
     * ログを書き出す
     * @param string $strLevel
     * @param string $strMessage
     */
    static public function write($strLevel, $strMessage)
    {
        if ((defined('LOGGING') && !LOGGING)) {
            return false;
        }

        self::$_logger = \Logger::configure(self::getConfig());
        self::$_logger = \Logger::getLogger(self::PREFIX);

        $strLevel = strtolower($strLevel);
        if (method_exists(self::$_logger, $strLevel)) {
            call_user_func_array(
                array(self::$_logger, $strLevel)
                , array(str_replace(
                    array(PHP_EOL, "\t")
                    , ""
                    , (is_array($strMessage) || is_object($strMessage)) ?
                        serialize($strMessage) :
                        $strMessage
                ))
            );
        }
    }

    /**
     * ログファイルの一覧を取得する
     * @return array
     */
    static public function getLogFiles()
    {
        $arr = array();
        $resDir = opendir(LOG_DIR);
        while ($fileName = readdir($resDir)) {
            if (".." != $fileName && "." != $fileName) {
                $arr[] = $fileName;
            }
        }
        closedir($resDir);
        sort($arr);
        return $arr;
    }

    /**
     * ログを取得する
     * @param string $file
     * @param integer $line
     * @param string $grep
     * @return array
     */
    static public function getLog($file, $line = 100, $grep = "")
    {
        $res = null;
        $match = null;

        $path = LOG_DIR . "/{$file}";
        $strCommand = "grep '{$grep}' {$path} | tail -n {$line}";
        exec($strCommand, $res);

        $arr = array();
        $resArr = array_reverse($res);
        foreach ($resArr as $log) {
            preg_match('/(TRACE|DEBUG|INFO|WARN|ERROR|FATAL)/i', $log, $match);
            $arr[] = array(
                'level' => (isset($match[0])) ? $match[0] : 'undefined'
                , 'log' => $log
            );
        }
        return $arr;
    }

}

6
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
5