A Simple Logging Class For PHP

Related tags

Logging KLogger
Overview

KLogger: Simple Logging for PHP

A project written by Kenny Katzgrau and Dan Horrigan.

About

KLogger is an easy-to-use PSR-3 compliant logging class for PHP. It isn't naive about file permissions (which is expected). It was meant to be a class that you could quickly include into a project and have working right away.

If you need a logger that supports PHP < 5.3, see past releases for KLogger versions < 1.0.0.

Installation

Composer

From the Command Line:

composer require katzgrau/klogger:dev-master

In your composer.json:

{
    "require": {
        "katzgrau/klogger": "dev-master"
    }
}

Basic Usage

<?php

require 'vendor/autoload.php';

$users = [
    [
        'name' => 'Kenny Katzgrau',
        'username' => 'katzgrau',
    ],
    [
        'name' => 'Dan Horrigan',
        'username' => 'dhrrgn',
    ],
];

$logger = new Katzgrau\KLogger\Logger(__DIR__.'/logs');
$logger->info('Returned a million search results');
$logger->error('Oh dear.');
$logger->debug('Got these users from the Database.', $users);

Output

[2014-03-20 3:35:43.762437] [INFO] Returned a million search results
[2014-03-20 3:35:43.762578] [ERROR] Oh dear.
[2014-03-20 3:35:43.762795] [DEBUG] Got these users from the Database.
    0: array(
        'name' => 'Kenny Katzgrau',
        'username' => 'katzgrau',
    )
    1: array(
        'name' => 'Dan Horrigan',
        'username' => 'dhrrgn',
    )

PSR-3 Compliant

KLogger is PSR-3 compliant. This means it implements the Psr\Log\LoggerInterface.

See Here for the interface definition.

Setting the Log Level Threshold

You can use the Psr\Log\LogLevel constants to set Log Level Threshold, so that any messages below that level, will not be logged.

Default Level

The default level is DEBUG, which means everything will be logged.

Available Levels

<?php
use Psr\Log\LogLevel;

// These are in order of highest priority to lowest.
LogLevel::EMERGENCY;
LogLevel::ALERT;
LogLevel::CRITICAL;
LogLevel::ERROR;
LogLevel::WARNING;
LogLevel::NOTICE;
LogLevel::INFO;
LogLevel::DEBUG;

Example

<?php
// The 
$logger = new Katzgrau\KLogger\Logger('/var/log/', Psr\Log\LogLevel::WARNING);
$logger->error('Uh Oh!'); // Will be logged
$logger->info('Something Happened Here'); // Will be NOT logged

Additional Options

KLogger supports additional options via third parameter in the constructor:

<?php
// Example
$logger = new Katzgrau\KLogger\Logger('/var/log/', Psr\Log\LogLevel::WARNING, array (
    'extension' => 'log', // changes the log file extension
));

Here's the full list:

Option Default Description
dateFormat 'Y-m-d G:i:s.u' The format of the date in the start of the log lone (php formatted)
extension 'txt' The log file extension
filename [prefix][date].[extension] Set the filename for the log file. This overrides the prefix and extention options.
flushFrequency false (disabled) How many lines to flush the output buffer after
prefix 'log_' The log file prefix
logFormat false Format of log entries
appendContext true When false, don't append context to log entries

Log Formatting

The logFormat option lets you define what each line should look like and can contain parameters representing the date, message, etc.

When a string is provided, it will be parsed for variables wrapped in braces ({ and }) and replace them with the appropriate value:

Parameter Description
date Current date (uses dateFormat option)
level The PSR log level
level-padding The whitespace needed to make this log level line up visually with other log levels in the log file
priority Integer value for log level (see $logLevels)
message The message being logged
context JSON-encoded context

Tab-separated

Same as default format but separates parts with tabs rather than spaces:

$logFormat = "[{date}]\t[{level}]\t{message}";

Custom variables and static text

Inject custom content into log messages:

