[Tools Resources] The Monolog of the PHP package is not complete but sufficient guide

Source: Internet
Author: User
Tags dateformat one mail zend server flowdock elastic search couchdb aws sdk
Monolog sends your logs to files, sockets, inboxes, databases and various Web services.

Monolog sends your logs to files, to sockets, to mailboxes, to databases or to other networked storage services (clouds). Monolog can be saved to one or more storage media (later stack bubbling processing).

Installation

$ composer require Monolog/monolog

Basic usage (initial impressions)

 
  Pushhandler (New Streamhandler (' Path/to/your.log ', logger::warning));//Add Records to the log$log->warning (' Foo '); $log->error (' Bar ');

Core Concept ¶ Official explanation

Every loggerinstance has a channel (name) and a stack of handlers. Whenever you add a record to the logger, it traverses the handler stack. Each handler decides whether it fully handled the record, and if so, the propagation of the record ends there.

Each logger instance has a channel (that is, a unique name) and a stack that consists of one or more handlers. When we add a record to the logger, it iterates through the handler stack. Each handler determines whether or not to fully process the record, and if so, the processing ends (stopping bubbling). The full point here is that we want to think about, and then continue, do not want to stop.

This allows us to set up the log flexibly. For example, we have a streamhandler, which at the bottom of the stack , it will save the record to the hard disk, there is a mailhandler on it, it will be the error message is recorded when the message is sent. Handlers has a $bubble attribute that defines whether or not a handler is blocking processing when it processes the record (blocking, that is, the record is here to me even if it is done, do not bubble processing, obedient). In this example, we set the Mailhandler $bubble to false, meaning that the records will be mailhandler processed and will not bubble to Streamhandler.

Add: Here mentioned the stack, also mentioned bubbling, at first glance a bit dizzy, because we understand bubbling is the bottom-up process, the stack is a cup-like container, and then said the bottom is Streamhandler, which is mailhandler, the result is Mailhandler treatment, stop bubbling to Streamhandler, give the feeling is this bubble is from the top down, 666, this can call bubble? Hero moment: stack What, I also occasionally confuse, here again remember that the heap is FIFO ( first- In/ first- Out), think of [unsolicited] water pipes Stack is advanced ( First- In/ Last- Out), think of an n-layer color ice cream in a cup, the following is yellow, ..., the top is pink, so, You first eat pink (Mailhandler), after eating is yellow (streamhandler), in fact, this bubble is right, to be exact, this bubble in a inverted cup, so that the image of understanding.

Go on...

We can create many Logger, each Logger define a channel (e.g.:d b,request,router,... ), each channel can be combined with multiple Handler,handler can be written as either generic or non-generic. Channel, the same date and time, it is a name, in the log is a string is recorded, probably so 2016-04-25 12:33:00 the channel name record content, the specific format to see settings, can be used to identify or filter.

Each handler has a Formatter that is used to format the log. Not described in detail.

Custom log levels are not available in Monolog, only 8 RFC 5424 levels, i.e. debug, info, notice, warning, error, critical, alert, emergency. But if we really have special needs, such as classification, we can add processors to Logger, of course, before the log messages are processed. I don't think I'll ever add ' processors ' to this life.

Log level

  • DEBUG (+): detailed debug information. Detailed Debug information
  • INFO (a): Interesting events. Examples:user logs in, SQL logs. Events or information of interest, such as user logon information, SQL log information
  • NOTICE (+): normal but significant events. General but important event information
  • WARNING (a): exceptional occurrences that is not errors. Examples:use of deprecated APIs, poor use of a API, undesirable things that is not necessarily wrong.
  • ERROR (+): Runtime errors that does not require immediate action but should typically is logged and monitored.
  • CRITICAL (a): Critical conditions. Example:application component unavailable, unexpected exception.
  • ALERT (550): Action must be taken immediately. Example:entire website down, database unavailable, etc. This should trigger the SMS alerts and wake your up.
  • EMERGENCY (+): Emergency:system is unusable.

Configuring a Logger

