PHP logs go beyond just errors. They're handy for tracking API and function performance, as well as keeping count of significant events in your application. No matter the project you're working on, implementing a logging strategy will help keep you in the loop about what's happening in your code.
Unlike languages like Go, Python, or Ruby, a dedicated logging solution does not exist in its standard library, so you must choose one of the available logging frameworks developed by the community. This article will present the top three options for logging in PHP and discuss their unique features, advantages, and use cases.
Let's get started!
1. Monolog
Monolog is the go-to logging framework for PHP applications. It provides a flexible and powerful way to log events and route the entries to various destinations, such as files, databases, email, or even external services. Getting started with Monolog is straight-forward via Composer:
You can subsequently import various Monolog classes into your project and use them as follows:
Monolog exposes a Logger class with a name and a stack of handlers. In the
above example, the StreamHandler class is used to create a handler that logs
to the standard output, and this handler is attached to the $logger.
Once an event is logged, each attached handler will decide whether to output the
record to the configured destination and how to format it. The default format
for Monolog handlers contains the timestamp, logger name, level, log message,
then some context and extra information ([] []).
You can customize this format through any of the
built-in formatter classes
such as the JsonFormatter. Once you create a formatter instance, you must
attach it to a handler instance as shown below:
You will now observe the following structured output:
Monolog defaults to logging at the DEBUG level, but you can customize this
through the Level class. To give maximum flexibility, the default level is
defined on the handler instances so that attached handlers can log at different
levels if desired:
To add contextual data to your log entries, you can pass an array of attributes as follows:
These data will be placed in the context property as shown below (assuming
you're using JsonFormatter):
A second way to add data to all log records created by a logger is through
processors.
For example, you can use the IntrospectionProcessor to add the originating
line number, file name, method, or class of the logged event:
You will observe that the extra field is now populated:
When it comes to logging exceptions, Monolog can automatically catch and log
uncaught exceptions before your application exits once you override the default
exception handling behavior with set_exception_handler():
Details about the exception will be placed in the event's context property:
Ensure to check out our dedicated Monolog guide for a deep dive on its concepts, features, and how it enhances logging practices in PHP applications.
2. Klogger
Klogger is a simple PSR-3 compliant library for writing event logs in PHP programs. It aims to be a solution that you could quickly incorporate into you project and have working right away without a convoluted configuration process. You may install it using the command below:
KLogger supports the log levels defined in the PSR-3 interface, and it defaults
to the DEBUG level:
You may modify the default level using the Psr\Log\LogLevel constants like
this:
The KLogger constructor also supports other options via a third argument. A
useful one is logFormat which defines the format of the log entries. JSON
formatted log entries can be achieved through the following configuration:
This yields log entries with the following structure:
You can also add contextual attributes at log point like this:
Logging to a file is also fully supported like this:
The first argument to the constructor signifies the directory to place the log file. Once you execute the program, you should see a file that looks like this in the current working directory:
Please see the KLogger documentation to learn how to customize this filename and the options it offers.
3. Analog
Analog's main goal is to provide a lightweight and simple logging solution similar Klogger, but without sacrificing flexibility regarding the logging destinations. It bundles a large number of handlers for this purpose, including the following:
- Syslog: output to syslog.
- Redis: send log entries to Redis.
- Post: send log entries over HTTP.
- Slackbot post log messages to Slack.
- Mongo: store logs in a MongoDB collection.
- and many more!
You can install the library through Composer like this:
Afterward, it may be utilized as follows through the provided PSR-3-compliant
Logger interface:
The default format is shown below:
It only allows limited customization through the $format option:
You can also convert log level numbers to names in the output through the
LevelName handler as follows:
This yields:
Please see the examples directory on GitHub for more usage examples. Note that Analog doesn't appear to be actively maintained at the time of writing given its last commit in late 2021.
Final thoughts
In the PHP ecosystem, the spectrum of libraries for effective logging is somewhat narrower when juxtaposed with the offerings available in other programming languages. Monolog is pretty much the only standout option, and it's also the default solution in popular frameworks such as Laravel and Symfony. We recommend that read our dedicated Monolog guide to learn how to best set up a production-ready configuration in your projects.
Thanks for reading, and happy logging!