$logFormat = "[{date}] [$var] StaticText {message}";

JSON

To output pure JSON, set appendContext to false and provide something like the below as the value of the logFormat option:

$logFormat = json_encode([
    'datetime' => '{date}',
    'logLevel' => '{level}',
    'message'  => '{message}',
    'context'  => '{context}',
]);

The output will look like:

{"datetime":"2015-04-16 10:28:41.186728","logLevel":"INFO","message":"Message content","context":"{"1":"foo","2":"bar"}"}

Pretty Formatting with Level Padding

For the obsessive compulsive

$logFormat = "[{date}] [{level}]{level-padding} {message}";

... or ...

$logFormat = "[{date}] [{level}{level-padding}] {message}";

Why use KLogger?

Why not? Just drop it in and go. If it saves you time and does what you need, go for it! Take a line from the book of our C-code fathers: "build upon the work of others".

Who uses KLogger?

Klogger has been used in projects at:

* The University of Iowa
* The University of Laverne
* The New Jersey Institute of Technology
* Middlesex Hospital in NJ

Additionally, it's been used in numerous projects, both commercial and personal.

Special Thanks

Special thanks to all contributors:

License

The MIT License

Copyright (c) 2008-2015 Kenny Katzgrau [email protected]

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Comments
  • Option to tabulate log lines

    Option to tabulate log lines

    I thought my log file would be more readable if all messages are indented with the same depth, no matter what $level. Example:

    original

    [2015-08-31 19:02:49.181617] [info] dumdidum
    [2015-08-31 19:02:49.182616] [emergency] mist
    

    nicer

    [2015-08-31 19:03:27.268881] [info]      dumdidum
    [2015-08-31 19:03:27.268881] [emergency] mist
    

    So I changed line 553 (method formatMessage()) like this (original line is the commented one):

            //$message = "[{$this->getTimestamp()}] [{$level}] {$message}";
            $message = "[{$this->getTimestamp()}] [{$level}] ".str_repeat(' ',(9-strlen($level)))."{$message}";
    

    Maybe it's helpful for someone.

    opened by webbird 18
  • Suggest to allow output to screen / stdout.

    Suggest to allow output to screen / stdout.

    Setting the log dir to /dev/tty does not work, since you append the filename. But changing it hardcoded in the file, to output to /dev/tty prints the log nicely to the screen.

    Perhaps make a check for this condition and not try to append a filename and check for its exists status?

    opened by DannyBen 11
  • Conversion deprecation warning with PHP 8.1

    Conversion deprecation warning with PHP 8.1

    When upgrading my project to PHP 8.1, I get tons of these warnings:

    Deprecated: Implicit conversion from float 1641216285.352105 to int loses precision in C:\MyProject\vendor\katzgrau\klogger\src\Logger.php on line 308

    Looking at the source code, this is the excerpt:

    296: /**
    297:  * Gets the correctly formatted Date/Time for the log entry.
    299:  *
    299:  * PHP DateTime is dump, and you have to resort to trickery to get microseconds
    300:  * to work correctly, so here it is.
    301:  *
    302:  * @return string
    303:  */
    304: private function getTimestamp()
    305: {
    306:     $originalTime = microtime(true);
    307:     $micro = sprintf("%06d", ($originalTime - floor($originalTime)) * 1000000);
    308:     $date = new DateTime(date('Y-m-d H:i:s.'.$micro, $originalTime));
    309:
    310:     return $date->format($this->options['dateFormat']);
    311: }
    

    So the error occurs in this line 308:

    $date = new DateTime(date('Y-m-d H:i:s.'.$micro, $originalTime));
    

    My question

    Are you planning to update your library to work without the warning?

    If not, any other suggestions on how to resolve this by myself?


    Update 1

    I do think the issue is that in line 306, the call to microtime() returns a float, which in turn is passed as the $timestamp parameter in line 308 to the date() call which required the $timestamp parameter to be an int.

    In my tests, the deprecation warning went away, when explicitly casting to int, e.g.:

    $date = new DateTime(date('Y-m-d H:i:s.'.$micro, (int)$originalTime));
    

    Here, I casted $originalTime to int.

    See e.g. this blog article for more details.

    opened by UweKeim 8
  • Set some Properties and Methods from private to protected

    Set some Properties and Methods from private to protected

    Hello Guys,

    at first, thanks for this simple Class! But I have some problems with it.

    I would like to extend the Class for Read the file. But some Properties and Methods are on private, so I can not use it on my child class.

    Example: $fileHandle & $logFilePath

    Thanks. Greetz Sysix

    opened by Sysix 6
  • DateTime Fatal Error with PHP 5.6.11

    DateTime Fatal Error with PHP 5.6.11

    I get this error when I try to use Klogger: " PHP Fatal error: Uncaught exception 'Exception' with message 'DateTime::__construct(): It is not safe to rely on the system's timezone settings. You are required to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected the timezone 'UTC' for now, but please set date.timezone to select your timezone. in vendor/katzgrau/klogger/src/Logger.php:307 "

    opened by teliov 6
  • Allow newer versions of psr/log

    Allow newer versions of psr/log

    PSR/log is currently at 1.0.2, but this package explicitly depends on 1.0.0, preventing any newer versions form being pulled in. This PR opens up the versioning to allow any 1.0 version of psr/log to be used.

    opened by rbayliss 5
  • Custom callback

    Custom callback

    Does anyone think the addition of custom callback feature would be of value? It could be passed the Logger object and/or Logger::lastLine and would open a lot of possibilities, for example:

    • Send an email if the level is notice or higher
    • Log emergency issues to a separate file
    • Mirror logs to a database
    • Delete/archive log files on a schedule

    The developer would have to write the implementations themself (e.g. database connections) but custom callbacks might be a good way to allow advanced logging features without affecting how easy-to-use the basic functions are.

    If people think this is of value I'll look into this feature.

    opened by richjenks 5
  • Fix cs

    Fix cs

    Also:

    • Added .gitattributes to perform LF normalization for text files and exclude tests from arhives.
    • Renamed phpunit.xml to phpunit.xml.dist and added phpunit.xml to .gitignore
    opened by ghost 5
  • Extension, filename and prefix not applying

    Extension, filename and prefix not applying

    Hello,

    for some reason, the extension, filename and prefix settings do not apply.

    $ composer clearcache
    $ mkdir test
    $ cd test
    $ composer require katzgrau/klogger
    $ touch index.php
    

    In index.php:

    <?php
    
    require 'vendor/autoload.php';
    
    $logger = new Katzgrau\KLogger\Logger(__DIR__, Psr\Log\LogLevel::DEBUG, array (
        'extension' => 'log'
    ));
    $logger->error('error content');
    

    It creates the log file, but in standard format log_2015-04-09.txt. Any explanation? Is it linked to my environment, so that I am the only one to have this issue?

    opened by tleb 5
  • Add support for logging the hostname and appname

    Add support for logging the hostname and appname

    Hi there,

    To better support logging for servers that have several apps running on them or to allow for a log collector to easily parse the different hostnames that are pushing logs, I've added support for this.

    Hostname and appname can be set in the $options array. Default is left to null.

    opened by onno-vos-dev 5
  • Some improvements

    Some improvements

    Hi,

    I really like your class, but anyway, I've made some additions you may like to pull. :)

    • added optional $args param that is dumped to the log to allow easy var dumps
    • log line includes calling class, function name, filename, and code line

    Example log line:

    2011-10-20 18:50:50 - DEBUG --> [addFile()] language file does not exist: [ I18n.php:169 ]

    Example with $args:

    2011-10-20 18:51:53 - DEBUG --> [init()] language files to search for: [ I18n.php:108 ] Array ( [0] => DE [1] => EN )

    opened by webbird 5
  • Set log file default permissions

    Set log file default permissions

    This should fix problem with log file permissions mentioned here https://github.com/katzgrau/KLogger/issues/94

    I had problem with logging from user frontend (run by apache user) and cli (run by different unix user).

    Mine solution checks file existence first and if it is writable, if not new file is created and chmoded to default permission (same as for log directory)

    opened by xomax 0
  • log method not PSR-3 compliant

    log method not PSR-3 compliant

    The PSR-3 specification states:

    A ninth method, log, accepts a log level as the first argument. Calling this method with one of the log level constants MUST have the same result as calling the level-specific method. Calling this method with a level not defined by this specification MUST throw a Psr\Log\InvalidArgumentException if the implementation does not know about the level. Users SHOULD NOT use a custom level without knowing for sure the current implementation supports it.

    Currently calling log with any level not specified in PSR-3 will write the log regardless of the current log threshold and give an undefined index notice.

    opened by gian-hancock 1
  • writing arrays

    writing arrays

    From the first example it appears arrays should be written to log. When I try to include an array, I get

    PHP Notice: Array to string conversion in /data/Data_Cleaning/CvR/wip_plib/vendor/katzgrau/klogger/src/Logger.php on line 285

    log shows

    [2019-02-27 10:30:01.878930] [info] Array [2019-02-27 10:30:01.879091] [info] /data/Data_Cleaning/CvR/wip_pbin/file_cleaning/rename/NEX* [2019-02-27 10:30:01.879139] [info] Found: nex [2019-02-27 10:30:01.879228] [debug] Array [2019-02-27 10:30:01.879385] [info] NEX_IMR_01012019 renamed nex_wk01_01012019.txt [2019-02-27 10:30:01.879467] [info] NEX_IMR_01022019 renamed nex_wk01_01022019.txt [2019-02-27 10:30:01.879591] [info] NEX_IMR_01032019 renamed nex_wk01_01032019.txt [2019-02-27 10:30:01.879656] [info] NEX_IMR_01042019 renamed nex_wk01_01042019.txt [2019-02-27 10:30:01.879723] [info] NEX_IMR_01052019 renamed nex_wk01_01052019.txt [2019-02-27 10:30:01.879789] [info] NEX_IMR_01062019 renamed nex_wk01_01062019.txt [2019-02-27 10:30:01.879880] [info] NEX_IMR_01072019 renamed nex_wk01_01072019.txt [2019-02-27 10:30:01.879951] [info] NEX_IMR_01082019 renamed nex_wk02_01082019.txt [2019-02-27 10:30:01.880014] [info] NEX_IMR_01092019 renamed nex_wk02_01092019.txt

    Am I missing something?

    opened by cgapperi 1
  • Bad premissions for file after create

    Bad premissions for file after create

    In class we can see

        /**
         * Octal notation for default permissions of the log file
         * @var integer
         */
        private $defaultPermissions = 0777;
    

    But, it only set permissions for path, not for created log file.

    opened by wacki4 1