Here are a basic setup to log to a file and to firephp on the DEBUG level:

 
  Pushhandler (New Streamhandler (__dir__. /my_app.log ', Logger::D ebug)); $logger->pushhandler (New Firephphandler ());//can now use your logger$logger-> Addinfo (' My logger is now ready ');

Let's analyze this configuration. The first step is to create the logger instance which would be a used in your code. The argument is a channel name, which are useful when you use several loggers (see below for more details about it). The first step is to create the logger instance, which is the channel name.

The logger itself does not know what to handle a record. It delegates it to some handlers. The code above registers the handlers in the stack to allow handling records in both different ways. Logger itself does not know how to handle the record, it will process the delegate to Handler[s], the above code is registered two handlers, so there are two ways to process the record.

Note The Firephphandler is called first as it's added on top of the stack. This allows-temporarily add a logger with bubbling disabled if you want to override other configured loggers. Tip: Firephphandler is first called because it is added to the top of the stack. This allows you to temporarily add a blocking Logger if you want to overwrite other logger[s] words.

Add additional data to the record

Monolog provides two ways to add additional information to a simple text message (along the easy textual message).

Using the log context

The first, the current log context, allows an array to be passed as the second parameter, and the data for that array is additional information:

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

Simple Handler (Steamhandler) will simply format the array as a string, and the feature-rich handler (firephp) can make it look better.

Using processors

The processors can be any callable method (callback). They accept $record as arguments, and then return it ($record), before returning, that is, the operation where we add extra information , where this action is to change the value of the Extrakey of the $record. Like this:

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

Monolog provides some built-in processors. Look dedicated chapter Take back what I said, I may soon use the processors.

Using channels

A channel is a good way to identify which part of the program The record is recorded in (of course, a keyword match), which is useful in large applications, such as Monologbundle in Symfony2.

Imagine that two logger share a Handler that writes a record to a file through this Handler. Using the channel allows us to identify which logger is being processed. We can simply filter this or that channel in this file.

 
  Pushhandler ($stream); $logger->pushhandler ($firephp);//Create a logger for the security-related stuff with a Different Channel$securitylogger = new Logger (' security '); $securityLogger->pushhandler ($stream); $ Securitylogger->pushhandler ($firephp);//Or clone the first one to only change the Channel$securitylogger = $logger-> ; Withname (' security ');

Custom log Format

It is easy to personalize the log in Monolog. Most Handler use the value of $record [' formatted ']. This value depends on the setting of the formatter. We can choose a predefined formatter class or write our own.

To configure a predefined formatter class, simply set it to a Handler field (property):

The default format is "y-m-d h:i:s" $dateFormat = "Y n J, g:i a";//the default output format is [%datetime%]%channel%. %level_name%:%message%%context%%extra%\n "$output ="%datetime% >%level_name% >%message%%context%%extra%\n "; $ Formatter = new Lineformatter ($output, $dateFormat);//Create a handler$stream = new Streamhandler (__dir__. ' My_app.log ', logger:debug); $stream->setformatter ($formatter);//bind it to a Logger Object$securitylogger = new Logger (' security '); $securityLogger->pushhandler ($stream);

Formatter can be reused between n Handler, and Handler can be shared between N Logger.

Handlers

Logging to file and system log (syslog)

    • Streamhandler: Logs the log to any PHP stream and uses it to record the file.
    • Rotatingfilehandler: One file per day, will automatically delete older files than $maxFiles, this is just a very casual scenario, you should use Logrotate for the high profile setups though.
    • Sysloghandler: Logging to the System log
    • Errorloghandler:logs records to PHP ' s error_log () function.

Expand ...

Send reminders and messages

See what you can understand.

    • Nativemailerhandler:sends emails using PHP ' s mail () function.
    • Swiftmailerhandler:sends emails using a Swift_mailer instance.
    • Pushoverhandler:sends Mobile notifications via the Pushover API.
    • Hipchathandler:logs Records to a hipchat chat, the using its API.
    • Flowdockhandler:logs records to a Flowdock account.
    • Slackhandler:logs records to a Slack account.
    • Mandrillhandler:sends emails via the Mandrill API using a swift_message instance.
    • Fleephookhandler:logs Records to a fleep conversation using Webhooks.
    • Ifttthandler:notifies an IFTTT trigger with the log channel, level name and message.

Logging to the specified server and network log

Then look at

Sockethandler:logs records to sockets, use this for UNIX and TCP sockets. See an example. Amqphandler:logs records to an amqpcompatible server. Requires the Php-amqpextension (1.0+). Gelfhandler:logs Records to a graylog2server. Cubehandler:logs Records to a cubeserver. Ravenhandler:logs Records to a sentryserver using Raven. Zendmonitorhandler:logs Records to the Zend Monitor present in Zend Server. Newrelichandler:logs Records to a newrelicapplication. Logglyhandler:logs Records to a logglyaccount. Rollbarhandler:logs Records to a rollbaraccount. Syslogudphandler:logs Records to a remote syslogdserver. Logentrieshandler:logs Records to a logentriesaccount.

In the development environment, using browser extensions

Load extension

Firephphandler:handler for firephp, providing inline console messages within FireBug. Chromephphandler:handler for chromephp, providing inline console messages within Chrome. Browserconsolehandler:handler to send logs to browser ' s Javascript console with no browser extension required. Most browsers supporting console API is supported. Phpconsolehandler:handler for PHP console, providing inline console and notification popup messages within Chrome.

Logging to a database

Name implies

Redishandler:logs Records to a redisserver. Mongodbhandler:handler to write records in MongoDB via a mongoextension connection. Couchdbhandler:logs records to a CouchDB server. Doctrinecouchdbhandler:logs records to a CouchDB server via the Doctrine CouchDB ODM. Elasticsearchhandler:logs Records to an Elastic Search server. Dynamodbhandler:logs records to a DynamoDB table with the AWS SDK.

Special handler.

Look slowly.

Fingerscrossedhandler:a very interesting wrapper. It takes a logger as parameter and would accumulate log records of all levels until a record exceeds the defined severity L Evel. At which point it delivers all records, including those of lower severity, to the handler it wraps. This means is until an error actually happens you won't see anything in your logs, but when it happens you'll have The full information, including debug and info records. This provides is the information you need, and only if you need it.

Deduplicationhandler:useful If you is sending notifications or emails when critical errors occur. It takes a logger as parameter and would accumulate log records of all levels until the end of the request (or flush () is C alled). At this point it delivers all records to the handler it wraps, but only if the records is unique over a given time period (60seconds by default). If the records is duplicates they is simply discarded. The main use of the critical failure like if your database are unreachable for example all your requests wil L fail and that can result in a lot of notifications being sent. Adding This handler reduces the amount of notifications to a manageable level.

Whatfailuregrouphandler:this handler extends the grouphandlerignoring exceptions raised by each child handler. This allows-ignore issues where a remote TCP connection may has died but you do not want your entire application T O Crash and may wish to continue to logs to other handlers.

Bufferhandler:this handler would buffer all the log records it receives until close () are called at which point it would cal Lhandlebatch () on the handler it wraps with all the logs messages at once. This was very useful to send a email with all records at once for example instead of have one mail for every log record.

Grouphandler:this handler groups other handlers. Every record received was sent to all the handlers it was configured with.

Filterhandler:this handler only lets records of the given levels through to the wrapped handler.

Samplinghandler:wraps around another handler and lets you sample records if you have want to store some of them.

Nullhandler:any record It can handle would be thrown away. This can is used to put on top of the existing handler stack to disable it temporarily.

Psrhandler:can is used to forward log records to an existing PSR-3 logger

Testhandler:used for testing, it records everything, it's sent to it and have accessors to read out the information.

Handlerwrapper:a Simple Handler wrapper the can inherit from to create your own wrappers easily.

Formatters

✪ for common

  • Lineformatter:formats a log record into a one-line string. ✪
  • htmlformatter:used to format log records into a human readable HTML table, mainly suitable for emails.✪
  • Normalizerformatter:normalizes objects/resources strings So a record can easily be serialized/encoded.
  • scalarformatter:used to format log records into an associative array of scalar values.
  • Jsonformatter:encodes a log record into Json.✪
  • wildfireformatter:used to format log records into the wildfire/firephp protocol, only useful for the firephphandler.
  • chromephpformatter:used to format log records into the chromephp format, only useful for the chromephphandler.
  • gelfmessageformatter:used to format log records into Gelf a message instances, only useful for the gelfhandler.
  • logstashformatter:used to format log records into Logstash event json, useful for any handler listed under inputs here.
  • elasticaformatter:used to format log records into a Elastica\document object, only useful for the elasticsearchhandler.
  • logglyformatter:used to format log records into Loggly messages, only useful for the logglyhandler.
  • flowdockformatter:used to format log records into Flowdock messages, only useful for the flowdockhandler.
  • Mongodbformatter:converts \datetime instances to \mongodate and objects recursively to arrays, only useful with the Mongo Dbhandler.

Processors

  • Psrlogmessageprocessor:processes a log record ' s message according to PSR-3 rules, replacing {foo} with the value from $co ntext[' foo '].

  • Introspectionprocessor:adds the Line/file/class/method from which, the log call originated.

  • Webprocessor:adds the current request URI, request method and client IP to a log record.

  • Memoryusageprocessor:adds the current memory usage to a log record.

  • Memorypeakusageprocessor:adds the peak memory usage to a log record.

  • Processidprocessor:adds the process ID to a log record.

  • Uidprocessor:adds a unique identifier to a log record.

  • Gitprocessor:adds the current Git branch and commits to a log record.

  • Tagprocessor:adds an array of predefined tags to a log record.

Utilities

  • Registry:the Monolog\registryclass lets you configure global loggers so can then statically access from anywhere. It is not really a best practice but can help in some older codebases or for ease of use. Monolog\registry allows us to configure global logger, and we can have global static access, although this is not a best practice, but can provide some help in some old code base or simply use it.

  • Errorhandler:the Monolog\errorhandlerclass allows you-easily register a Logger instance as an exception handler, error Handler or fatal error handler. Monolog\errorhandler allows us to register an logger instance as an exception handling handle, an error handling handle, or a fatal error handling handle.

  • Errorlevelactivationstrategy:activates a fingerscrossedhandler when a certain logs is reached. Activates Fingerscrossedhandler when a log level is reached.

  • Channellevelactivationstrategy:activates a fingerscrossedhandler when a certain log level was reached, depending on which Channel received the log record. When a log level is reached, Fingerscrossedhandler is activated, depending on which channel receives the log information.

Extending Monolog

Monolog can be fully extensible. It's easy to make logger suitable for our needs.

Write your own Handler.

Although Monolog provides a lot of built-in Handler, we may still not find the one we want, and then we'll write and use our own. Only implement Monolog\handler\handlerinterface is required.

To write a pdohandler to save the log to the database, we inherit the abstract class provided by Monolog to stick to the Don ' t rpeat yourself principle.

    
 PDO = $pdo;        Parent::__construct ($level, $bubble);                 } protected function write (array $record) {if (! $this->initialized) {             $this->initialize (); } $this->statement->execute (' channel ' = ' $record [' channel '], ' leve L ' = = $record [' Level '], ' message ' and ' $record [' formatted '], ' time ' = $record [' Datet        IME ']->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) VALUE            S (: Channel,: Level,: Message,: Time) ');  $this->initialized = true;      }    } 

You can now use this handler in logger:

$logger->pushhandler (New Pdohandler (' Sqlite:logs.sqlite '));//can now use your logger$logger-> Addinfo (' My logger is now ready ');

Monolog\handler\abstractprocessinghandler provides most of the logic required by Handler, including the use of processors and the formatting of the record (which is, the We $record [' Formatted ']instead of $record [' message ']).

  • 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.