How to create a logfile in php

PhpLogfile

Php Problem Overview


I want to create a logfile for my system to register/log every action they do inside the system. But I have no idea how to do it.

For example, I have this php code that does the login function.

public function hasAccess($username,$password){
	$form = array();
	$form['username'] = $username;
	$form['password'] = $password;
	

	$securityDAO = $this->getDAO('SecurityDAO');
	$result = $securityDAO->hasAccess($form);
	//var_dump($form);
	//var_dump($result);
	if($result[0]['success']=='1'){
		$this->Session->add('user_id', $result[0]['id']);
		//$this->Session->add('username', $result[0]['username']);
		//$this->Session->add('roleid', $result[0]['roleid']);
		return $this->status(0,true,'auth.success',$result);
	}else{
		return $this->status(0,false,'auth.failed',$result);
	}
}

now I want to create a logfile entitled 'the date today', then when that functions is used for loging in, it will write that user has logged in, the same with other functions. But I only want a single file for every day.

Could anyone be kind enough to guide and teach me how I should do my codes?

Php Solutions


Solution 1 - Php

To write to a log file and make a new one each day, you could use date("j.n.Y") as part of the filename.

//Something to write to txt log
$log  = "User: ".$_SERVER['REMOTE_ADDR'].' - '.date("F j, Y, g:i a").PHP_EOL.
        "Attempt: ".($result[0]['success']=='1'?'Success':'Failed').PHP_EOL.
        "User: ".$username.PHP_EOL.
        "-------------------------".PHP_EOL;
//Save string to log, use FILE_APPEND to append.
file_put_contents('./log_'.date("j.n.Y").'.log', $log, FILE_APPEND);

So you would place that within your hasAccess() method.

public function hasAccess($username,$password){
	$form = array();
	$form['username'] = $username;
	$form['password'] = $password;

	$securityDAO = $this->getDAO('SecurityDAO');
	$result = $securityDAO->hasAccess($form);

	//Write action to txt log
	$log  = "User: ".$_SERVER['REMOTE_ADDR'].' - '.date("F j, Y, g:i a").PHP_EOL.
			"Attempt: ".($result[0]['success']=='1'?'Success':'Failed').PHP_EOL.
			"User: ".$username.PHP_EOL.
			"-------------------------".PHP_EOL;
    //-
	file_put_contents('./log_'.date("j.n.Y").'.txt', $log, FILE_APPEND);
	
	if($result[0]['success']=='1'){
		$this->Session->add('user_id', $result[0]['id']);
		//$this->Session->add('username', $result[0]['username']);
		//$this->Session->add('roleid', $result[0]['roleid']);
		return $this->status(0,true,'auth.success',$result);
	}else{
		return $this->status(0,false,'auth.failed',$result);
	}
}

Solution 2 - Php

create a logfile in php, to do it you need to pass data on function and it will create log file for you.

function wh_log($log_msg)
{
	$log_filename = "log";
	if (!file_exists($log_filename)) 
	{
		// create directory/folder uploads.
		mkdir($log_filename, 0777, true);
	}
	$log_file_data = $log_filename.'/log_' . date('d-M-Y') . '.log';
    // if you don't add `FILE_APPEND`, the file will be erased each time you add a log
    file_put_contents($log_file_data, $log_msg . "\n", FILE_APPEND);
} 
// call to function
wh_log("this is my log message");

Solution 3 - Php

Please check with this documentation.

http://php.net/manual/en/function.error-log.php

Example:

<?php
// Send notification through the server log if we can not
// connect to the database.
if (!Ora_Logon($username, $password)) {
    error_log("Oracle database not available!", 0);
}

// Notify administrator by email if we run out of FOO
if (!($foo = allocate_new_foo())) {
    error_log("Big trouble, we're all out of FOOs!", 1,
               "[email protected]");
}

// another way to call error_log():
error_log("You messed up!", 3, "/var/tmp/my-errors.log");
?>

Solution 4 - Php

Agree with the @jon answer. Just added modified the path to create the log directory inside the root

 function wh_log($log_msg) {
    $log_filename = $_SERVER['DOCUMENT_ROOT']."/log";
    if (!file_exists($log_filename))
    {
        // create directory/folder uploads.
        mkdir($log_filename, 0777, true);
    }
    $log_file_data = $log_filename.'/log_' . date('d-M-Y') . '.log';
    file_put_contents($log_file_data, $log_msg . "\n", FILE_APPEND);
}

wh_log('log to file');

just added $_SERVER['DOCUMENT_ROOT']

Solution 5 - Php

Please check this code, it works fine for me.

$data = array('shopid'=>3,'version'=> 1,'value=>1');  //here $data is dummy varaible

error_log(print_r($data,true), 3, $_SERVER['DOCUMENT_ROOT']."/your-file-name.log");

//In $data we can mention the error messege and create the log

Solution 6 - Php

You could use built-in function trigger_error() to trigger user errors/warnings/notices and set_error_handler() to handle them. Inside your error handler you might want to use error_log() or file_put_contents() to store all records on files. To have a single file for every day just use something like sprintf('%s.log', date('Y-m-d')) as filename. And now you should know where to start... :)

Solution 7 - Php