High-performance API performing logging for PHP applications into files or SysLog

Logging API Table of contents: About Configuration Binding Points Logging Installation Unit Tests Reference Guide Specifications How Are Log Lines For

Lucian Gabriel Popescu 0 Jan 9, 2022
🐣 Backend-Logging aller Aktionen im Backend

Addon BE_Logger - Backend-Logging Mit dem Addon be_logger können die Backend-Zugriffe aller Benutzer in einer Logging-Tabelle ausgegeben werden. Es gi

Friends Of REDAXO 14 Sep 12, 2022
This package is for centralized logging of multiple Laravel application into one connection.

Laralogs This package is for centralized logging of multiple Laravel application into one connection. Installation You can install the package via com

Remon 4 Apr 26, 2022
RadPHP Logging Component

RadPHP Logging Component The Logging library provides multiple logging adapters using a simple interface. With the Logger class it is possible to send

RadPHP 9 Sep 8, 2021
Monolog logging support for Slim Framework

Monolog Logging for Slim Framework This repository adds support for logging to Monolog to the Slim Framework. Installation MonologWriter takes an arra

null 113 Dec 18, 2022
Slim-Logger - A stand-alone logger class for use with the Slim Framework

Slim-Logger - A stand-alone logger class for use with the Slim Framework

Josh Lockhart 41 Mar 12, 2022
Simple PHP Logger. Composer package

