Monolog Php

Azure App Service provides a highly scalable, self-patching web hosting service using the Windows operating system. This tutorial shows how to create a PHP app in Azure and connect it to a MySQL database. Php composer.phar install Autoload Dependencies. If your packages specify autoloading information, you can autoload all the dependencies by adding this to your code: require 'vendor/autoload.php'; Browse the packages we have to find more great libraries you can use in your project. For example, if your project depends on the monolog library, your project is the root package. However, if you clone monolog from GitHub in order to fix a bug in it, then monolog is the root package. Properties# name# The name of the package. It consists of vendor name and project name, separated by /. Examples: monolog/monolog; igorw/event-source. To make it a complete, end-to-end logging infrastructure for your PHP web application, I highly recommend using monolog as well to cover more back-end-related debugging purposes. Tie it all together by using an application performance monitoring tool such as Retrace to track your application performance, search through all your logs easily,.


Monolog is available on Packagist (monolog/monolog)and as such installable via Composer.

Core Concepts

Every Logger instance has a channel (name) and a stack of handlers. Wheneveryou add a record to the logger, it traverses the handler stack. Each handlerdecides whether it fully handled the record, and if so, the propagation of therecord ends there.

This allows for flexible logging setups, for example having a StreamHandler atthe bottom of the stack that will log anything to disk, and on top of that adda MailHandler that will send emails only when an error message is logged.Handlers also have a $bubble property which defines whether they block therecord or not if they handled it. In this example, setting the MailHandler’s$bubble argument to false means that records handled by the MailHandler willnot propagate to the StreamHandler anymore.

You can create many Loggers, each defining a channel (e.g.: db, request,router, ..) and each of them combining various handlers, which can be sharedor not. The channel is reflected in the logs and allows you to easily see orfilter records.

Monolog Php Software

Each Handler also has a Formatter, a default one with settings that make sensewill be created if you don’t set one. The formatters normalize and formatincoming records so that they can be used by the handlers to output usefulinformation.

Custom severity levels are not available. Only the eightRFC 5424 levels (debug, info, notice,warning, error, critical, alert, emergency) are present for basic filteringpurposes, but for sorting and other use cases that would requireflexibility, you should add Processors to the Logger that can add extrainformation (tags, user ip, ..) to the records before they are handled.

Log Levels

Monolog supports the logging levels described by RFC 5424.

  • DEBUG (100): Detailed debug information.

  • INFO (200): Interesting events. Examples: User logs in, SQL logs.

  • NOTICE (250): Normal but significant events.

  • WARNING (300): Exceptional occurrences that are not errors. Examples:Use of deprecated APIs, poor use of an API, undesirable things that are notnecessarily wrong.

  • ERROR (400): Runtime errors that do not require immediate action butshould typically be logged and monitored.

  • CRITICAL (500): Critical conditions. Example: Application componentunavailable, unexpected exception.

  • ALERT (550): Action must be taken immediately. Example: Entire websitedown, database unavailable, etc. This should trigger the SMS alerts and wakeyou up.

  • EMERGENCY (600): Emergency: system is unusable.

Configuring a logger

Here is a basic setup to log to a file and to firephp on the DEBUG level:

Let’s explain it. The first step is to create the logger instance which willbe used in your code. The argument is a channel name, which is useful whenyou use several loggers (see below for more details about it).

Monolog phpmailer

The logger itself does not know how to handle a record. It delegates it tosome handlers. The code above registers two handlers in the stack to allowhandling records in two different ways.

Note that the FirePHPHandler is called first as it is added on top of thestack. This allows you to temporarily add a logger with bubbling disabled ifyou want to override other configured loggers.

If you use Monolog standalone and are looking for an easy way toconfigure many handlers, the theorchard/monolog-cascadecan help you build complex logging configs via PHP arrays, yaml or json configs.

Adding extra data in the records

Monolog provides two different ways to add extra information along the simpletextual message.

Using the logging context

The first way is the context, allowing to pass an array of data along therecord:

Php Logging Library

Simple handlers (like the StreamHandler for instance) will simply formatthe array to a string but richer handlers can take advantage of the context(FirePHP is able to display arrays in pretty way for instance).

Using processors

The second way is to add extra data for all records by using a processor.Processors can be any callable. They will get the record as parameter andmust return it after having eventually changed the extra part of it. Let’swrite a processor adding some dummy data in the record:

Monolog provides some built-in processors that can be used in your project.Look at the dedicated chapter for the list.

Tip: processors can also be registered on a specific handler instead of the logger to apply only for this handler.

Leveraging channels

Channels are a great way to identify to which part of the application a recordis related. This is useful in big applications (and is leveraged byMonologBundle in Symfony).

Picture two loggers sharing a handler that writes to a single log file.Channels would allow you to identify the logger that issued every record.You can easily grep through the log files filtering this or that channel.

Customizing the log format

In Monolog it’s easy to customize the format of the logs written into files,sockets, mails, databases and other handlers. Most of the handlers use the

value to be automatically put into the log device. This value depends on theformatter settings. You can choose between predefined formatter classes orwrite your own (e.g. a multiline text file for human-readable output).

To configure a predefined formatter class, just set it as the handler’s field:

You may also reuse the same formatter between multiple handlers and share thosehandlers between multiple loggers.

Long running processes and avoiding memory leaks

When logging lots of data or especially when running background workers whichare long-lived processes and do lots of logging over long periods of time, thememory usage of buffered handlers like FingersCrossedHandler or BufferHandlercan rise quickly.

Monolog provides the ResettableInterface for this use case, allowing you toend a log cycle and get things back to their initial state.

Calling $logger->reset(); means flushing/cleaning all buffers, resetting internalstate, and getting it back to a state in which it can receive log records again.

This is the conceptual equivalent of ending a web request, and can be donebetween every background job you process, or whenever appropriate. It reduces memoryusage and also helps keep logs focused on the task at hand, avoiding log leaksbetween different jobs.

Handlers, Formatters and Processors →