Sends your logs to files, sockets, inboxes, databases and various web services

Related tags

Logging monolog
Overview

Monolog - Logging for PHP Continuous Integration

Total Downloads Latest Stable Version

Monolog sends your logs to files, sockets, inboxes, databases and various web services. See the complete list of handlers below. Special handlers allow you to build advanced logging strategies.

This library implements the PSR-3 interface that you can type-hint against in your own libraries to keep a maximum of interoperability. You can also use it in your applications to make sure you can always use another compatible logger at a later time. As of 1.11.0 Monolog public APIs will also accept PSR-3 log levels. Internally Monolog still uses its own level scheme since it predates PSR-3.

Installation

Install the latest version with

$ composer require monolog/monolog

Basic Usage

<?php

use Monolog\Logger;
use Monolog\Handler\StreamHandler;

// create a log channel
$log = new Logger('name');
$log->pushHandler(new StreamHandler('path/to/your.log', Logger::WARNING));

// add records to the log
$log->warning('Foo');
$log->error('Bar');

Documentation

Support Monolog Financially

Get supported Monolog and help fund the project with the Tidelift Subscription or via GitHub sponsorship.

Tidelift delivers commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use.

Third Party Packages

Third party handlers, formatters and processors are listed in the wiki. You can also add your own there if you publish one.

About

Requirements

  • Monolog ^2.0 works with PHP 7.2 or above, use Monolog ^1.25 for PHP 5.3+ support.

Support

Monolog 1.x support is somewhat limited at this point and only important fixes will be done. You should migrate to Monolog 2 where possible to benefit from all the latest features and fixes.

Submitting bugs and feature requests

Bugs and feature request are tracked on GitHub

Framework Integrations

Author

Jordi Boggiano - [email protected] - http://twitter.com/seldaek
See also the list of contributors who participated in this project.

License

Monolog is licensed under the MIT License - see the LICENSE file for details

Acknowledgements

This library is heavily inspired by Python's Logbook library, although most concepts have been adjusted to fit to the PHP world.

Comments
  • Add new Slack handlers using Slackbot and webhooks

    Add new Slack handlers using Slackbot and webhooks

    See https://github.com/Seldaek/monolog/issues/743#issuecomment-242994019

    This is keeping the previous SlackHandler, but extracts the message formatting logic and introduces two new Slack handlers:

    • SlackbotHandler - this is the simplest way to log to Slack and most people could use that. It doesn't allow fancy formatting, but has autolinking and the simplest configuration with two clicks in the Slack settings and getting a token.
    • SlackWebhookHandler - This is a bit more advanced as it allows for the same formatting and adding attachements as the SlackHandler, but it uses the Slack Webhooks which are quite easier to set up than the OAuth API. The minimum it requires is a webhook URL which is a retrievable with about two clicks in the Slack settings. Even the channel is optional as it could be configured in the integration.

    This is probably not the leanest way to implement what we've discussed in https://github.com/Seldaek/monolog/issues/743, but after working at this I believe this is the simplest and the right approach.

    While we could implement everything in one handler the API would become horrible and it would be harder to understand from users. Providing choice with simple to use separate classes is better IMHO. Apart from this the SlackHandler extends the SocketHandler and the webhooks and the Slackbot wouldn't work nicely with that.

    What do you think?

    @Seldaek @gkedzierski @Gummibeer @nisbeti


    • [x] Extracting Slack formatting logic in SlackRecord
    • [x] SlackbotHandler
    • [x] SlackWebhookHandler
    • [x] Refactor SlackHandler using the new SlackRecord
    • [x] Add new handlers to the docs
    • [x] Unit tests of SlackRecord
    • [x] Unit tests for SlackbotHandler
    • [x] Unit tests for SlackWebhookHandler
    • [x] Update unit tests for SlackHandler
    Feature 
    opened by hkdobrev 31
  • Added an handler for NewRelic

    Added an handler for NewRelic

    • implemented a test which verifies that the fallback handler handles records when the NewRelic PHP extension is not installes
    • implemented the actual handler

    There are a few problems that Id like to discuss:

    • how to properly test it? The NewRelic extension is proprietary, so you cannot obtain it for free
    • do we need the fallback handler? It would be super useful for local development, since developers dont usually get the NR extension on their local machines - at the same time I recognize that there is no fallback handler for other handlers (ie Graylog2)
    • currently, that test seems a little bit too weak to be called a "test"
    • if we use function_exists we could add some more meaningful tests, but at the same time extension_loaded is more right
    opened by odino 30
  • Suppress warnings on date_default_timezone_get()

    Suppress warnings on date_default_timezone_get()

    Unfortunately date_default_timezone_get() still triggers the classic timezone warning, and there is no other way to determine if a timezone has been set.

    While one can ensure their projects always perform a date_default_timezone_set() there are still common places where monolog can be imported without direct user control over setting default timezones.

    In my particular case, including monolog in a Symfony2 composer project with the stock Symfony2 post-install-cmd and post-update-cmd chain causes failures at the end of an install/update cycle. I believe it's composer in this case that translates all triggered warnings/errors into exceptions which causes whatever process that is running to fail.

    Therefore I propose we just suppress the warnings from date_default_timezone_set() for now.

    In the future timezone management should maybe be mildly refactored to be injectable and default to UTC, but this will eliminate

    opened by dcousineau 29
  • Added a new ResettableInterface and implemented it where possible.

    Added a new ResettableInterface and implemented it where possible.

    Added a new ResetableInterface and implemented it where possible.

    When one use Monolog in a long process like an AMQP worker with a FingersCrossedHandler or BufferHandler there is a drawback: as soon as there is an AMQP message that generate a log >= error (for example), all next AMQP messages will output logs, even if theses messages don't generate log where level >= error.

    In the same context there is a drawback for processor that add an UUID to the logs. The UUID should change for each AMQP messages.


    This patch address this issue with a new interface: ResettableInterface interface. Side note: reset(), flush(), clear(), are already used in Monolog. So basically, one can use the reset() on the Logger and on some Handlers / Processors.

    It's especially useful for

    • the FingersCrossedHandler: it close() the buffer, then it clear() the buffer.
    • the BufferHandler: it flush() the buf
    Feature 
    opened by lyrixx 28
  • 2.0 Code cleanups / tasks

    2.0 Code cleanups / tasks

    • [x] ~~Clean up arg orders of handlers that have had added args pushed at the end (after bubbling etc), maybe group them in an $options array or parameter objects? Needs RFC. Check #801 too about fluent setters~~
    • [x] add scalar hints and return type hints where relevant ("only" handlers left to go through)
    • [x] ~~figure out how to handle network timeouts globally somehow, see #733~~
    • [x] Add a close() method on the Logger to close all its handlers? What about resetting FingersCrossedHandler?
    • [x] Define which php version should be supported (=> 7.1)
    • [x] Add a timezone arg to Logger instead of the static timezone?
    • [x] Turn static::getLevelName into static::
    • [x] Set Monolog\Logger::API = 2 to allow users to adjust
    • [x] Remove non PSR-3 methods to add record
    • [x] Remove processor/formatter setters and getters from the HandlerInterface
    • [x] Remove logstash V0 support or at least make V1 default
    • [x] Remove legacy GELF handler support, c.f. #326
    • [x] Remove datetime TODO in loggly handler
    • [x] Move Monolog\TestCase to src/, see https://github.com/Seldaek/monolog/pull/356#issuecomment-40899938
    • [x] ~~Split handlers w/ dependencies into packages i.e. http://php-and-symfony.matthiasnoback.nl/2014/04/theres-no-such-thing-as-an-optional-dependency/~~
    • [x] ~~Change Logger constants to have RFC values (https://github.com/php-fig/log/issues/8)~~
    • [x] Remove substr TODO in AmqpHandler
    • [x] Remove default handler ($this->pushHandler(new StreamHandler('php://stderr', static::DEBUG));) from Monolog\Logger
    • [x] ~~Consider adding a public method (send or write or so) on handlers to make reusing them out of monolog easier, c.f.~~ https://github.com/Seldaek/monolog/commit/f3b61cf48af2c0730f149ae48f930e12a3bec1f2#commitcomment-8237858
    • [x] Consider using MongoDBFormatter as default in MongoDBHandler
    • [x] Drop support for outdated mongo exts in MongoDBHandler
    • [x] Remove BC __get() in SwiftMailerHandler
    • [x] Update HipChat to API v2 using 01549ec4d05e2d3f33227531d9fc9454d5ef6049 and room_id and from in buildContent (+ nickname everywhere) should be removed. See if we can't detect the token format and warn users using a v1 token.
    • [x] Check all PHP_VERSION and version_compare checks for relevance
    • [x] LineFormatter when showing stack traces should show new lines on new lines, and not the exception as part of the context that gets inlined into json => #752
    • [x] Consider removing useless PHP docs if the scalar + return type hints give enough info
    • [x] Disable microseconds timestamps by default?

    php7 ideas:

    • [x] treat Error-class exceptions in a special way as they are replacing E_COMPILE_ERROR and such from defaultErrorLevelMap
    • [x] ~~possibly remove ErrorHandler::registerFatalHandler if this is not needed anymore~~
    • [x] enable strict mode everywhere?

    ~~those items have been abandoned~~

    opened by Seldaek 28
  • Getting token to use Monolog with Slack

    Getting token to use Monolog with Slack

    It is not straight forward to get a token to use monolog with Slack. The expectation is that you write an OAuth client to get the token, but it is possible to get it manually. These are the steps I followed today:

    You should already have an account and a channel set up that you want to send error messages to.

    1. Create a new Slack App - https://api.slack.com/applications/new which will give you a client_id and a client_secret which you need for step two. You will need to enter a redirect URI, which can be any page for this purpose.
    2. Got to https://slack.com/oauth/authorize?client_id=[client_id]&scope=chat:write:bot
    3. Authorise App on the page that is returned.
    4. From the URI copy the code that is returned.
    5. Go to https://slack.com/api/oauth.access?client_id=[client_id]&client_secret=[client_secret]&code=[code]
    6. Your token is in the JSON that is displayed.

    TO debug errors insert echo fread($this->resource, 1000); at the end of the writeToSocket method of Monolog/Handler/SocketHandler (see https://github.com/Seldaek/monolog/issues/514)

    Documentation Bug 
    opened by nisbeti 25
  • FirePHP 1.0 support

    FirePHP 1.0 support

    I added support for FirePHP 1.0 to the FirePHP handler along with instructions in the README.

    The handler will now use FirePHP 1.0 if detected instead of the built-in protocol implementation. There are many advantages to this including:

    • Encoding of complex variables
    • File and line info
    • Support for large numbers of log messages
    • Support for evolving Companion client tools

    Coming soon:

    • Conditional logging where the client can enable and disable log handlers on request

    Try it out, let me know what you think. I would be happy to maintain this integration and add to it over time.

    I hope you are enjoying your time away!

    Christoph

    opened by cadorn 25
  • use of `new DateTimeImmutable` without `\` prefix or `use` statement

    use of `new DateTimeImmutable` without `\` prefix or `use` statement

    Monolog version 2

    https://github.com/Seldaek/monolog/blob/main/src/Monolog/Logger.php#L310

    Attempted to load class "DateTimeImmutable" from namespace "Monolog".
    Did you forget a "use" statement for another namespace?
    

    Also seen on StackOverflow

    Bug 
    opened by alister 23
  • Logstash throws error with json codec due time format

    Logstash throws error with json codec due time format

    Here's an error that logstash 1.3.2 throws using V1 LogstashFormatter:

    A plugin had an unrecoverable error. Will restart this plugin.
      Plugin: <LogStash::Inputs::File path=>["/Users/simas/Sites/kibana/logger/logs/app.log"], type=>"app", start_position=>"end">
      Error: Invalid format: "2013-12-29T22:11:23.429748+02:00" is malformed at "748+02:00" {:level=>:error}
    

    Seems that logstash expects UTC timestamp without timezone, somethning like this: 2013-12-29T22:11:23.429Z

    opened by saimaz 23
  • Add support for handling PHP Errors, etc

    Add support for handling PHP Errors, etc

    Examples of this are in Zend\Log and Raven_Client

    https://github.com/getsentry/raven-php/blob/master/lib/Raven/ErrorHandler.php (Handles uncaught exceptions, fatal errors and PHP errors)

    https://github.com/zendframework/zf2/blob/master/library/Zend/Log/Logger.php#L504

    opened by davidwindell 23
  • Sync RollbarHandler with the latest changes rollbar/rollbar package

    Sync RollbarHandler with the latest changes rollbar/rollbar package

    We received a request to update Monolog's RollbarHandler to be in sync with the latest version of our SDK ( https://github.com/rollbar/rollbar-php ). The github issue can be found here: https://github.com/rollbar/rollbar-php/issues/249

    This PR makes the RollbarHandler up to date with rollbar-php v1.0+.

    Please, review and merge to master if it looks good to go.

    opened by ArturMoczulski 22
  • Level_name options

    Level_name options

    It would be great to have optional level_name name. For example NLog has feature to make level_name as 1, 3 letters or full name. Current situation (log strings):

    [2022-21-12 10:10:01.718][INFO][127.0.0.1] '6': user login [2022-21-12 10:10:01.724][WARNING][127.0.0.1] '6': domain gmail.com is forbidden to use or does not exist
    [2022-21-12 10:10:01.724][ERROR][127.0.0.1] '6': user email is forbidden to use

    If set it level_name as 1 or 3 letters logs can be like this:

    [2022-21-12 10:10:01.718][INF][127.0.0.1] '6': user login [2022-21-12 10:10:01.724][WRN][127.0.0.1] '6': domain gmail.com is forbidden to use or does not exist
    [2022-21-12 10:10:01.724][ERR][127.0.0.1] '6': user email is forbidden to use

    [2022-21-12 10:10:01.718][I][127.0.0.1] '6': user login [2022-21-12 10:10:01.724][W][127.0.0.1] '6': domain gmail.com is forbidden to use or does not exist
    [2022-21-12 10:10:01.724][E][127.0.0.1] '6': user email is forbidden to use

    It helps to read logs. Idea do make option: INFO = INF = I ERROR = ERR = E WARNING = WRN = W DEBUG = DBG = D and so on...

    Feature 
    opened by funtus00 0
  • glob() not finding the existing log -> Log rotation doesn't delete files

    glob() not finding the existing log -> Log rotation doesn't delete files

    Monolog version 1|2|3? it's version 2

    Related to https://github.com/Seldaek/monolog/issues/204#issuecomment-19757534

    I use the drupal monolog module which is using this monolog library.

    In the following line I get an empty array:

    https://github.com/Seldaek/monolog/blob/2.8.0/src/Monolog/Handler/RotatingFileHandler.php#L142

    for the path "private://logs/debug.log" because glob can't compute the right paths. The files definitely exist. If I replace the path with an absolute one, it works, but then I'd have to adjust the paths for each and every environment which is tedious :-/

    Maybe we can think about using something else than glob() here? Or is there something I can do?

    See here as well: https://www.drupal.org/project/monolog/issues/3326496

    Thanks in advance!

    Bug 
    opened by Defcon0 0
  • Uncaught TypeError: Monolog\Logger::getLevelName() ConsoleHandler given

    Uncaught TypeError: Monolog\Logger::getLevelName() ConsoleHandler given

    Monolog version 2 & 3

    Since upgrading to Symfony 6.1 (and PHP 8.1), I have been seeing a very rare Symfony container construction issue within the Monolog code. The error is logged by PHP-FPM to nginx:

    2022/12/10 07:50:02 [error] 28#28: *273 FastCGI sent in stderr: "PHP message: PHP Fatal error:  Uncaught TypeError: Monolog\Logger::getLevelName(): Argument #1 ($level) must be of type Monolog\Level|int, Symfony\Bridge\Monolog\Handler\ConsoleHandler given, called in /app/vendor/monolog/monolog/src/Monolog/Logger.php on line 196 and defined in /app/vendor/monolog/monolog/src/Monolog/Logger.php:437
    Stack trace:
    #0 /app/vendor/monolog/monolog/src/Monolog/Logger.php(196): Monolog\Logger::getLevelName()
    #1 /app/var/cache/prod/ContainerOqglp2q/App_KernelProdContainer.php(1441): Monolog\Logger->pushHandler()
    #2 /app/var/cache/prod/ContainerOqglp2q/App_KernelProdContainer.php(1103): ContainerOqglp2q\App_KernelProdContainer->getMonolog_Logger_RequestService()
    #3 /app/vendor/symfony/dependency-injection/Container.php(218): ContainerOqglp2q\App_KernelProdContainer->getHttpKernelService()
    #4 /app/vendor/symfony/dependency-injection/Container.php(198): Symfony\Component\DependencyInjection\Container->make()
    #5 /app/vendor/symfony/http-kernel/Kernel.php(195): Symfony\Compone" while reading response header from upstream, client: 172.19.0.2, server: _, request: "POST /job-engine-client/execute HTTP/1.0", upstream: "fastcgi://172.31.0.3:9000", host: "x"
    

    This error only gets triggered once every 500 requests. The code is deployed using docker to multiple hosts (ubuntu 22.04 host and container), and the same rare issue happens on multiple hosts.

    When looking at the monolog Logger.php code, it seems impossible that a pushHandler will trigger a getLevelName, and even more will cause a ConsoleHandler to be given as level argument. But still this is the only issue I'm seeing, with the exact same trace every time.

    Is this a bug within Monolog? Are there any similar issues known?

    Bug 
    opened by erikbaan 2
  • How Remove PII (Personal Information) from MonoLog log files?

    How Remove PII (Personal Information) from MonoLog log files?

    Monolog version 3?

    I see some plugins and scripts to remove PII from monolog logs, but everything i have found is realted to Monolog 2. How can i remove information like CreditCard data from any logs?

    Here's and example i found for Monolog 2.0

    If I implement what is here with Monolog 3, I get the following error.

    Fatal error: Declaration of RedactSensitive\RedactSensitiveProcessor::__invoke(array $record): array must be compatible with Monolog\Processor\ProcessorInterface::__invoke(Monolog\LogRecord $record) in /... .../RedactSensitiveProcessor.php on line 34

    Support 
    opened by ballcorn 0
  • add some @throws in constructors

    add some @throws in constructors

    In some constructors Exceptions are thown, but not mentioned in the Docblocks. This results in phpstan error messages when I want to catch these Exceptions.

    opened by mimmi20 0
Owner
Jordi Boggiano
Working on https://packagist.com and https://teamup.com - @composer lead - OSS wishlist: https://seld.be/wishlist
Jordi Boggiano
Amazon Web Services CloudWatch Logs Handler for Monolog library

AWS CloudWatch Logs Handler for Monolog Handler for PHP logging library Monolog for sending log entries to AWS CloudWatch Logs service. Before using t

Maksym Leonov 377 Dec 16, 2022
Keep your laravel logs small and tidy.

Logs can get quite out of hand. This package helps save server space and keep your Laravel log files small.

Accent Interactive 73 Nov 14, 2022
Clear all your logs in [linux/windows] servers 🛡️

Log-killer Log Killer is tool for [Linux/Windows] Servers This tool will delete all your logs just download the tool and run it on the server if your

Rizer 281 Nov 24, 2022
Capture and monitor detailed error logs with nice dashboard and UI

Capture and monitor detailed error logs with nice dashboard and UI Requirements Check Laravel 6 requirements Check Laravel 7 requirements Installation

Bugphix 107 Dec 12, 2022
Paste, share and analyse Minecraft server logs

mclo.gs Paste, share & analyse your Minecraft server logs About The project mclo.gs was created in 2017 by the Aternos team after more than 4 years of

Aternos 99 Jan 3, 2023
Logs which process created or modified a record

It is sometimes very useful to know which process created or modified a particular record in your database. This package provides a trait to add to your Laravel models which automatically logs that for you.

ORIS Intelligence 98 Dec 4, 2022
Small package that can helps in debugging with API logs for Laravel Project.

Rest APIs Logger This is a small package that can helps in debugging with API logs. Installation Install the package via composer composer require tfs

Sunny Mahajan 7 Aug 31, 2022
Small laravel package for viewing api logs which can be used in debugging.

This is a small package that can helps in debugging api logs. It can log request method, url, duration, request payload, which models are retrieved, controller and method.

awt 334 Jan 6, 2023
Small tool that extracts witness data from Helium miner logs.

Helium Miner Logs Analyzer Small tool that extracts witness data from Helium miner logs. It currently works for the Pisces 100 and miner version miner

Iñigo Flores 42 Dec 11, 2022
Allows you to process logs using any PSR-3 compatible logger such as Monolog

Yii 2 PSR Log Target Allows you to process logs using any PSR-3 compatible logger such as Monolog

Alexander Makarov 67 Dec 14, 2022
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
DatabaseLog CakePHP plugin to log into DB instead of files. Better to filter and search.

CakePHP DatabaseLog Plugin DatabaseLog engine for CakePHP applications. This branch is for CakePHP 4.0+. See version map for details. Features Easy se

Mark Sch. 41 Jul 29, 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
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
Laravel logger is an activity event logger for your Laravel or Lumen application

Laravel logger is an activity event logger for your Laravel or Lumen application. It comes out the box with ready to use with dashboard to view your activity. Laravel logger can be added as a middleware or called through a trait. Easily have an Activity Log. This package is easily configurable and customizable. Supports Laravel 5.3, 5.4, 5.5, 5.6, 5.7, 5.8, 6, and 7+

Jeremy Kenedy 475 Dec 22, 2022
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
Flexible and rock solid audit log tracking for CakePHP 3

AuditStash Plugin For CakePHP This plugin implements an "audit trail" for any of your Table classes in your application, that is, the ability of recor

José Lorenzo Rodríguez 68 Dec 15, 2022
Log Laravel application request and response with a unique ID for easy debugging

Flexible and extendable logging of Laravel application request and responses Zero configuration logging of Requests and Responses to database or custo

Bilfeldt 37 Nov 6, 2022
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