search

Monolog是PHP的一个日志类库。相比于其他的日志类库,它有以下的特点:

  • 功能强大。可以把日志发送到文件、socket、邮箱、数据库和各种web services。
  • 遵循PSR3的接口规范。可以很轻易的替换成其他遵循同一规范的日志类库。
  • 良好的扩展性。通过Handler、Formatter和Processor这几个接口,可以对Monolog类库进行各种扩展和自定义。

基本用法

安装最新版本:

composer require monolog/monolog

要求PHP版本为5.3以上。

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');

核心概念

每一个Logger实例都包含一个频道名(channel)和handler的堆栈。当你添加一条记录时,记录会依次通过handler堆栈的处理。而每个handler也可以决定是否把记录传递到下一个堆栈里的下一个handler。

通过handler,我们可以实现一些复杂的日志操作。例如我们把StreamHandler放在堆栈的最下面,那么所有的日志记录最终都会写到硬盘文件里。同时我们把MailHandler放在堆栈的最上面,通过设置日志等级把错误日志通过邮件发送出去。Handler里有个$bubble属性,这个属性定义了handler是否拦截记录不让它流到下一个handler。所以如果我们把MailHandler的$bubble参数设置为false,则出现错误日志时,日志会通过MailHandler发送出去,而不会经过StreamHandler写到硬盘上。

Logger可以创建多个,每个都可以定义自己的频道名和handler堆栈。handler可以在多个Logger中共享。频道名会反映在日志里,方便我们查看和过滤日志记录。

如果没有指定日志格式(Formatter),Handler会使用默认的Formatter。

日志的等级不能自定义,目前使用的是RFC 5424里定义的8个等级:debug、info、notice、warning、error、critical、alert和emergency。如果对日志记录有其他的需求,可以通过Processo对日志记录添加内容。

日志等级

  • DEBUG (100): 详细的debug信息。
  • INFO (200): 关键事件。
  • NOTICE (250): 普通但是重要的事件。
  • WARNING (300): 出现非错误的异常。
  • ERROR (400): 运行时错误,但是不需要立刻处理。
  • CRITICA (500): 严重错误。
  • EMERGENCY (600): 系统不可用。

用法详解

多个handler

php<?phpuse Monolog\Logger;use Monolog\Handler\StreamHandler;use Monolog\Handler\FirePHPHandler;// 创建Logger实例$logger = new Logger('my_logger');// 添加handler$logger->pushHandler(new StreamHandler(__DIR__.'/my_app.log', Logger::DEBUG));$logger->pushHandler(new FirePHPHandler());// 开始使用$logger->addInfo('My logger is now ready');

第一步我们先创建一个Logger实例,传入的是频道名,这个频道名可以用于区分多个Logger实例。

实例本身并不知道如何处理日志记录,它是通过handler进行处理的。handler可以设置多个,例如上面的例子设置了两个handler,可以对日志记录进行两种不同方式的处理。

需要注意的是,由于handler是采用堆栈的方式保存,所以后面添加的handler位于栈顶,会首先被调用。

添加额外的数据

Monolog有两种方式对日志添加额外的信息。

使用上下文

第一个方法是使用$context参数,传入一个数组:

php<?php$logger->addInfo('Adding a new user', array('username' => 'Seldaek'));

使用processor

第二个方法是使用processor。processor可以是任何可调用的方法,这些方法把日志记录作为参数,然后经过处理修改extra部分后返回。

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

Processor不一定要绑定在Logger实例上,也可以绑定到某个具体的handler上。使用handler实例的pushProcessor方法进行绑定。

频道的使用

使用频道名可以对日志进行分类,这在大型的应用上是很有用的。通过频道名,可以很容易的对日志记录进行刷选。

例如我们想在同一个日志文件里记录不同模块的日志,我们可以把相同的handler绑定到不同的Logger实例上,这些实例使用不同的频道名:

php<?phpuse Monolog\Logger;use Monolog\Handler\StreamHandler;use Monolog\Handler\FirePHPHandler;// 创建handler$stream = new StreamHandler(__DIR__.'/my_app.log', Logger::DEBUG);$firephp = new FirePHPHandler();// 创建应用的主要logger$logger = new Logger('my_logger');$logger->pushHandler($stream);$logger->pushHandler($firephp);// 通过不同的频道名创建一个用于安全相关的logger$securityLogger = new Logger('security');$securityLogger->pushHandler($stream);$securityLogger->pushHandler($firephp);

