Skip to content

Instantly share code, notes, and snippets.

@Alexander-Pop
Last active June 22, 2022 16:13
Show Gist options
  • Save Alexander-Pop/2c8ea146beba335b0d10d77360eb8a81 to your computer and use it in GitHub Desktop.
Save Alexander-Pop/2c8ea146beba335b0d10d77360eb8a81 to your computer and use it in GitHub Desktop.
PHP - custom Logging
<?php
// $this->logger = new Logger();
// $this->logger->setLogFile('admin.log');
// $this->logger->setTextBefore('user: '.$this->getUser()->getIdentity()->username);
// $this->logger->log($log);
class Logger {
private $logFile = 'logfile.log';
private $path; // log path
private $textBefore = ''; // text can be set in advance, placed before your own logging
function __construct() {
$this->path = dirname(__FILE__) . '/../../log/';
}
/**
* logging to a text file
* @param string $msg logging text
* @param string $fileName File Name
*/
public function log($msg) {
// setlocale(LC_ALL,"US"); https://www.w3schools.com/php/func_string_setlocale.asp
$logBegin = date('Y-m-d H:i:s').' | '.$_SERVER['REMOTE_ADDR'];
file_put_contents($this->path . $this->logFile, $logBegin . $this->textBefore . ' | ' . trim($msg) . "\n", FILE_APPEND);
}
/**
* set extra log file name
* @param [type] $name [description]
*/
public function setLogFile($fileName) {
if (!empty($fileName)) {
$this->logFile = $fileName;
}
}
/**
* allows you to set the text before your own log,
* - for greater purity = eg set who is logged in
* @param [type] $msg [description]
*/
public function setTextBefore($msg) {
$msg = trim($msg);
if (!empty($msg)) {
$this->textBefore = " | " . $msg;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment