[PHP class library] Monolog

Source: Internet
Author: User
[PHP class library] Monolog is a PHP log class library. Compared with other log class libraries, it has the following features:

  • Powerful functions. Logs can be sent to files, sockets, mailboxes, databases, and various web services.
  • Follow the PSR3 interface specifications. It can be easily replaced with other log class libraries that follow the same specification.
  • Excellent scalability. Through the Handler, Formatter, and Processor interfaces, you can extend and customize the Monolog class library.
Basic usage

Install the latest version:

composer require monolog/monolog

PHP version 5.3 or later is required.

Php
 PushHandler (new StreamHandler ('path/to/your. log', Logger: WARNING); // add a log record $ log-> addWarning ('Foo'); $ log-> addError ('bar ');
Core Concepts

Each Logger instance contains a channel name and a handler stack. When you add a record, the record will be processed in turn through the handler stack. Each handler can decide whether to pass the record to the next handler in the next stack.

With handler, we can implement some complex log operations. For example, if we put StreamHandler at the bottom of the stack, all the log records will eventually be written to the hard disk file. At the same time, we put MailHandler at the top of the stack, and set the log level to send error logs by email. Handler has a $ bubble attribute, which defines whether the handler intercepts the record and does not let it flow to the next handler. Therefore, if we set the $ bubble parameter of MailHandler to false, the log will be sent out through MailHandler when an error log appears, instead of being written to the hard disk through StreamHandler.

Logger can create multiple channels, each of which can define its own channel name and handler stack. Handler can be shared among multiple Logger instances. The channel name is reflected in the log so that we can view and filter the log records.

If no Formatter is specified, Handler uses the default Formatter.

The log level cannot be customized. Currently, eight levels defined in RFC 5424 are used: debug, info, notice, warning, error, critical, alert, and emergency. If you have other requirements for logging, you can add content to the logging through Processo.

Log level
  • DEBUG(100): detailed debug information.
  • INFO(200): critical events.
  • NOTICE(250): Common but important events.
  • WARNING(300): Non-error exception.
  • ERROR(400): indicates a running error, but it does not need to be handled immediately.
  • CRITICA(500): serious error.
  • EMERGENCY600: The system is unavailable.
Multiple handler
Php
 PushHandler (new StreamHandler (_ DIR __. '/my_app.log', Logger: DEBUG); $ logger-> pushHandler (new firephandler ()); // start using $ logger-> addInfo ('My logger is now ready ');

The first step is to create a Logger instance with the channel name. this channel name can be used to differentiate multiple Logger instances.

The instance itself does not know how to handle the log record, it is processed through handler. Handler can be set to multiple. for example, two handler can be set in the preceding example to process log records in two different ways.

Note that the handler is saved in the stack mode, so the handler added later is located at the top of the stack and will be called first.

Add additional data

Monolog can be used to add additional information to logs.

Use context

The first method is to use the $ context parameter to input an array:

php
 addInfo('Adding a new user', array('username' => 'Seldaek'));
Use processor

The second method is to use processor. Processor can be any callable method. these methods take the log record as a parameter and return the result after processing and modifying the extra part.

php
 pushProcessor(function ($record) {    $record['extra']['dummy'] = 'Hello world!';    return $record;});

Processor does not have to be bound to a Logger instance or to a specific handler. Use the pushProcessor method of the handler instance for binding.

Use of channels

You can use the channel name to classify logs, which is useful for large applications. By using the channel name, you can easily select log records.

For example, if we want to record logs of different modules in the same log file, we can bind the same handler to different Logger instances. these instances use different channel names:

Php
 PushHandler ($ stream); $ logger-> pushHandler ($ firephp ); // create a security-related logger with different channel names $ securityLogger = new Logger ('security'); $ securityLogger-> pushHandler ($ stream ); $ securityLogger-> pushHandler ($ firephp );
Handler

Monolog has many built-in practical handler, which covers almost all kinds of use cases. here we will introduce some usage:
StreamHandler: writes records into PHP streams and is mainly used for log files.
SyslogHandler: writes records into syslogs.
ErrorLogHandler: writes records into PHP error logs.
NativeMailerHandler: use the mail () function of PHP to send log records.
SocketHandler: writes logs through socket.

php
 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 records into services compatible with the amqp protocol.
BrowserConsoleHandler: writes log records to the browser console. Because the console object of the browser is used, check whether the browser supports it.
RedisHandler: write the record into Redis.
MongoDBHandler: writes records into Mongo.
ElasticSearchHandler: writes records to the ElasticSearch Service.
BufferHandler: allows us to cache log records for one-time processing.

For more Handler information, see https://github.com/seldaek/monolog?handlers.

Formatter

Similarly, here we will introduce several built-in Formatter:
LineFormatter: format the log into a string.
HtmlFormatter: format the log record into an HTML table, which is mainly used for mail.
JsonFormatter: encodes log records into JSON format.
LogstashFormatter: format the log record into the event JSON format of logstash.
ElasticaFormatter: format the log into the data format used by ElasticSearch.

For more Formatter information, see https://github.com/seldaek/monolog1_formatters.

Processor

As mentioned above, Processor can add additional information for log records. Monolog also provides some useful processor:
IntrospectionProcessor: Adds information such as the file name and class name of the current script.
WebProcessor: Adds information such as the URI, request method, and access IP address of the current request.
MemoryUsageProcessor: adds the current memory usage information.
MemoryPeakUsageProcessor: increases the memory usage peak information.

For more Processor information, see https://github.com/seldaek/monolog#processors.

Extended handler

Monolog has many built-in handler, but not all scenarios can be covered. sometimes handler needs to be customized by yourself. Writing a handler is not difficult. you only need to implement the interface Monolog \ Handler \ HandlerInterface.

The following example writes log records to the database. We don't need to implement all the methods in the interface once. Instead, we can use the abstract class AbstractProcessingHandler provided by Monolog to inherit from each other and implement the write method in it.

php
 pdo = $pdo;        parent::__construct($level, $bubble);    }    protected function write(array $record)    {        if (!$this->initialized) {            $this->initialize();        }        $this->statement->execute(array(            'channel' => $record['channel'],            'level' => $record['level'],            'message' => $record['formatted'],            'time' => $record['datetime']->format('U'),        ));    }    private function initialize()    {        $this->pdo->exec(            'CREATE TABLE IF NOT EXISTS monolog '            .'(channel VARCHAR(255), level INTEGER, message LONGTEXT, time INTEGER UNSIGNED)'        );        $this->statement = $this->pdo->prepare(            'INSERT INTO monolog (channel, level, message, time) VALUES (:channel, :level, :message, :time)'        );    }}

Then we can use it:

php
 pushHandler(new PDOHandler(new PDO('sqlite:logs.sqlite'));// You can now use your logger$logger->addInfo('My logger is now ready');
Reference

Https://github.com/Seldaek/monolog

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.