Handler

Monolog内置很多很实用的handler,它们几乎囊括了各种的使用场景,这里介绍一些使用的:
StreamHandler:把记录写进PHP流,主要用于日志文件。
SyslogHandler:把记录写进syslog。
ErrorLogHandler:把记录写进PHP错误日志。
NativeMailerHandler:使用PHP的mail()函数发送日志记录。
SocketHandler:通过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);// Now add the handler$logger->pushHandler($handler, Logger::DEBUG);// You can now use your logger$logger->addInfo('My logger is now ready');

AmqpHandler:把记录写进兼容amqp协议的服务。
BrowserConsoleHandler:把日志记录写到浏览器的控制台。由于是使用浏览器的console对象,需要看浏览器是否支持。
RedisHandler:把记录写进Redis。
MongoDBHandler:把记录写进Mongo。
ElasticSearchHandler:把记录写到ElasticSearch服务。
BufferHandler:允许我们把日志记录缓存起来一次性进行处理。

更多的Handler请看https://github.com/Seldaek/monolog#handlers。

Formatter

同样的,这里介绍几个自带的Formatter:
LineFormatter:把日志记录格式化成一行字符串。
HtmlFormatter:把日志记录格式化成HTML表格,主要用于邮件。
JsonFormatter:把日志记录编码成JSON格式。
LogstashFormatter:把日志记录格式化成logstash的事件JSON格式。
ElasticaFormatter:把日志记录格式化成ElasticSearch使用的数据格式。

更多的Formatter请看https://github.com/Seldaek/monolog#formatters。

Processor

前面说过,Processor可以为日志记录添加额外的信息,Monolog也提供了一些很实用的processor:
IntrospectionProcessor:增加当前脚本的文件名和类名等信息。
WebProcessor:增加当前请求的URI、请求方法和访问IP等信息。
MemoryUsageProcessor:增加当前内存使用情况信息。
MemoryPeakUsageProcessor:增加内存使用高峰时的信息。

更多的Processor请看https://github.com/Seldaek/monolog#processors。

扩展handler

Monolog内置了很多handler,但是并不是所有场景都能覆盖到,有时需要自己去定制handler。写一个handler并不难,只需要实现Monolog\Handler\HandlerInterface这个接口即可。

下面这个例子实现了把日志记录写到数据库里。我们不需要把接口里的方法全部实现一次,可以直接使用Monolog提供的抽象类AbstractProcessingHandler进行继承,实现里面的write方法即可。

php<?phpuse Monolog\Logger;use Monolog\Handler\AbstractProcessingHandler;class PDOHandler extends AbstractProcessingHandler{    private $initialized = false;    private $pdo;    private $statement;    public function __construct(PDO $pdo, $level = Logger::DEBUG, $bubble = true)    {        $this->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)'        );    }}

然后我们就可以使用它了:

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

参考

https://github.com/Seldaek/monolog

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP's Purpose: Building Dynamic WebsitesPHP's Purpose: Building Dynamic WebsitesApr 15, 2025 am 12:18 AM

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP: Handling Databases and Server-Side LogicPHP: Handling Databases and Server-Side LogicApr 15, 2025 am 12:15 AM

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

How do you prevent SQL Injection in PHP? (Prepared statements, PDO)How do you prevent SQL Injection in PHP? (Prepared statements, PDO)Apr 15, 2025 am 12:15 AM

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.

PHP and Python: Code Examples and ComparisonPHP and Python: Code Examples and ComparisonApr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP in Action: Real-World Examples and ApplicationsPHP in Action: Real-World Examples and ApplicationsApr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: Creating Interactive Web Content with EasePHP: Creating Interactive Web Content with EaseApr 14, 2025 am 12:15 AM

PHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.

PHP and Python: Comparing Two Popular Programming LanguagesPHP and Python: Comparing Two Popular Programming LanguagesApr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

The Enduring Relevance of PHP: Is It Still Alive?The Enduring Relevance of PHP: Is It Still Alive?Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor