开发者

How do i save logs in php

开发者 https://www.devze.com 2023-01-05 17:31 出处:网络
How do i save logs in PHP? Is there any \"magical\" function available in php for开发者_高级运维 doing so, or any library? Or should i have to fopen file everytime and dump in it? I want to save my lo

How do i save logs in PHP? Is there any "magical" function available in php for开发者_高级运维 doing so, or any library? Or should i have to fopen file everytime and dump in it? I want to save my logs in text file.

Thanks in advance :)


If you do not want to use an own implementation or just do fopen-stuff you cyn use the built in function error_log('string to log'); . This will write the desired string into the error log of your server software.


I wrote a simple class to do this. Maybe you'll find it useful.

class Log
  {
  public function __construct($log_name,$page_name)
    {
    if(!file_exists('/your/directory/'.$log_name)){ $log_name='a_default_log.log'; }
    $this->log_name=$log_name;

    $this->app_id=uniqid();//give each process a unique ID for differentiation
    $this->page_name=$page_name;

    $this->log_file='/your/directory/'.$this->log_name;
    $this->log=fopen($this->log_file,'a');
    }
  public function log_msg($msg)
    {//the action
    $log_line=join(' : ', array( date(DATE_RFC822), $this->page_name, $this->app_id, $msg ) );
    fwrite($this->log, $log_line."\n");
    }
  function __destruct()
    {//makes sure to close the file and write lines when the process ends.
    $this->log_msg("Closing log");
    fclose($this->log);
    }
  }

 $log=new Log('file_name','my_php_page');
 $log->log_msg('fizzy soda : 45 bubbles remaining per cubic centimeter');


If you're not into using the PHP Error Handling Functions (http://www.php.net/manual/en/ref.errorfunc.php) that the other replies have mentioned, here is a deadly simple Logger class that I've used before. Standard warnings apply, as I have not used it in a high risk application or on a heavily trafficked site (though it should be fine).

<?
class Logger
{
  private static function addEntry($str)
  {
    $handle = fopen('./services.log', 'a');
    fwrite($handle, sprintf("%s %s\n", date('c'), $str));
    fclose($handle);
  }

  public static function warn($str)
  {
    self::addEntry("WARNING $str");
  }

  public static function info($str)
  {
    self::addEntry("INFO $str");
  }

  public static function debug($str)
  {
    self::addEntry("DEBUG $str");
  }
}
?>

Then you can use it like this:

<?php
require('Logger.php');
Logger::debug('test');
Logger::warn('bwah');
Logger::info('omg');
?>

Very simple to add more functions (like Logger::error()), store the file handler so you don't have to keep re-opening it every time you want to log something (ie., store the $handle variable in a private static class scope variable, and have addEntry() check to see if it's set whenever it's run and run fopen() if it isn't), or change the format of how you're logging.

Cheers.


All depends what you're trying to log. By default you will have an error_log already which is essentially a plain text file. If you're talking about logging events within your code for debugging or tracking activity within a script then you will need to write your own log handler for this but this is very simple. As another poster says you can push content to the error log using the error_log() function but this would make for some very unmanageable log files imv.


The last answer is from 2010 so it needs a breath of fresh air. I'm sharing with you my php class that I use in my programs. I took similar approach to @Sam-Bisbee's answer above, so it's easy to add new functionalities and functions, but I also made it more flexible to use in different programs/scripts.

I put my class in Logg.php file, you can do it as well.

My class

<?php
class Logg
{
    public static $fileName = 'new_log';
    public static $filePath = '/';
    public static $fileType = '.log';
    
    public static function addInfo($logMsg, $fName = null, $fPath = null)
    {
        $fName = $fName ?: self::$fileName;
        $fPath = $fPath ?: self::$filePath;
        self::addData($logMsg, $fName, $fPath, ' |  INFO   |');
    }
    
    public static function addWarn($logMsg, $fName = null, $fPath = null)
    {
        $fName = $fName ?: self::$fileName;
        $fPath = $fPath ?: self::$filePath;
        self::addData($logMsg, $fName, $fPath, ' | WARNING |');
    }
    
    public static function addErr($logMsg, $fName = null, $fPath = null)
    {
        $fName = $fName ?: self::$fileName;
        $fPath = $fPath ?: self::$filePath;
        self::addData($logMsg, $fName, $fPath, ' |  ERROR  |');
    }
    
    public static function addConf($logMsg, $fName = null, $fPath = null)
    {
        $fName = $fName ?: self::$fileName;
        $fPath = $fPath ?: self::$filePath;
        self::addData($logMsg, $fName, $fPath, ' | CONFIG  |');
    }
    
    private static function addData($logMsg, $fName, $fPath, $type)
    {
        $handle = fopen($fPath . $fName . self::$fileType, 'a');
        
        if (gettype($logMsg) == 'array') {
            if (count($logMsg)%2 == 0) {
                $logText = '';
                for ($i = 0; $i < count($logMsg); $i+=2) {
                    $logText .= str_pad($logMsg[$i], $logMsg[$i+1], " ", STR_PAD_BOTH).'|';
                }
                fwrite($handle, sprintf("| %s%s", date("Y-m-d H:i:s"), $type.$logText.PHP_EOL));
            } else {
                throw new Exception('Wrong arguments for Array-type log.');
            }
        } else {
            fwrite($handle, sprintf("| %s%s", date("Y-m-d H:i:s"), $type.' '.$logMsg.PHP_EOL));
        }
        
        fclose($handle);
    }
    