Basic PHP Logger ?? Simple logger. Composer package.

null 1 Jan 28, 2022
AcLog is a simple, zero-dependency PHP package to log activity to files

AcLog is a simple, zero-dependency PHP package to log activity to files. This is not meant for logging errors, this is can be used for logging c

null 2 Sep 9, 2022
A simple database logger for all outgoing emails sent by Laravel website.

Laravel Email Database Log A simple database logger for all outgoing emails sent by Laravel website.

Shvets Group 136 Jan 4, 2023
A simple and beautiful laravel log reader

Laravel Log Reader A simple and beautiful laravel log reader Documentation Get full documentation of Laravel Log Reader Other Packages Laravel H - A h

Md.Harun-Ur-Rashid 356 Dec 30, 2022
temperature-pi: a simple Raspberry Pi based temperature logger using a DS18B20 1-Wire digital temperature sensor, & a local sqlite database

temperature-pi temperature-pi is a simple Raspberry Pi based temperature logger using a DS18B20 1-Wire digital temperature sensor, & a local sqlite da

Ronan Guilloux 23 Dec 27, 2020
123Solar is a set of PHP/JS files that make a web logger to monitor your photovoltaic inverter(s)

123Solar is a set of PHP/JS files that make a web logger to monitor your photovoltaic inverter(s). It just need a web server and PHP, no databases are even needed. The philosophy is: To keep it simple, fast, with a low foot print to run on cheap and low powered devices.

