使用sqlite的超薄日志编写器

时间:2017-02-06 05:54:35

标签: sqlite logging slim

我已经配置了slim来将日志写入日志文件作为标准方式。但是,当我们想要在给定时间搜索大型和所有日志时,这无效。所以我想将这些日志写入单独的sqlite DB。 我的问题是如何设置日志编写器来编写消息(如Zend framework中所述)?

P S:我知道我可以创建一个PDO对象并使用查询。但我不想改变现有的代码。只是喜欢设置编写器,让框架为我完成工作。

1 个答案:

答案 0 :(得分:1)

我设法按照以下方式执行此操作,

创建sqlite连接

$sqlite = new PDO('sqlite:./logs/log.db');

创建类似于框架的自己的LogWritter

<?php

/**
 * Description of LogWritter
 *
 * @author Ruwantha.Lankathilaka
 */

class LogWritter {

    protected $sqliteConnection;

    public function __construct($connection) {
        $this->sqliteConnection = $connection;
    }

    /**
     * Write function will bypass the slim default LogWriter and will return 
     * last inserted log id which could be used as a reference
     * 
     * @param type $object will get the error message
     * @param type $level will get the error levels of \Slim\Log
     * @return mix if successfully logged will return the last insert id, else 
     * will return false
     */
    public function write($object,$level) {

        //Determine label
        $label = 'DEBUG';
        $message = (string) $object;
        switch ($level) {
            case \Slim\Log::FATAL:
                $label = 'FATAL';
                break;
            case \Slim\Log::ERROR:
                $label = 'ERROR';
                break;
            case \Slim\Log::WARN:
                $label = 'WARN';
                break;
            case \Slim\Log::INFO:
                $label = 'INFO';
                break;
        }

        $sqliteQuery = "INSERT INTO logs (lable,message) VALUES (:lable,:message)";
        $statement = $this->sqliteConnection->prepare($sqliteQuery);
        $result = $statement->execute(array(':lable'=>$label,':message'=>$message));

        if(!empty($result)){
            return $this->sqliteConnection->lastInsertId();
        }else{
            return false;
        }
    }
}

将LogWritter添加到索引

将LogWritter添加到Slim应用程序

$app = new \Slim\Slim(array(
    'log.writer' => $logWriter,
    'log.enabled' => true,
    'log.level' => \Slim\Log::DEBUG,
    'debug' => true
));

现在您可以从应用

获取日志
$retult = $app->log->error('test error');
如果日志失败,

$ result将使插入的日志ID为false

希望这将有助于将来。