This is my working code. Thanks to Paulo for the links. You create a custom error handler and call the trigger_error function with the correct $errno exception, even if it's not an error. Make sure you can write to the log file directory without administrator access.

<?php
	$logfile_dir = "C:\workspace\logs\\";   // or "/var/log/" for Linux
	$logfile = $logfile_dir . "php_" . date("y-m-d") . ".log";
	$logfile_delete_days = 30;

    function error_handler($errno, $errstr, $errfile, $errline)
    {
        global $logfile_dir, $logfile, $logfile_delete_days;

        if (!(error_reporting() & $errno)) {
            // This error code is not included in error_reporting, so let it fall
            // through to the standard PHP error handler
            return false;
        }

        $filename = basename($errfile);

        switch ($errno) {
            case E_USER_ERROR:
                file_put_contents($logfile, date("y-m-d H:i:s.").gettimeofday()["usec"] . " $filename ($errline): " . "ERROR >> message = [$errno] $errstr\n", FILE_APPEND | LOCK_EX);
                exit(1);
                break;

            case E_USER_WARNING:
                file_put_contents($logfile, date("y-m-d H:i:s.").gettimeofday()["usec"] . " $filename ($errline): " . "WARNING >> message = $errstr\n", FILE_APPEND | LOCK_EX);
                break;

            case E_USER_NOTICE:
                file_put_contents($logfile, date("y-m-d H:i:s.").gettimeofday()["usec"] . " $filename ($errline): " . "NOTICE >> message = $errstr\n", FILE_APPEND | LOCK_EX);
                break;

            default:
                file_put_contents($logfile, date("y-m-d H:i:s.").gettimeofday()["usec"] . " $filename ($errline): " . "UNKNOWN >> message = $errstr\n", FILE_APPEND | LOCK_EX);
                break;
        }

        // delete any files older than 30 days
        $files = glob($logfile_dir . "*");
        $now   = time();

        foreach ($files as $file)
            if (is_file($file))
                if ($now - filemtime($file) >= 60 * 60 * 24 * $logfile_delete_days)
                    unlink($file);

        return true;    // Don't execute PHP internal error handler
    }

	set_error_handler("error_handler");

	trigger_error("testing 1,2,3", E_USER_NOTICE);
?>

Solution 8 - Php

Use below function

// Enable error reporting
ini_set('display_errors', 1);
//Report runtime errors
error_reporting(E_ERROR | E_WARNING | E_PARSE);
//error_reporting(E_ALL & ~E_NOTICE);
// Tell php where your custom php error log is
ini_set('error_log', 'php_error.log');

$dateTime=date("Y-m-d H:i:s");
$ip= $_SERVER['REMOTE_ADDR'];
$errorString="Error occured on time $dateTime by ip $ip";
$php_error_msg.=$errorString;
// Append the error message to the php-error log
//error_log($php_error_msg);
error_log("A custom error has been triggered",1,"email_address","From: email_address");

Above function will create a log in file php_error with proper description and email will be sent.

Solution 9 - Php

For printing log use this function, this will create log file in log folder. Create log folder if its not exists .

logger("Your msg in log ", "Filename you want ", "Data to be log string or array or object");


function logger($logMsg="logger", $filename="logger", $logData=""){		
			$log  = date("j.n.Y h:i:s")." || $logMsg : ".print_r($logData,1).PHP_EOL .     				
			"-------------------------".PHP_EOL;
			file_put_contents('./log/'.$filename.date("j.n.Y").'.log', $log, FILE_APPEND);						
	}

Solution 10 - Php

A custom log function (for php server):

Features:

logs will be hidden (invisible) to public (without doing setting on server)

easy to read logs data

function log_it($info)
{
$filename = $_SERVER['DOCUMENT_ROOT'] . '/' . '1LOGS.php';
$dieCode = "<?php die();?>";
$fileStart = @file_get_contents($filename, false, null, 0, 14);
if ($fileStart) {
    if ($fileStart !== $dieCode)
        file_put_contents($filename, $dieCode . file_get_contents($filename));
} else file_put_contents($filename, $dieCode);

if (is_string($info) || is_int($info) || is_float($info)) $txt = '    ' . $info;
elseif (is_array($info) || is_object($info)) $txt = PHP_EOL . '    ' . print_r($info, true);
else $txt = '    ' . 'Data Type: ' . gettype($info);
file_put_contents(
    $filename,
    PHP_EOL . '>>> ( Date:' . date("Y:m:d H:i:s") . ' )' . $txt,
    FILE_APPEND
);
}

inform if it has room for improvement

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionmaecy mView Question on Stackoverflow
Solution 1 - PhpLawrence CheroneView Answer on Stackoverflow
Solution 2 - PhpJONView Answer on Stackoverflow
Solution 3 - PhpSurabhil SergyView Answer on Stackoverflow
Solution 4 - PhpManishView Answer on Stackoverflow
Solution 5 - PhpPasupathi ThangavelView Answer on Stackoverflow
Solution 6 - Phpuser222758View Answer on Stackoverflow
Solution 7 - PhpxinthoseView Answer on Stackoverflow
Solution 8 - PhpvritikaView Answer on Stackoverflow
Solution 9 - PhpAshwani PanwarView Answer on Stackoverflow
Solution 10 - PhpproseosocView Answer on Stackoverflow