"PHP class Library" Monolog

Source: Internet
Author: User
Tags php error php error log
Monolog is a log class library for PHP. Compared to other log class libraries, it has the following features:

    • Powerful. Logs can be sent to files, sockets, mailboxes, databases, and various Web services.
    • Follow the PSR3 interface specification. can be easily replaced with other log class libraries that follow the same specification.
    • Good extensibility. The Monolog class libraries can be expanded and customized through the handler, formatter, and processor interfaces.

Basic usage

Install the latest version:

Composer require Monolog/monolog

PHP version is required to be 5.3 or more.

PHP
 
   Pushhandler (New Streamhandler (' Path/to/your.log ', logger::warning));//Add Logging $log->addwarning (' Foo '); $log->adderror (' Bar ');

Core Concepts

Each logger instance contains a stack of channel names (channel) and handler. When you add a record, the record is processed sequentially through the handler stack. Each handler can also decide whether to pass records to the next handler in the next stack.

With handler, we can implement some complex log operations. For example, if we put streamhandler on the bottom of the stack, 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, by setting the log level to send the error log through the mail. There is a $bubble attribute in 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 the Mailhandler to False, when the error log occurs, the log is sent through Mailhandler without streamhandler writing to the hard disk.

Logger can create multiple, each of which can define its own channel name and handler stack. Handler can be shared across multiple logger. The channel name is reflected in the log, which allows us to view and filter the log records.

If you do not specify a log format (Formatter), Handler uses the default Formatter.

The level of the log cannot be customized and currently uses 8 levels defined in RFC 5424: Debug, info, notice, warning, error, critical, alert, and emergency. If you have additional requirements for logging, you can add content to the log record through Processo.

Log level

    • DEBUG (100): detailed debug information.
    • INFO (200): Key event.
    • NOTICE (250): ordinary but important events.
    • WARNING (300): A non-error exception occurred.
    • ERROR (400): Run-time error, but no immediate processing required.
    • Critica (500): Critical error.
    • EMERGENCY (600): The system is not available.

Usage explanation

Multiple handler

PHP
 
   Pushhandler (New Streamhandler (__dir__. ' /my_app.log ', Logger::D ebug)), $logger->pushhandler (New Firephphandler ());//start using $logger->addinfo (' My Logger is now ready ');

The first step is to create a logger instance, passing in the channel name, which can be used to differentiate multiple logger instances.

The instance itself does not know how to handle logging, which is handled through handler. Handler can be set to multiple, for example, the above example set up two handler, you can do two different ways of processing the log records.

It is important to note that since handler is saved in a stack, the handler added later is at the top of the stack and will be called first.

Add additional data

Monolog There are two ways to add additional information to the log.

Use context

The first method is to pass in an array using the $context parameter:

PHP
 
   addinfo (' Adding A new user ', Array (' username ' = ' seldaek '));

Using processor

The second method is to use processor. Processor can be any callable method that takes logging as a parameter and then returns after processing the modified extra section.

PHP
 
   pushprocessor (function ($record) {    $record [' Extra '] [' dummy '] = ' Hello world! ';    return $record;});

Processor do not have to be bound on logger instances, or they can be bound to a specific handler. Binds using the Pushprocessor method of the handler instance.

Use of channels

The use of channel names can be used to classify logs, which is useful for large applications. With the channel name, you can easily swipe the log record.

For example, if we want to log different modules in the same log file, we can bind the same handler to different logger instances, which use different channel names:

PHP
 
   Pushhandler ($stream); $logger->pushhandler ($firephp);//Create a security-related Logger$securitylogger with different channel names = new Logger (' security '); $securityLogger->pushhandler ($stream); $securityLogger->pushhandler ($firephp);

Handler

The monolog has a lot of useful handler, and they cover almost all kinds of usage scenarios, some of which are used here:
Streamhandler: Writes the record in the PHP stream, mainly for the log file.
Sysloghandler: Write the records into the syslog.
Errorloghandler: Write the record in the PHP error log.
Nativemailerhandler: Send log records using the mail () function of PHP.
Sockethandler: Write the log through the socket.

PHP
 
   setpersistent (TRUE);//Now Add the Handler$logger->pushhandler ($handler, logger::D ebug);//can now Use your Logger$logger->addinfo (' My logger are now ready ');

Amqphandler: Write the records into a service that is compatible with the AMQP protocol.
Browserconsolehandler: Writes log records to the browser's console. Because you are using the browser's console object, you need to see if the browser supports it.
Redishandler: Write the records into Redis.
Mongodbhandler: Write the records into the MONGO.
Elasticsearchhandler: Write the records to the Elasticsearch service.
Bufferhandler: Allows us to cache log records for processing at once.

For more handler please see https://github.com/Seldaek/monolog#handlers.

Formatter

In the same way, here are a few of our own formatter:
Lineformatter: Formats the log records as a single line of string.
Htmlformatter: Format log records as HTML tables, primarily for mail.
Jsonformatter: Encode the log records into JSON format.
Logstashformatter: Formats the log records into the Logstash event JSON format.
Elasticaformatter: Formats the log records into the data format used by the Elasticsearch.

For more formatter please see https://github.com/Seldaek/monolog#formatters.

Processor

As I said earlier, processor can add additional information to the log records, and Monolog also provides some useful processor:
Introspectionprocessor: Adds information such as the file name and class name of the current script.
Webprocessor: Increases the URI, request method, and access IP information for the current request.
Memoryusageprocessor: Increases current memory usage information.
Memorypeakusageprocessor: Increases the information when memory usage spikes.

For more processor please see https://github.com/Seldaek/monolog#processors.

Extended Handler

Monolog has a lot of handler built-in, but not all the scenes can be covered, sometimes you need to customize the handler. It is not difficult to write a Handler, just implement the Monolog\handler\handlerinterface interface.

The following example enables logging of log records to the database. We do not need to implement all the methods in the interface once, can directly use the monolog provided by the abstract class Abstractprocessinghandler to inherit, implement the Write method inside.

Php
 PDO = $pdo;    Parent::__construct ($level, $bubble);        } protected function write (array $record) {if (! $this->initialized) {$this->initialize (); } $this->statement->execute (' channel ' = ' $record [' channel '], ' level ' = > $record [' Level '], ' message ' + $record [' formatted '], ' time ' = $record [' DateTime ']->FO    Rmat (' 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 (' Sqlite:logs.sqlite '));//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.