用于PHP 5.3+的日志组件:Monolog

jopen 9年前

Monolog是一个PHP日志组件。能够将你的日志发送至文件,sockets,inboxes,数据库和各种Web服务。
使用:

<?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 records to the log  $log->addWarning('Foo');  $log->addError('Bar');

日志级别

Monolog 支持由RFC 5424定义的日志级别:

  • DEBUG (100): Detailed debug information.

  • INFO (200): Interesting events. Examples: User logs in, SQL logs.

  • NOTICE (250): Normal but significant events.

  • WARNING (300): Exceptional occurrences that are not errors. Examples: Use of deprecated APIs, poor use of an API, undesirable things that are not necessarily wrong.

  • ERROR (400): Runtime errors that do not require immediate action but should typically be logged and monitored.

  • CRITICAL (500): 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 you up.

  • EMERGENCY (600): Emergency: system is unusable.

Handlers

Log to files and syslog

  • StreamHandler: Logs records into any PHP stream, use this for log files.
  • RotatingFileHandler: Logs records to a file and creates one logfile per day. It will also delete files older than $maxFiles. You should uselogrotate for high profile setups though, this is just meant as a quick and dirty solution.
  • SyslogHandler: Logs records to the syslog.
  • ErrorLogHandler: Logs records to PHP'serror_log() function.

Send alerts and emails

  • NativeMailerHandler: Sends emails using PHP'smail() function.
  • SwiftMailerHandler: Sends emails using a Swift_Mailer instance.
  • PushoverHandler: Sends mobile notifications via the Pushover API.
  • HipChatHandler: Logs records to a HipChat chat room 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.

Log specific servers and networked logging

  • SocketHandler: Logs records to sockets, use this for UNIX and TCP sockets. See an example.
  • AmqpHandler: Logs records to an amqp compatible server. Requires the php-amqp extension (1.0+).
  • GelfHandler: Logs records to a Graylog2 server.
  • CubeHandler: Logs records to a Cube server.
  • RavenHandler: Logs records to a Sentry server usingraven.
  • ZendMonitorHandler: Logs records to the Zend Monitor present in Zend Server.
  • NewRelicHandler: Logs records to a NewRelic application.
  • LogglyHandler: Logs records to a Loggly account.
  • RollbarHandler: Logs records to a Rollbar account.
  • SyslogUdpHandler: Logs records to a remote Syslogd server.
  • LogEntriesHandler: Logs records to a LogEntries account.

Logging in development

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

Log to databases

  • RedisHandler: Logs records to a redis server.
  • MongoDBHandler: Handler to write records in MongoDB via aMongo extension 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.

Wrappers / Special Handlers

  • FingersCrossedHandler: A very interesting wrapper. It takes a logger as parameter and will accumulate log records of all levels until a record exceeds the defined severity level. At which point it delivers all records, including those of lower severity, to the handler it wraps. This means that until an error actually happens you will not see anything in your logs, but when it happens you will have the full information, including debug and info records. This provides you with all the information you need, but only when you need it.
  • NullHandler: Any record it can handle will be thrown away. This can be used to put on top of an existing handler stack to disable it temporarily.
  • BufferHandler: This handler will buffer all the log records it receives until close() is called at which point it will call handleBatch() on the handler it wraps with all the log messages at once. This is very useful to send an email with all records at once for example instead of having one mail for every log record.
  • GroupHandler: This handler groups other handlers. Every record received is sent to all the handlers it is configured with.
  • FilterHandler: This handler only lets records of the given levels through to the wrapped handler.
  • TestHandler: Used for testing, it records everything that is sent to it and has accessors to read out the information.
  • WhatFailureGroupHandler: This handler extends the GroupHandler ignoring exceptions raised by each child handler. This allows you to ignore issues where a remote tcp connection may have died but you do not want your entire application to crash and may wish to continue to log to other handlers.

格式

  • 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 down to 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 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 an 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.

Processors

  • 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 commit to a log record.
  • TagProcessor: Adds an array of predefined tags to a log record.

Utilities

  • Registry: The Monolog\Registry class lets you configure global loggers that you 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.
  • ErrorHandler: The Monolog\ErrorHandler class allows you to easily register a Logger instance as an exception handler, error handler or fatal error handler.
  • ErrorLevelActivationStrategy: Activates a FingersCrossedHandler when a certain log level is reached.
  • ChannelLevelActivationStrategy: Activates a FingersCrossedHandler when a certain log level is reached, depending on which channel received the log record.

About

Requirements

  • Monolog works with PHP 5.3 or above, and is also tested to work with HHVM.

框架集成

  • Frameworks and libraries using PSR-3 can be used very easily with Monolog since it implements the interface.
  • Symfony2 comes out of the box with Monolog.
  • Silex comes out of the box with Monolog.
  • Laravel 4 comes out of the box with Monolog.
  • PPI comes out of the box with Monolog.
  • CakePHP is usable with Monolog via the cakephp-monolog plugin.
  • Slim is usable with Monolog via the Slim-Monolog log writer.
  • XOOPS 2.6 comes out of the box with Monolog.
  • Aura.Web_Project comes out of the box with Monolog.

项目主页:http://www.open-open.com/lib/view/home/1415157687293