» » Monolog-PHP log class library introduction

 

Monolog-PHP log class library introduction

Author: bamboo06 on 2-12-2018, 17:47, views: 299

0
Monolog is a full and easy to expand log log library under php. There are many well-known php frameworks including Symfony, Laravel, CakePHP and so on that have Monolog built in. Monolog can send your logs to files, sockets, inboxes, databases and various web services.
Monolog-PHP log class library introduction

Monolog follows the PSR3 interface specification and can be easily replaced with other log classes that follow the same specification. Monolog has good extensibility. Through the interfaces Handler, Formatter and Processor, you can expand and customize the Monolog library.

Basic usage
Monolog can be installed via github or composer. The following is the latest version installed with composer:
composer require monolog/monolog


The PHP version is required to be 5.3 or higher.
<?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 logging
$log->addWarning('Foo');
$log->addError('Bar');


Key concept
Each Logger instance contains a channel name and a stack of handlers. When you add a record, the record is processed through the handler stack in turn. Each handler can also decide whether to pass the record to the next handler in the next stack.
With the handler, we can implement some complicated log operations. For example, if we put the StreamHandler at the bottom of the stack, then all the log records will eventually be written to the hard disk file. At the same time, we put the MailHandler on the top of the stack, and send the error log through the mail by setting the log level. There is a $bubble attribute in the Handler that defines whether the handler intercepts the record and does not let it flow to the next handler. So if we set the $bubble parameter of MailHandler to false, then when the error log appears, the log will be sent out through MailHandler, and will not be written to the hard disk via StreamHandler.
Logger can create multiple, each of which can define its own channel name and handler stack. The handler can be shared among multiple Loggers. The channel name will be reflected in the log so that we can view and filter the log records.
If no log format is specified, the Handler will use the default Formatter.
The level of the log cannot be customized. Currently, 8 levels defined in RFC 5424 are used: debug, info, notice, warning, error, critical, alert, and emergency. If there are other requirements for logging, you can add content to the log record through Processo.

Log level
DEBUG (100): Detailed debug information.
INFO (200): Key events.
NOTICE (250): A normal but important event.
WARNING (300): A non-error exception occurred.
ERROR (400): Runtime error, but does not need to be processed immediately.
CRITICA (500): Serious error.
EMERGENCY (600): The system is not available.

Detailed usage
Multiple handlers
<?php

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

// Create a Logger instance
$logger = new Logger('my_logger');
// add handler
$logger->pushHandler(new StreamHandler(__DIR__.'/my_app.log', Logger::DEBUG));
$logger->pushHandler(new FirePHPHandler());

// start to use
$logger->addInfo('My logger is now ready');


The first step is to create a Logger instance. The channel name is passed in. This channel name can be used to distinguish multiple Logger instances.
The instance itself does not know how to handle logging, it is handled by the handler. The handler can be set to multiple. For example, the above example sets up two handlers, which can handle the log records in two different ways.
It should be noted that since the handler is saved in a stack, the handler added later is at the top of the stack and will be called first.

Add extra data
Monolog has two ways to add extra information to the log.
The first method is to use the context, using the $context parameter, passing in an array:
<?php
$logger->addInfo('Adding a new user', array('username' => 'Seldaek'));

The second method is to use a processor. The processor can be any callable method that takes the log record as a parameter and then returns it after processing the extra part.
<?php
$logger->pushProcessor(function ($record) {
    $record['extra']['dummy'] = 'Hello world!';

    return $record;
});

The Processor does not have to be bound to the Logger instance, or it can be bound to a specific handler. Bind using the pushProcessor method of the handler instance.

Use of the channel
Logs can be categorized using channel names, which is useful for large applications. The log record can be easily selected by the channel name.
For example, we want to record the logs of different modules in the same log file. We can bind the same handler to different Logger instances, which use different channel names:
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
use Monolog\Handler\FirePHPHandler;

// creat handler
$stream = new StreamHandler(__DIR__.'/my_app.log', Logger::DEBUG);
$firephp = new FirePHPHandler();

// Create an app’s main logger
$logger = new Logger('my_logger');
$logger->pushHandler($stream);
$logger->pushHandler($firephp);

// Create a security-related logger with a different channel name
$securityLogger = new Logger('security');
$securityLogger->pushHandler($stream);
$securityLogger->pushHandler($firephp);


Handler
Monolog has a lot of very useful handlers. They cover almost all kinds of usage scenarios. Here are some of the usages:
StreamHandler: Writes the record into the PHP stream, mainly for log files.
SyslogHandler: Write the record to syslog.
ErrorLogHandler: Write the record to the PHP error log.
NativeMailerHandler: Sends a log record using PHP's mail() function.
SocketHandler: Write the log through the socket.
use Monolog\Logger;
use Monolog\Handler\SocketHandler;

// Create the logger
$logger = new Logger('my_logger');

// Create the handler
$handler = new SocketHandler('unix:///var/log/httpd_app_log.socket');
$handler->setPersistent(true);

// Now add the handler
$logger->pushHandler($handler, Logger::DEBUG);

// You can now use your logger
$logger->addInfo('My logger is now ready');


AmqpHandler: Write the record into a service compatible with the amqp protocol.
BrowserConsoleHandler: Write the log record to the browser's console. Since you are using the browser's console object, you need to see if the browser supports it.
RedisHandler: Write the record to Redis.
MongoDBHandler: Write the record to Mongo.
ElasticSearchHandler: Write the record to the ElasticSearch service.
BufferHandler: Allows us to cache the log records for processing at once.

Formatter
Similarly, here are a few of the included Formatters:
LineFormatter: Formats the log record into a single line of characters.
HtmlFormatter: Formats log records into HTML forms, primarily for mail.
JsonFormatter: Encode log records into JSON format.
LogstashFormatter: Formats the log record into the event JSON format of logstash.
ElasticaFormatter: Format the log records into the data format used by ElasticSearch.

Processor
As mentioned earlier, Processor can add additional information to the log record. Monolog also provides some very useful processors:
IntrospectionProcessor: Add information such as the file name and class name of the current script.
WebProcessor: Add information such as the current request URI, request method, and access IP.
MemoryUsageProcessor: Increase current memory usage information.
MemoryPeakUsageProcessor: Increases the information when the memory usage peaks.

For more information about Monolog, please refer to the Monolog website: monolog on github

Tags: Monolog, php, log, class

Category: PHP Scripts / Plugins

Dear visitor, you are browsing our website as Guest.
We strongly recommend you to register and login to view hidden contents.
Information
Comment on the news site is possible only within (days) days from the date of publication.