Monolog-logging for PHP 5.3+

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. Through Handler , Formatter and Processor These interfaces, the Monolog class library can be extended and customized.
Basic usage

Install the latest version:

require monolog/monolog

PHP version is required to be 5.3 or more.

php<?phpuse Monolog\Logger;use Monolog\Handler\StreamHandler;// 创建日志频道$log = new Logger(‘name‘);$log->pushHandler(new StreamHandler(‘path/to/your.log‘, Logger::WARNING));// 添加日志记录$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, we put on the bottom of the StreamHandler stack, then all the log records will eventually be written to the hard disk file. At the same time we put on the top MailHandler of the stack, by setting the log level to send the error log through the mail. There is a property in handler $bubble that defines whether handler intercepts the record and does not let it flow to the next handler. So if we MailHandler set the $bubble parameter to an false error log, the log is MailHandler sent out and not StreamHandler written to the hard disk.

LoggerYou can create multiple, each of which can define your own channel name and handler stack. Handler can be shared among 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 detailed multiple Handler
  php   <?php Use Monolog\logger; use monolog\handler\streamhandler; use monolog\handler\firephphandler; //Create logger instance  $logger = new logger ( ' My_logger '); //add handler $logger->pushhandler (new Streamhandler (__dir__. $logger->pushhandler (new firephphandler ());  $logger->addinfo ( ' My logger is now ready ');    

The first step is to create an 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<?php$logger->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 log records as parameters and then returns after processing the modified extra part.

php<?php$logger->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. Bind using the method of the handler instance pushProcessor .

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<?phpUse Monolog\logger;Use Monolog\handler\streamhandler;Use Monolog\handler\firephphandler;Create Handler $stream = new streamhandler (__dir__. $firephp = new firephphandler ();  Create your app's main logger $logger = new logger ( ' My_logger ' );  $logger->pushhandler ( $stream);  $firephp); new Logger ( $securityLogger->pushhandler ( $stream);  $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 records into the PHP stream, primarily for log files.
    • 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: Writes the log through the socket.
php <?phpuse 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);  $logger->pushhandler ( $handler, logger::D ebug ); //you can now use your logger $logger->addinfo ( ' My logger is 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 the log records as HTML tables, mainly for mail.
    • JsonFormatter: Encode the log record in JSON format.
    • LogstashFormatter: Formats the log records into the Logstash event JSON format.
    • ElasticaFormatter: Formats the log records into the data format used by 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 Monolog\Handler\HandlerInterface this 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 abstract class provided by Monolog to AbstractProcessingHandler inherit, implement the write method inside.

php<?phpUse Monolog\logger;Use Monolog\handler\abstractprocessinghandler;ClassPdohandlerExtendsabstractprocessinghandler{ Private$initialized =False Private$pdo; Private$statement; Publicfunction__construct(PDO$pdo,$level = Logger::D ebug,$bubble = True){  $this->pdo =$pdo;  Parent::__construct ($level,$bubble);} ProtectedfunctionWrite(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 '), ));} PrivatefunctionInitialize(){   $this->pdo->exec ( Span class= "indent" >   ' CREATE TABLE IF not EXISTS monolog '   }              /span>          

Then we can use it:

php<?php$logger->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

Monolog-logging for PHP 5.3+

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.