null 30 Jan 6, 2023
An effective,fast,stable log extension for PHP

SeasLog An effective,fast,stable log extension for PHP @author Chitao.Gao [[email protected]] Documentation On php.net 中文文档 Synopsis Why use seaslog What

Neeke Gao 76 Sep 28, 2022
ChromePhp - a PHP library for the Chrome Logger Google Chrome extension

ChromePhp - a PHP library for the Chrome Logger Google Chrome extension

Craig Campbell 1.4k Dec 30, 2022
PHP Router class - A simple Rails inspired PHP router class.

PHP Router class A simple Rails inspired PHP router class. Usage of different HTTP Methods REST / Resourceful routing Reversed routing using named rou

Danny van Kooten 565 Jan 8, 2023
PHP logging library that is highly extendable and simple to use.

Analog - Minimal PHP logging library Copyright: (c) 2012-Present Johnny Broadway License: MIT A minimal PHP logging package based on the idea of using

Aband*nthecar 331 Dec 21, 2022
Simple blog concept with features such authentication (creating accounts, logging in) and commenting.

Simple blog concept with features such authentication (creating accounts, logging in) and commenting. Styling done with tailwindcss and inline javascript is provided by alpineJS.

null 1 Oct 26, 2021
A simple Laravel event log package for easy model based logging.

Karacraft Logman A simple Model Event Logging Package Usage Installation composer require karacraft/logman Migrate php artisan migrate Publish php a

Karacraft 0 Dec 28, 2021
😎 Tracy: the addictive tool to ease debugging PHP code for cool developers. Friendly design, logging, profiler, advanced features like debugging AJAX calls or CLI support. You will love it.

Tracy - PHP debugger Introduction Tracy library is a useful helper for everyday PHP programmers. It helps you to: quickly detect and correct errors lo

Nette Foundation 1.6k Dec 23, 2022
High-performance API performing logging for PHP applications into files or SysLog

Logging API Table of contents: About Configuration Binding Points Logging Installation Unit Tests Reference Guide Specifications How Are Log Lines For

Lucian Gabriel Popescu 0 Jan 9, 2022