PHP Classes

File: src/PlainFileLogger.php

Recommend this page to a friend!
  Classes of Joseluis Laso   Simple Logger   src/PlainFileLogger.php   Download  
File: src/PlainFileLogger.php
Role: Class source
Content type: text/plain
Description: Class source
Class: Simple Logger
Log messages and view log filtered files
Author: By
Last change: Update of src/PlainFileLogger.php
Date: 1 year ago
Size: 1,189 bytes
 

Contents

Class file image Download
<?php

namespace JLaso\SimpleLogger;

class
PlainFileLogger extends BaseLogger
{
    use
SingletonTrait;
   
   
/**
     * @param string $level
     * @param mixed $data
     */
   
public static function log($level, $data)
    {
       
$instance = static::getInstance();

        if(
$instance->isLevel($level)) {

           
file_put_contents(
               
$instance->logFile,
               
$instance->encodeLine($level, $data),
               
FILE_APPEND
           
);
        }
    }

    public function
encodeLine($level, $data)
    {
       
$data = is_scalar($data) ? (string)$data : json_encode($data);
       
$date = date("Y-m-d h:i:s");

        return
sprintf("*%'*-10s*[@%s]*: %s\n", "[ {$level} ]", $date, $data);
    }

   
/**
     * @param string $line
     * @return array
     */
   
public function decodeLine($line)
    {
        if(
preg_match("/\*\[\s(?<level>\w+)\s\]\*+\[@(?<date>\d{4}\-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2})\]\*:\s(?<text>.*)$/i", $line, $matches)){
            return array(
               
'level' => $matches['level'],
               
'date' => $matches['date'],
               
'text' => $matches['text'],
            );
        }
    }

}