    public static function addLine($lines = 1, $fName = null, $fPath = null)
    {
        $fName = $fName ?: self::$fileName;
        $fPath = $fPath ?: self::$filePath;
        $handle = fopen($fPath . $fName . self::$fileType, 'a');
        fwrite($handle, str_repeat(PHP_EOL, $lines));
        fclose($handle);
    }
}
?>

Usage examples

Including class - specifying logs file name and path:

<?php 
require '/Logg.php';

//specifying logs file name and path - best do this right after include
Logg::$fileName = 'ExampleName_'.date("Y_m_d");             //if not specified, default value = 'new_log'
Logg::$filePath = 'C:/Apache24/htdocs/public_html/logs/';   //if not specified, default value = '/'

You can change this values once again later on in your program if you want to.

Simple usage:

//Logging simple messages
Logg::addInfo("FooBar");            //sample information log message
Logg::addWarn("Sample warning");    //sample warning log message
Logg::addErr ("Sample error");      //sample error log message
Logg::addConf("Sample config log"); //sample config change log message

//Adding empty lines
Logg::addLine();                            //adds empty line
Logg::addInfo("Log after empty line");      //some log
Logg::addLine(3);                           //adds 3 lines instead of one
Logg::addInfo("Log after 3 empty lines");   //some log

You can also use an Array (recommended) instead of String as your "Log Message", like on examples below. It will make your log messages formatted to the specified length in order to make them more readable:

Logg::addLine();
Logg::addInfo(['Goo', 5]);          //logs 'Goo' as char of length 5
Logg::addInfo(['', 10, 'Goo', 5]);  //logs empty space of length 10 and a 'Goo' of length 5 after that
Logg::addInfo(['Foo',       10 , 'Bar', 5, 'Sample message with some length formatted to 75 chars',              75]); //more examples
Logg::addInfo(['FooBar',    10 , 'Baz', 5, 'Another sample message with different length formatted to 75 chars', 75]);
Logg::addLine();
Logg::addInfo(['Different message of length 65 - trying to format it to length 50', 50]);   //in this case the message will keep it initial length so we wont be loosing any of the information we are logging

Execution of the code above, created a file "ExampleName_2021_08_31.log" in the specified file path with content:

| 2021-08-31 11:28:52 |  INFO   | FooBar
| 2021-08-31 11:28:52 | WARNING | Sample warning
| 2021-08-31 11:28:52 |  ERROR  | Sample error
| 2021-08-31 11:28:52 | CONFIG  | Sample config log

| 2021-08-31 11:28:52 |  INFO   | Log after empty line



| 2021-08-31 11:28:52 |  INFO   | Log after 3 empty lines

| 2021-08-31 11:28:52 |  INFO   | Goo |
| 2021-08-31 11:28:52 |  INFO   |          | Goo |
| 2021-08-31 11:28:52 |  INFO   |   Foo    | Bar |           Sample message with some length formatted to 75 chars           |
| 2021-08-31 11:28:52 |  INFO   |  FooBar  | Baz |    Another sample message with different length formatted to 75 chars     |

| 2021-08-31 11:28:52 |  INFO   |Different message of length 65 - trying to format it to length 50|


Changing file type

You can change to different file types by changing the $fileType property of my Logg class. The default file type is ".log".

For example:

//changing file type, can be put after class include
Logg::$fileType = ".txt";

//logging some example messages
Logg::addInfo("Log message now in .txt file");
Logg::addWarn("Everything will be saved to this file from now on!");

Now the "ExampleName_2021_08_31.txt" file was created with content:

| 2021-08-31 09:35:20 |  INFO   | Log message now in .txt file
| 2021-08-31 09:35:20 | WARNING | Everything will be saved to this file from now on!

Additional function parameters

Every public "add" function has two additional parameters - file name and file path. Specifying this parameters will temporarily override the Logg::$fileName and Logg::$filePath class variables values specified earlier. It can be usefull if you want to log some information into file with different name or file in different path, but you don't want to change the file path or file name for every log used in your program.

Usage:

//Additional parameters
Logg::addErr("New error log");                                                          //no additional parameters - uses filename and path from "Logg::$fileName" and "Logg::$filePath"
Logg::addErr("New error log in different file", "<file name>");                         //one additional parameter - uses provided filename instead of "Logg::$fileName"
Logg::addErr("New error log in different file and path", '<file name>', '<file path>'); //two additional parameters - uses provided filename and path instead of "Logg::$fileName" and "Logg::$filePath"

Example:

//this:
{
    //logging information to different file in different path
    Logg::addInfo(['Some info', 15], 'AnotherFileName', '/some/different/path/');
}
//is equal to this:
{
    //changing filename and path
    Logg::$fileName = 'AnotherFileName';
    Logg::$filePath = '/some/different/path/';

    //logging information
    Logg::addInfo(['Some info', 15]);

    //changing filename and path back to its original values
    Logg::$fileName = 'ExampleName_'.date("Y_m_d");
    Logg::$filePath = 'C:/Apache24/htdocs/public_html/logs/';
}

I'm waiting for your comments and suggestions. Have a good day.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号